blob: 68594661b0d67d8a69e8b325fa70b9572d44a94b [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 Wu6d844112018-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>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#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"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080070#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070073#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080074#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
116class ConditionalLock {
117public:
118 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
119 if (lock) {
120 mMutex.lock();
121 }
122 }
123 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
124private:
125 Mutex& mMutex;
126 bool mLocked;
127};
128} // namespace anonymous
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130// ---------------------------------------------------------------------------
131
Mathias Agopian99b49842011-06-27 16:05:52 -0700132const String16 sHardwareTest("android.permission.HARDWARE_TEST");
133const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
134const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
135const String16 sDump("android.permission.DUMP");
136
137// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800138int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
139int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700140int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700141bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800142uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800143bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800144bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800145int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800146// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600147bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700148
Kalle Raitaa099a242017-01-11 11:17:29 -0800149
150std::string getHwcServiceName() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.hwc_service_name", value, "default");
153 ALOGI("Using HWComposer service: '%s'", value);
154 return std::string(value);
155}
156
157bool useTrebleTestingOverride() {
158 char value[PROPERTY_VALUE_MAX] = {};
159 property_get("debug.sf.treble_testing_override", value, "false");
160 ALOGI("Treble testing override: '%s'", value);
161 return std::string(value) == "true";
162}
163
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800164std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
165 switch(displayColorSetting) {
166 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700167 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800168 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700169 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800170 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700171 return std::string("Enhanced");
172 default:
173 return std::string("Unknown ") +
174 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176}
177
Lloyd Pique09594832018-01-22 17:48:03 -0800178NativeWindowSurface::~NativeWindowSurface() = default;
179
180namespace impl {
181
182class NativeWindowSurface final : public android::NativeWindowSurface {
183public:
184 static std::unique_ptr<android::NativeWindowSurface> create(
185 const sp<IGraphicBufferProducer>& producer) {
186 return std::make_unique<NativeWindowSurface>(producer);
187 }
188
189 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
190 : surface(new Surface(producer, false)) {}
191
192 ~NativeWindowSurface() override = default;
193
194private:
195 sp<ANativeWindow> getNativeWindow() const override { return surface; }
196
197 void preallocateBuffers() override { surface->allocateBuffers(); }
198
199 sp<Surface> surface;
200};
201
202} // namespace impl
203
David Sodmanbc815282017-11-05 18:57:52 -0800204SurfaceFlingerBE::SurfaceFlingerBE()
205 : mHwcServiceName(getHwcServiceName()),
206 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800207 mFrameBuckets(),
208 mTotalTime(0),
209 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800210 mComposerSequenceId(0) {
211}
212
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800213SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800214 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700216 mTransactionPending(false),
217 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700218 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700219 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700220 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800222 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800224 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800225 mAnimCompositionPending(false),
Chia-I Wuad8d8272018-06-26 10:18:18 +0800226 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700228 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700229 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700230 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700231 mDebugInSwapBuffers(0),
232 mLastSwapBufferTime(0),
233 mDebugInTransaction(0),
234 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Jorim Jaggie203e042018-06-19 15:57:08 +0200335 property_get("debug.sf.early_phase_offset_ns", value, "-1");
336 const int earlySfOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
339 const int earlyGlSfOffsetNs = atoi(value);
340
341 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
342 const int earlyAppOffsetNs = atoi(value);
343
344 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
345 const int earlyGlAppOffsetNs = atoi(value);
346
347 const VSyncModulator::Offsets earlyOffsets =
348 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
349 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
350 const VSyncModulator::Offsets earlyGlOffsets =
351 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
352 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
353 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
354 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700355
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376SurfaceFlinger::~SurfaceFlinger()
377{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Dan Stozac7014012014-02-14 15:03:43 -0800380void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381{
382 // the window manager died on us. prepare its eulogy.
383
Andy McFadden13a082e2012-08-24 10:16:42 -0700384 // restore initial conditions (default device unblank, etc)
385 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386
387 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700388 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389}
390
Robert Carr1db73f62016-12-21 12:58:51 -0800391static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700392 status_t err = client->initCheck();
393 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 }
Robert Carr1db73f62016-12-21 12:58:51 -0800396 return nullptr;
397}
398
399sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
400 return initClient(new Client(this));
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
404 const sp<IGraphicBufferProducer>& gbp) {
405 if (authenticateSurfaceTexture(gbp) == false) {
406 return nullptr;
407 }
408 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
409 if (layer == nullptr) {
410 return nullptr;
411 }
412
413 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700416sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
417 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418{
419 class DisplayToken : public BBinder {
420 sp<SurfaceFlinger> flinger;
421 virtual ~DisplayToken() {
422 // no more references, this display must be terminated
423 Mutex::Autolock _l(flinger->mStateLock);
424 flinger->mCurrentState.displays.removeItem(this);
425 flinger->setTransactionFlags(eDisplayTransactionNeeded);
426 }
427 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700428 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429 : flinger(flinger) {
430 }
431 };
432
433 sp<BBinder> token = new DisplayToken(this);
434
435 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700436 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700437 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800439 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 return token;
441}
442
Jesse Hall6c913be2013-08-08 12:15:49 -0700443void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
444 Mutex::Autolock _l(mStateLock);
445
446 ssize_t idx = mCurrentState.displays.indexOfKey(display);
447 if (idx < 0) {
448 ALOGW("destroyDisplay: invalid display token");
449 return;
450 }
451
452 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
453 if (!info.isVirtualDisplay()) {
454 ALOGE("destroyDisplay called for non-virtual display");
455 return;
456 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800457 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 mCurrentState.displays.removeItemsAt(idx);
459 setTransactionFlags(eDisplayTransactionNeeded);
460}
461
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700463 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800465 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 }
Jesse Hall692c7232012-11-08 15:41:56 -0800467 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468}
469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470void SurfaceFlinger::bootFinished()
471{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700472 if (mStartPropertySetThread->join() != NO_ERROR) {
473 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475 const nsecs_t now = systemTime();
476 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000477 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700478
479 // wait patiently for the window manager death
480 const String16 name("window");
481 sp<IBinder> window(defaultServiceManager()->getService(name));
482 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700484 }
485
Steven Thomas050b2c82017-03-06 11:45:16 -0800486 if (mVrFlinger) {
487 mVrFlinger->OnBootFinished();
488 }
489
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700490 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700491 // formerly we would just kill the process, but we now ask it to exit so it
492 // can choose where to stop the animation.
493 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700494
495 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
496 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
497 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700498
Thierry Strudel2924d012017-08-14 15:19:37 -0700499 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700500 readPersistentProperties();
Chia-I Wuad8d8272018-06-26 10:18:18 +0800501 mBootStage = BootStage::FINISHED;
Romain Guy11d63f42017-07-20 12:47:14 -0700502 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700503 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504}
505
Mathias Agopian3f844832013-08-07 21:24:32 -0700506void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700507 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800508 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700509 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700510 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800511 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
512 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700513 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700514 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700515 return true;
516 }
517 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700518 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700519}
520
Lloyd Piquee83f9312018-02-01 12:53:17 -0800521class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700523 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 const char* name) :
525 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700526 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700527 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000528 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
529 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700530 mDispSync(dispSync),
531 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532 mVsyncMutex(),
533 mPhaseOffset(phaseOffset),
534 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537
Lloyd Piquee83f9312018-02-01 12:53:17 -0800538 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000541 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 static_cast<DispSync::Callback*>(this));
543 if (err != NO_ERROR) {
544 ALOGE("error registering vsync callback: %s (%d)",
545 strerror(-err), err);
546 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700547 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 } else {
549 status_t err = mDispSync->removeEventListener(
550 static_cast<DispSync::Callback*>(this));
551 if (err != NO_ERROR) {
552 ALOGE("error unregistering vsync callback: %s (%d)",
553 strerror(-err), err);
554 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700555 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700557 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558 }
559
Lloyd Piquee83f9312018-02-01 12:53:17 -0800560 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700562 mCallback = callback;
563 }
564
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700566 Mutex::Autolock lock(mVsyncMutex);
567
568 // Normalize phaseOffset to [0, period)
569 auto period = mDispSync->getPeriod();
570 phaseOffset %= period;
571 if (phaseOffset < 0) {
572 // If we're here, then phaseOffset is in (-period, 0). After this
573 // operation, it will be in (0, period)
574 phaseOffset += period;
575 }
576 mPhaseOffset = phaseOffset;
577
578 // If we're not enabled, we don't need to mess with the listeners
579 if (!mEnabled) {
580 return;
581 }
582
Dan Stoza2713c302018-03-28 17:07:36 -0700583 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
584 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700585 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700586 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700587 strerror(-err), err);
588 }
589 }
590
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591private:
592 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 callback = mCallback;
597
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700598 if (mTraceVsync) {
599 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700600 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700601 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 }
603
Peiyong Lin566a3b42018-01-09 18:22:43 -0800604 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 callback->onVSyncEvent(when);
606 }
607 }
608
Tim Murray4a4e4a22016-04-19 16:29:23 +0000609 const char* const mName;
610
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611 int mValue;
612
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700613 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700614 const String8 mVsyncOnLabel;
615 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700616
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700618
619 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700621
622 Mutex mVsyncMutex; // Protects the following
623 nsecs_t mPhaseOffset;
624 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700625};
626
Lloyd Piquee83f9312018-02-01 12:53:17 -0800627class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700628public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800629 InjectVSyncSource() = default;
630 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700631
Lloyd Piquee83f9312018-02-01 12:53:17 -0800632 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700633 std::lock_guard<std::mutex> lock(mCallbackMutex);
634 mCallback = callback;
635 }
636
Lloyd Piquee83f9312018-02-01 12:53:17 -0800637 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700638 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700639 if (mCallback) {
640 mCallback->onVSyncEvent(when);
641 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700642 }
643
Lloyd Piquee83f9312018-02-01 12:53:17 -0800644 void setVSyncEnabled(bool) override {}
645 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700646
647private:
648 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800649 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700650};
651
Wei Wangf9b05ee2017-07-19 20:59:39 -0700652// Do not call property_set on main thread which will be blocked by init
653// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700654void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700655 ALOGI( "SurfaceFlinger's main thread ready to run. "
656 "Initializing graphics H/W...");
657
Thierry Strudel2924d012017-08-14 15:19:37 -0700658 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900659
Steven Thomasb02664d2017-07-26 18:48:28 -0700660 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661
Steven Thomasb02664d2017-07-26 18:48:28 -0700662 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800663 mEventThreadSource =
664 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
665 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800666 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
667 [this]() { resyncWithRateLimit(); },
668 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800669 "appEventThread");
670 mSfEventThreadSource =
671 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
672 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800673
Lloyd Pique24b0a482018-03-09 18:52:26 -0800674 mSFEventThread =
675 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
676 [this]() { resyncWithRateLimit(); },
677 [this](nsecs_t timestamp) {
678 mInterceptor->saveVSyncEvent(timestamp);
679 },
680 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800681 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200682 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683
Steven Thomasb02664d2017-07-26 18:48:28 -0700684 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800685 getBE().mRenderEngine =
686 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
687 hasWideColorDisplay
688 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
689 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800690 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700691
692 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
693 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800694 getBE().mHwc.reset(
695 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700696 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800697 // Process any initial hotplug and resulting display changes.
698 processDisplayHotplugEventsLocked();
699 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
700 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800701
Lloyd Piquefcd86612017-12-14 17:15:36 -0800702 // make the default display GLContext current so that we can create textures
703 // when creating Layers (which may happens before we render something)
704 getDefaultDisplayDeviceLocked()->makeCurrent();
705
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (useVrFlinger) {
707 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700708 // This callback is called from the vr flinger dispatch thread. We
709 // need to call signalTransaction(), which requires holding
710 // mStateLock when we're not on the main thread. Acquiring
711 // mStateLock from the vr flinger dispatch thread might trigger a
712 // deadlock in surface flinger (see b/66916578), so post a message
713 // to be handled on the main thread instead.
714 sp<LambdaMessage> message = new LambdaMessage([=]() {
715 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
716 mVrFlingerRequestsDisplay = requestDisplay;
717 signalTransaction();
718 });
719 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800720 };
David Sodman105b7dc2017-11-04 20:28:14 -0700721 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
722 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800723 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800724 if (!mVrFlinger) {
725 ALOGE("Failed to start vrflinger");
726 }
727 }
728
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800729 mEventControlThread = std::make_unique<impl::EventControlThread>(
730 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700731
Mathias Agopian92a979a2012-08-02 18:32:23 -0700732 // initialize our drawing state
733 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700734
Andy McFadden13a082e2012-08-24 10:16:42 -0700735 // set initial conditions (e.g. unblank default device)
736 initializeDisplays();
737
David Sodmanbc815282017-11-05 18:57:52 -0800738 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700739
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740 // Inform native graphics APIs whether the present timestamp is supported:
741 if (getHwComposer().hasCapability(
742 HWC2::Capability::PresentFenceIsNotReliable)) {
743 mStartPropertySetThread = new StartPropertySetThread(false);
744 } else {
745 mStartPropertySetThread = new StartPropertySetThread(true);
746 }
747
748 if (mStartPropertySetThread->Start() != NO_ERROR) {
749 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751
Chia-I Wu6d844112018-06-27 07:17:41 +0800752 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
753 // is used to saturate legacy sRGB content. However, to make sure the same color under
754 // Display P3 will be saturated to the same color, we intentionally break the API spec
755 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
756 // such saturation matrix on Display P3 is understood fully, the API should always return
757 // identify matrix.
758 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800759 Dataspace::SRGB_LINEAR);
760
Chia-I Wu6d844112018-06-27 07:17:41 +0800761 // we will apply this on Display P3.
762 if (mEnhancedSaturationMatrix != mat4()) {
763 ColorSpace srgb(ColorSpace::sRGB());
764 ColorSpace displayP3(ColorSpace::DisplayP3());
765 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
766 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
767 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
768 }
769
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700771}
772
Romain Guy11d63f42017-07-20 12:47:14 -0700773void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700774 Mutex::Autolock _l(mStateLock);
775
Romain Guy11d63f42017-07-20 12:47:14 -0700776 char value[PROPERTY_VALUE_MAX];
777
778 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800779 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700780 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800781 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100782
783 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700784 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700785}
786
Mathias Agopiana67e4182012-06-19 17:26:12 -0700787void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800788 // Start boot animation service by setting a property mailbox
789 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700790 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800791 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700792 if (mStartPropertySetThread->join() != NO_ERROR) {
793 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800794 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700795}
796
Mathias Agopian875d8e12013-06-07 15:35:48 -0700797size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800798 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700799}
800
Mathias Agopian875d8e12013-06-07 15:35:48 -0700801size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800802 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700803}
804
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800806
Jamie Gennis582270d2011-08-17 18:19:00 -0700807bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800808 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800809 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800810 return authenticateSurfaceTextureLocked(bufferProducer);
811}
812
813bool SurfaceFlinger::authenticateSurfaceTextureLocked(
814 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800815 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800816 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800817}
818
Brian Anderson6b376712017-04-04 10:51:39 -0700819status_t SurfaceFlinger::getSupportedFrameTimestamps(
820 std::vector<FrameEvent>* outSupported) const {
821 *outSupported = {
822 FrameEvent::REQUESTED_PRESENT,
823 FrameEvent::ACQUIRE,
824 FrameEvent::LATCH,
825 FrameEvent::FIRST_REFRESH_START,
826 FrameEvent::LAST_REFRESH_START,
827 FrameEvent::GPU_COMPOSITION_DONE,
828 FrameEvent::DEQUEUE_READY,
829 FrameEvent::RELEASE,
830 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700831 ConditionalLock _l(mStateLock,
832 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700833 if (!getHwComposer().hasCapability(
834 HWC2::Capability::PresentFenceIsNotReliable)) {
835 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
836 }
837 return NO_ERROR;
838}
839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
841 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 return BAD_VALUE;
844 }
845
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500846 if (!display.get())
847 return NAME_NOT_FOUND;
848
Jesse Hall692c7232012-11-08 15:41:56 -0800849 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700850 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800851 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700852 type = i;
853 break;
854 }
855 }
856
857 if (type < 0) {
858 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700859 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700860
Mathias Agopian8b736f12012-08-13 17:54:26 -0700861 // TODO: Not sure if display density should handled by SF any longer
862 class Density {
863 static int getDensityFromProperty(char const* propName) {
864 char property[PROPERTY_VALUE_MAX];
865 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800866 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700867 density = atoi(property);
868 }
869 return density;
870 }
871 public:
872 static int getEmuDensity() {
873 return getDensityFromProperty("qemu.sf.lcd_density"); }
874 static int getBuildDensity() {
875 return getDensityFromProperty("ro.sf.lcd_density"); }
876 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700877
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700879
Steven Thomas6d8110b2017-08-31 18:24:21 -0700880 ConditionalLock _l(mStateLock,
881 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 DisplayInfo info = DisplayInfo();
884
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 float xdpi = hwConfig->getDpiX();
886 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700887
888 if (type == DisplayDevice::DISPLAY_PRIMARY) {
889 // The density of the device is provided by a build property
890 float density = Density::getBuildDensity() / 160.0f;
891 if (density == 0) {
892 // the build doesn't provide a density -- this is wrong!
893 // use xdpi instead
894 ALOGE("ro.sf.lcd_density must be defined as a build property");
895 density = xdpi / 160.0f;
896 }
897 if (Density::getEmuDensity()) {
898 // if "qemu.sf.lcd_density" is specified, it overrides everything
899 xdpi = ydpi = density = Density::getEmuDensity();
900 density /= 160.0f;
901 }
902 info.density = density;
903
904 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700905 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800906 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907 } else {
908 // TODO: where should this value come from?
909 static const int TV_DENSITY = 213;
910 info.density = TV_DENSITY / 160.0f;
911 info.orientation = 0;
912 }
913
Dan Stoza9e56aa02015-11-02 13:00:03 -0800914 info.w = hwConfig->getWidth();
915 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 info.xdpi = xdpi;
917 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900919 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920
Andy McFadden91b2ca82014-06-13 14:04:23 -0700921 // This is how far in advance a buffer must be queued for
922 // presentation at a given time. If you want a buffer to appear
923 // on the screen at time N, you must submit the buffer before
924 // (N - presentationDeadline).
925 //
926 // Normally it's one full refresh period (to give SF a chance to
927 // latch the buffer), but this can be reduced by configuring a
928 // DispSync offset. Any additional delays introduced by the hardware
929 // composer or panel must be accounted for here.
930 //
931 // We add an additional 1ms to allow for processing time and
932 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800934 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700935
936 // All non-virtual displays are currently considered secure.
937 info.secure = true;
938
Iris Chang7501ed62018-04-30 14:45:42 +0800939 if (type == DisplayDevice::DISPLAY_PRIMARY &&
940 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
941 std::swap(info.w, info.h);
942 }
943
Michael Wright28f24d02016-07-12 13:30:53 -0700944 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700945 }
946
Dan Stoza7f7da322014-05-02 15:26:25 -0700947 return NO_ERROR;
948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800950status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700951 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800952 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700953 return BAD_VALUE;
954 }
955
956 // FIXME for now we always return stats for the primary display
957 memset(stats, 0, sizeof(*stats));
958 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
959 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
960 return NO_ERROR;
961}
962
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800964 if (display == nullptr) {
965 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800966 return BAD_VALUE;
967 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700968
969 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800970 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700971 return device->getActiveConfig();
972 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700973
Dan Stoza24a42e92015-03-09 10:04:11 -0700974 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700975}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700976
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
978 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
979 this);
980 int32_t type = hw->getDisplayType();
981 int currentMode = hw->getActiveConfig();
982
983 if (mode == currentMode) {
984 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
985 return;
986 }
987
988 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
989 ALOGW("Trying to set config for virtual display");
990 return;
991 }
992
993 hw->setActiveConfig(mode);
994 getHwComposer().setActiveConfig(type, mode);
995}
996
997status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
998 class MessageSetActiveConfig: public MessageBase {
999 SurfaceFlinger& mFlinger;
1000 sp<IBinder> mDisplay;
1001 int mMode;
1002 public:
1003 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1004 int mode) :
1005 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1006 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001007 Vector<DisplayInfo> configs;
1008 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001009 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001010 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001011 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001012 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001013 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001014 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001015 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001017 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001018 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1019 ALOGW("Attempt to set active config = %d for virtual display",
1020 mMode);
1021 } else {
1022 mFlinger.setActiveConfigInternal(hw, mMode);
1023 }
1024 return true;
1025 }
1026 };
1027 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1028 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001029 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001030}
Michael Wright28f24d02016-07-12 13:30:53 -07001031status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001032 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001033 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1034 return BAD_VALUE;
1035 }
1036
1037 if (!display.get()) {
1038 return NAME_NOT_FOUND;
1039 }
1040
1041 int32_t type = NAME_NOT_FOUND;
1042 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1043 if (display == mBuiltinDisplays[i]) {
1044 type = i;
1045 break;
1046 }
1047 }
1048
1049 if (type < 0) {
1050 return type;
1051 }
1052
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001054 {
1055 ConditionalLock _l(mStateLock,
1056 std::this_thread::get_id() != mMainThreadId);
1057 modes = getHwComposer().getColorModes(type);
1058 }
Michael Wright28f24d02016-07-12 13:30:53 -07001059 outColorModes->clear();
1060 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1061
1062 return NO_ERROR;
1063}
1064
Peiyong Lina52f0292018-03-14 17:26:31 -07001065ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001067 if (device != nullptr) {
1068 return device->getActiveColorMode();
1069 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001071}
1072
1073void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001074 ColorMode mode, Dataspace dataSpace,
1075 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001076 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001078 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001079 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001080
Peiyong Lin38e9a562018-04-10 16:24:20 -07001081 if (mode == currentMode && dataSpace == currentDataSpace &&
1082 renderIntent == currentRenderIntent) {
1083 return;
1084 }
1085
1086 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1087 ALOGW("Trying to set config for virtual display");
1088 return;
1089 }
1090
1091 hw->setActiveColorMode(mode);
1092 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001093 hw->setActiveRenderIntent(renderIntent);
1094 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1095
1096 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1097 decodeColorMode(mode).c_str(), mode,
1098 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1099 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001100}
1101
1102
1103status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001104 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001105 class MessageSetActiveColorMode: public MessageBase {
1106 SurfaceFlinger& mFlinger;
1107 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001108 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001109 public:
1110 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001111 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001112 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1113 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001114 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001115 mFlinger.getDisplayColorModes(mDisplay, &modes);
1116 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001117 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001118 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1119 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001120 return true;
1121 }
1122 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1123 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001124 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1125 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001126 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001127 ALOGW("Attempt to set active color mode %s %d for virtual display",
1128 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001129 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001130 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1131 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001132 }
1133 return true;
1134 }
1135 };
1136 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1137 postMessageSync(msg);
1138 return NO_ERROR;
1139}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001140
Svetoslavd85084b2014-03-20 10:28:31 -07001141status_t SurfaceFlinger::clearAnimationFrameStats() {
1142 Mutex::Autolock _l(mStateLock);
1143 mAnimFrameTracker.clearStats();
1144 return NO_ERROR;
1145}
1146
1147status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1148 Mutex::Autolock _l(mStateLock);
1149 mAnimFrameTracker.getStats(outStats);
1150 return NO_ERROR;
1151}
1152
Dan Stozac4f471e2016-03-24 09:31:08 -07001153status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1154 HdrCapabilities* outCapabilities) const {
1155 Mutex::Autolock _l(mStateLock);
1156
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001157 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 if (displayDevice == nullptr) {
1159 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1160 return BAD_VALUE;
1161 }
1162
Peiyong Linfb069302018-04-25 14:34:31 -07001163 // At this point the DisplayDeivce should already be set up,
1164 // meaning the luminance information is already queried from
1165 // hardware composer and stored properly.
1166 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1167 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1168 capabilities.getDesiredMaxLuminance(),
1169 capabilities.getDesiredMaxAverageLuminance(),
1170 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001171
1172 return NO_ERROR;
1173}
1174
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1177 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179 if (mInjectVSyncs == enable) {
1180 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182
1183 if (enable) {
1184 ALOGV("VSync Injections enabled");
1185 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001186 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001187 mInjectorEventThread = std::make_unique<
1188 impl::EventThread>(mVSyncInjector.get(),
1189 [this]() { resyncWithRateLimit(); },
1190 impl::EventThread::InterceptVSyncsCallback(),
1191 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001192 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001193 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 } else {
1195 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001196 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 }
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 });
1201 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 return NO_ERROR;
1203}
1204
1205status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001206 Mutex::Autolock _l(mStateLock);
1207
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208 if (!mInjectVSyncs) {
1209 ALOGE("VSync Injections not enabled");
1210 return BAD_VALUE;
1211 }
1212 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1213 ALOGV("Injecting VSync inside SurfaceFlinger");
1214 mVSyncInjector->onInjectSyncEvent(when);
1215 }
1216 return NO_ERROR;
1217}
1218
Lloyd Pique755e3192018-01-31 16:46:15 -08001219status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1220 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001221 IPCThreadState* ipc = IPCThreadState::self();
1222 const int pid = ipc->getCallingPid();
1223 const int uid = ipc->getCallingUid();
1224 if ((uid != AID_SHELL) &&
1225 !PermissionCache::checkPermission(sDump, pid, uid)) {
1226 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1227 return PERMISSION_DENIED;
1228 }
1229
1230 // Try to acquire a lock for 1s, fail gracefully
1231 const status_t err = mStateLock.timedLock(s2ns(1));
1232 const bool locked = (err == NO_ERROR);
1233 if (!locked) {
1234 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1235 return TIMED_OUT;
1236 }
1237
1238 outLayers->clear();
1239 mCurrentState.traverseInZOrder([&](Layer* layer) {
1240 outLayers->push_back(layer->getLayerDebugInfo());
1241 });
1242
1243 mStateLock.unlock();
1244 return NO_ERROR;
1245}
1246
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001247// ----------------------------------------------------------------------------
1248
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001249sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1250 ISurfaceComposer::VsyncSource vsyncSource) {
1251 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1252 return mSFEventThread->createEventConnection();
1253 } else {
1254 return mEventThread->createEventConnection();
1255 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001256}
1257
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259
1260void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001261 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001265 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001269 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001270}
1271
1272void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001273 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001274 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001275}
1276
1277status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001278 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001279 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001280}
1281
1282status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001283 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001284 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001285 if (res == NO_ERROR) {
1286 msg->wait();
1287 }
1288 return res;
1289}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001290
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001291void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001292 do {
1293 waitForEvent();
1294 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001295}
1296
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297void SurfaceFlinger::enableHardwareVsync() {
1298 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001301 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1302 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001304 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305}
1306
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001308 Mutex::Autolock _l(mHWVsyncLock);
1309
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 if (makeAvailable) {
1311 mHWVsyncAvailable = true;
1312 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001313 // Hardware vsync is not currently available, so abort the resync
1314 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001315 return;
1316 }
1317
David Sodman105b7dc2017-11-04 20:28:14 -07001318 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
1321 mPrimaryDispSync.reset();
1322 mPrimaryDispSync.setPeriod(period);
1323
1324 if (!mPrimaryHWVsyncEnabled) {
1325 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1327 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 mPrimaryHWVsyncEnabled = true;
1329 }
1330}
1331
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 Mutex::Autolock _l(mHWVsyncLock);
1334 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1336 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337 mPrimaryDispSync.endResync();
1338 mPrimaryHWVsyncEnabled = false;
1339 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001340 if (makeUnavailable) {
1341 mHWVsyncAvailable = false;
1342 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343}
1344
Tim Murray4a4e4a22016-04-19 16:29:23 +00001345void SurfaceFlinger::resyncWithRateLimit() {
1346 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001347
1348 // No explicit locking is needed here since EventThread holds a lock while calling this method
1349 static nsecs_t sLastResyncAttempted = 0;
1350 const nsecs_t now = systemTime();
1351 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001352 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353 }
Dan Stoza57164302017-05-08 14:03:54 -07001354 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001355}
1356
Steven Thomasb02664d2017-07-26 18:48:28 -07001357void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1358 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001359 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
1363 }
1364
1365 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001366 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 return;
1368 }
1369
Jamie Gennisd1700752013-10-14 12:22:52 -07001370 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001371
Jamie Gennisd1700752013-10-14 12:22:52 -07001372 { // Scope for the lock
1373 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001375 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001376 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001377 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001378
1379 if (needsHwVsync) {
1380 enableHardwareVsync();
1381 } else {
1382 disableHardwareVsync(false);
1383 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001384}
1385
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001386void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001387 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1388 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389}
1390
Lloyd Pique715a2c12017-12-14 17:18:08 -08001391void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1392 HWC2::Connection connection) {
1393 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1394 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001395
Lloyd Piqueba04e622017-12-14 17:11:26 -08001396 // Ignore events that do not have the right sequenceId.
1397 if (sequenceId != getBE().mComposerSequenceId) {
1398 return;
1399 }
1400
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 // Only lock if we're not on the main thread. This function is normally
1402 // called on a hwbinder thread, but for the primary display it's called on
1403 // the main thread with the state lock already held, so don't attempt to
1404 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001405 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001406
Lloyd Pique715a2c12017-12-14 17:18:08 -08001407 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001408
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001409 if (std::this_thread::get_id() == mMainThreadId) {
1410 // Process all pending hot plug events immediately if we are on the main thread.
1411 processDisplayHotplugEventsLocked();
1412 }
1413
Lloyd Piqueba04e622017-12-14 17:11:26 -08001414 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001415}
1416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417void SurfaceFlinger::onRefreshReceived(int sequenceId,
1418 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001419 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001422 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001423 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001424}
1425
Dan Stoza9e56aa02015-11-02 13:00:03 -08001426void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001427 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001429 getHwComposer().setVsyncEnabled(disp,
1430 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001431}
1432
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001434void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436 // Clear the drawing state so that the logic inside of
1437 // handleTransactionLocked will fire. It will determine the delta between
1438 // mCurrentState and mDrawingState and re-apply all changes when we make the
1439 // transition.
1440 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001441 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 mDisplays.clear();
1443}
1444
Steven Thomas050b2c82017-03-06 11:45:16 -08001445void SurfaceFlinger::updateVrFlinger() {
1446 if (!mVrFlinger)
1447 return;
1448 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001449 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001450 return;
1451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
David Sodman105b7dc2017-11-04 20:28:14 -07001453 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 ALOGE("Vr flinger is only supported for remote hardware composer"
1455 " service connections. Ignoring request to transition to vr"
1456 " flinger.");
1457 mVrFlingerRequestsDisplay = false;
1458 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001459 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 int currentDisplayPowerMode = getDisplayDeviceLocked(
1464 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001467 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001471 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001472 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1473 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001474 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001475
David Sodman105b7dc2017-11-04 20:28:14 -07001476 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1477 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001478
1479 if (vrFlingerRequestsDisplay) {
1480 mVrFlinger->GrantDisplayOwnership();
1481 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001483 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484
1485 mVisibleRegionsDirty = true;
1486 invalidateHwcGeometry();
1487
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001488 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1490 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1491 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001492
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001494 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001495 const nsecs_t period = activeConfig->getVsyncPeriod();
1496 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001497
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 // Use phase of 0 since phase is not known.
1499 // Use latency of 0, which will snap to the ideal latency.
1500 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001501
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001502 android_atomic_or(1, &mRepaintEverything);
1503 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504}
1505
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001507 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001508 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001510 bool frameMissed = !mHadClientComposition &&
1511 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001512 (mPreviousPresentFence->getSignalTime() ==
1513 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001514 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001515 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001516 mTimeStats.incrementMissedFrames();
1517 if (mPropagateBackpressure) {
1518 signalLayerUpdate();
1519 break;
1520 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001521 }
Dan Stoza50182882016-07-08 12:02:20 -07001522
Steven Thomas050b2c82017-03-06 11:45:16 -08001523 // Now that we're going to make it to the handleMessageTransaction()
1524 // call below it's safe to call updateVrFlinger(), which will
1525 // potentially trigger a display handoff.
1526 updateVrFlinger();
1527
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 bool refreshNeeded = handleMessageTransaction();
1529 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001530 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001531 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001532 // Signal a refresh if a transaction modified the window state,
1533 // a new buffer was latched, or if HWC has requested a full
1534 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001535 signalRefresh();
1536 }
1537 break;
1538 }
1539 case MessageQueue::REFRESH: {
1540 handleMessageRefresh();
1541 break;
1542 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543 }
1544}
1545
Dan Stoza6b9454d2014-11-07 16:00:59 -08001546bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001547 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001549 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001550 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001551 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001552 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001553}
1554
Dan Stoza6b9454d2014-11-07 16:00:59 -08001555bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001557 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001558}
1559
1560void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001562
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001563 mRefreshPending = false;
1564
Pablo Ceballos40845df2016-01-25 17:41:15 -08001565 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001566
Brian Andersond6927fb2016-07-23 23:37:30 -07001567 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001568 rebuildLayerStacks();
1569 setUpHWComposer();
1570 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001571 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001572 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001573 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001575
David Sodman105b7dc2017-11-04 20:28:14 -07001576 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001577
1578 mHadClientComposition = false;
1579 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1580 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1581 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001582 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001583 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001584 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001585
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589void SurfaceFlinger::doDebugFlashRegions()
1590{
1591 // is debugging enabled
1592 if (CC_LIKELY(!mDebugRegion))
1593 return;
1594
1595 const bool repaintEverything = mRepaintEverything;
1596 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1597 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001598 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599 // transform the dirty region into this screen's coordinate space
1600 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1601 if (!dirtyRegion.isEmpty()) {
1602 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001603 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604
1605 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001607 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001608 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1609
Mathias Agopianda27af92012-09-13 18:17:13 -07001610 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611 }
1612 }
1613 }
1614
1615 postFramebuffer();
1616
1617 if (mDebugRegion > 1) {
1618 usleep(mDebugRegion * 1000);
1619 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001620
Dan Stoza9e56aa02015-11-02 13:00:03 -08001621 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001622 auto& displayDevice = mDisplays[displayId];
1623 if (!displayDevice->isDisplayOn()) {
1624 continue;
1625 }
1626
David Sodman105b7dc2017-11-04 20:28:14 -07001627 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1628 ALOGE_IF(result != NO_ERROR,
1629 "prepareFrame for display %zd failed:"
1630 " %d (%s)",
1631 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001632 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633}
1634
Adrian Roos1e1a1282017-11-01 19:05:31 +01001635void SurfaceFlinger::doTracing(const char* where) {
1636 ATRACE_CALL();
1637 ATRACE_NAME(where);
1638 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001639 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001640 }
1641}
1642
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001643void SurfaceFlinger::logLayerStats() {
1644 ATRACE_CALL();
1645 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1646 int32_t hwcId = -1;
1647 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1648 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1649 if (displayDevice->isPrimary()) {
1650 hwcId = displayDevice->getHwcDisplayId();
1651 break;
1652 }
1653 }
1654 if (hwcId < 0) {
1655 ALOGE("LayerStats: Hmmm, no primary display?");
1656 return;
1657 }
1658 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1659 }
1660}
1661
Brian Andersond6927fb2016-07-23 23:37:30 -07001662void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 ATRACE_CALL();
1665 ALOGV("preComposition");
1666
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001668 mDrawingState.traverseInZOrder([&](Layer* layer) {
1669 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670 needExtraInvalidate = true;
1671 }
Robert Carr2047fae2016-11-28 14:09:09 -08001672 });
1673
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 if (needExtraInvalidate) {
1675 signalLayerUpdate();
1676 }
1677}
1678
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679void SurfaceFlinger::updateCompositorTiming(
1680 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1681 std::shared_ptr<FenceTime>& presentFenceTime) {
1682 // Update queue of past composite+present times and determine the
1683 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001684 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001686 while (!getBE().mCompositePresentTimes.empty()) {
1687 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 // Cached values should have been updated before calling this method,
1689 // which helps avoid duplicate syscalls.
1690 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1691 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1692 break;
1693 }
1694 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001695 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 }
1697
1698 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001699 while (getBE().mCompositePresentTimes.size() > 16) {
1700 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 }
1702
Brian Andersond0010582017-03-07 13:20:31 -08001703 setCompositorTimingSnapped(
1704 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1705}
1706
1707void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1708 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 // Integer division and modulo round toward 0 not -inf, so we need to
1710 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001711 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1713 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1714
Brian Andersond0010582017-03-07 13:20:31 -08001715 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1716 if (idealLatency <= 0) {
1717 idealLatency = vsyncInterval;
1718 }
1719
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720 // Snap the latency to a value that removes scheduling jitter from the
1721 // composition and present times, which often have >1ms of jitter.
1722 // Reducing jitter is important if an app attempts to extrapolate
1723 // something (such as user input) to an accurate diasplay time.
1724 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1725 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001726 nsecs_t bias = vsyncInterval / 2;
1727 int64_t extraVsyncs =
1728 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1729 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1730 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731
David Sodman99974d22017-11-28 12:04:33 -08001732 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1733 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1734 getBE().mCompositorTiming.interval = vsyncInterval;
1735 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736}
1737
1738void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 ATRACE_CALL();
1741 ALOGV("postComposition");
1742
Brian Anderson3546a3f2016-07-14 11:51:14 -07001743 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001744 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001745 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001746 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001747 }
1748
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001749 // |mStateLock| not needed as we are on the main thread
1750 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001751
David Sodman73beded2017-11-15 11:56:06 -08001752 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001754 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755 glCompositionDoneFenceTime =
1756 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001757 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001758 } else {
1759 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1760 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761
David Sodman73beded2017-11-15 11:56:06 -08001762 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001763 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001764 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001765 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001767 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1768 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1769
1770 // We use the refreshStartTime which might be sampled a little later than
1771 // when we started doing work for this frame, but that should be okay
1772 // since updateCompositorTiming has snapping logic.
1773 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001774 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001775 CompositorTiming compositorTiming;
1776 {
David Sodman99974d22017-11-28 12:04:33 -08001777 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1778 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001779 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780
Robert Carr2047fae2016-11-28 14:09:09 -08001781 mDrawingState.traverseInZOrder([&](Layer* layer) {
1782 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001783 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001784 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001785 recordBufferingStats(layer->getName().string(),
1786 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001787 }
Robert Carr2047fae2016-11-28 14:09:09 -08001788 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001789
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001790 if (presentFenceTime->isValid()) {
1791 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001792 enableHardwareVsync();
1793 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001794 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001795 }
1796 }
1797
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001798 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001799 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001800 enableHardwareVsync();
1801 }
1802 }
1803
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001804 if (mAnimCompositionPending) {
1805 mAnimCompositionPending = false;
1806
Brian Anderson4e606e32017-03-16 15:34:57 -07001807 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001808 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001809 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001810 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001811 // The HWC doesn't support present fences, so use the refresh
1812 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001814 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001815 mAnimFrameTracker.setActualPresentTime(presentTime);
1816 }
1817 mAnimFrameTracker.advanceFrame();
1818 }
Dan Stozab90cf072015-03-05 11:05:59 -08001819
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001820 mTimeStats.incrementTotalFrames();
1821 if (mHadClientComposition) {
1822 mTimeStats.incrementClientCompositionFrames();
1823 }
1824
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001825 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1826 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001827 return;
1828 }
1829
1830 nsecs_t currentTime = systemTime();
1831 if (mHasPoweredOff) {
1832 mHasPoweredOff = false;
1833 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001834 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001836 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1837 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001838 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001839 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001840 }
David Sodman4a36e932017-11-07 14:29:47 -08001841 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001842 }
David Sodman4a36e932017-11-07 14:29:47 -08001843 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844}
1845
1846void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 ATRACE_CALL();
1848 ALOGV("rebuildLayerStacks");
1849
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001852 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001853 mVisibleRegionsDirty = false;
1854 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855
Jeff Sharkey76488112017-02-27 14:15:18 -07001856 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1857 Region opaqueRegion;
1858 Region dirtyRegion;
1859 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001860 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1862 const Transform& tr(displayDevice->getTransform());
1863 const Rect bounds(displayDevice->getBounds());
1864 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001865 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001868 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001869 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1870 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 Region drawRegion(tr.transform(
1872 layer->visibleNonTransparentRegion));
1873 drawRegion.andSelf(bounds);
1874 if (!drawRegion.isEmpty()) {
1875 layersSortedByZ.add(layer);
1876 } else {
1877 // Clear out the HWC layer if this layer was
1878 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001879 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001880 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001882 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001883 // WM changes displayDevice->layerStack upon sleep/awake.
1884 // Here we make sure we delete the HWC layers even if
1885 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001886 hwcLayerDestroyed = layer->destroyHwcLayer(
1887 displayDevice->getHwcDisplayId());
1888 }
1889
1890 // If a layer is not going to get a release fence because
1891 // it is invisible, but it is also going to release its
1892 // old buffer, add it to the list of layers needing
1893 // fences.
1894 if (hwcLayerDestroyed) {
1895 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1896 mLayersWithQueuedFrames.cend(), layer);
1897 if (found != mLayersWithQueuedFrames.cend()) {
1898 layersNeedingFences.add(layer);
1899 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001900 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001901 });
1902 }
1903 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001904 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001905 displayDevice->undefinedRegion.set(bounds);
1906 displayDevice->undefinedRegion.subtractSelf(
1907 tr.transform(opaqueRegion));
1908 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001909 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001910 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001911}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001912
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001913// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001915// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001917// The returned HDR data space is one of
1918// - Dataspace::UNKNOWN
1919// - Dataspace::BT2020_HLG
1920// - Dataspace::BT2020_PQ
1921Dataspace SurfaceFlinger::getBestDataspace(
1922 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1923 Dataspace bestDataSpace = Dataspace::SRGB;
1924 *outHdrDataSpace = Dataspace::UNKNOWN;
1925
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001927 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928 case Dataspace::V0_SCRGB:
1929 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001930 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001931 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001932 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001933 case Dataspace::BT2020_PQ:
1934 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001935 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001937 case Dataspace::BT2020_HLG:
1938 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001939 // When there's mixed PQ content and HLG content, we set the HDR
1940 // data space to be BT2020_PQ and convert HLG to PQ.
1941 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1942 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001943 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 break;
1945 default:
1946 break;
1947 }
Romain Guy54f154a2017-10-24 21:40:32 +01001948 }
1949
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001950 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001951}
1952
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001954void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001955 ColorMode* outMode, Dataspace* outDataSpace,
1956 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001957 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1958 *outMode = ColorMode::NATIVE;
1959 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001960 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001962 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001963
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001964 Dataspace hdrDataSpace;
1965 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1966
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001967 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001968 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001969 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001970 if (isHdr) {
1971 bestDataSpace = hdrDataSpace;
1972 }
1973
Chia-I Wu0d711262018-05-21 15:19:35 -07001974 RenderIntent intent;
1975 switch (mDisplayColorSetting) {
1976 case DisplayColorSetting::MANAGED:
1977 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001978 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001979 break;
1980 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001981 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001982 break;
1983 default: // vendor display color setting
1984 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1985 break;
1986 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001987
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001988 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001989}
1990
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 ATRACE_CALL();
1993 ALOGV("setUpHWComposer");
1994
Jesse Hall028dc8f2013-08-20 16:35:32 -07001995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001996 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001997 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1998 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1999
2000 // If nothing has changed (!dirty), don't recompose.
2001 // If something changed, but we don't currently have any visible layers,
2002 // and didn't when we last did a composition, then skip it this time.
2003 // The second rule does two things:
2004 // - When all layers are removed from a display, we'll emit one black
2005 // frame, then nothing more until we get new layers.
2006 // - When a display is created with a private layer stack, we won't
2007 // emit any black frames until a layer is added to the layer stack.
2008 bool mustRecompose = dirty && !(empty && wasEmpty);
2009
2010 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2011 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2012 mustRecompose ? "doing" : "skipping",
2013 dirty ? "+" : "-",
2014 empty ? "+" : "-",
2015 wasEmpty ? "+" : "-");
2016
Dan Stoza71433162014-02-04 16:22:36 -08002017 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002018
2019 if (mustRecompose) {
2020 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2021 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002022 }
2023
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 // build the h/w work list
2025 if (CC_UNLIKELY(mGeometryInvalid)) {
2026 mGeometryInvalid = false;
2027 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2028 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2029 const auto hwcId = displayDevice->getHwcDisplayId();
2030 if (hwcId >= 0) {
2031 const Vector<sp<Layer>>& currentLayers(
2032 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002033 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002034 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002036 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002039 }
2040 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002041
Robert Carrae060832016-11-28 10:51:00 -08002042 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002043 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002045 }
2046 }
2047 }
2048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 }
Riley Andrews03414a12014-07-01 14:22:59 -07002050
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 // Set the per-frame data
2052 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2053 auto& displayDevice = mDisplays[displayId];
2054 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002055
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 if (hwcId < 0) {
2057 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002058 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002059 if (mDrawingState.colorMatrixChanged) {
2060 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2061 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002062 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2063 "display %zd: %d", displayId, result);
2064 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002066 if (layer->isHdrY410()) {
2067 layer->forceClientComposition(hwcId);
2068 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2069 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002070 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002071 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002072 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2073 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002074 !displayDevice->hasHLGSupport()) {
2075 layer->forceClientComposition(hwcId);
2076 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002077
chaviwc9232ed2017-11-14 15:31:15 -08002078 if (layer->getForceClientComposition(hwcId)) {
2079 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2080 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2081 continue;
2082 }
2083
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 layer->setPerFrameData(displayDevice);
2085 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002086
2087 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002088 ColorMode colorMode;
2089 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002090 RenderIntent renderIntent;
2091 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2092 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002093 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094 }
2095
Chia-I Wu28f320b2018-05-03 11:02:56 -07002096 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002097
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002099 auto& displayDevice = mDisplays[displayId];
2100 if (!displayDevice->isDisplayOn()) {
2101 continue;
2102 }
2103
David Sodman105b7dc2017-11-04 20:28:14 -07002104 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2106 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002107 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002108}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002109
Mathias Agopiancd60f992012-08-16 16:28:27 -07002110void SurfaceFlinger::doComposition() {
2111 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 ALOGV("doComposition");
2113
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002114 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002115 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002116 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002117 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002118 // transform the dirty region into this screen's coordinate space
2119 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002120
2121 // repaint the framebuffer (if needed)
2122 doDisplayComposition(hw, dirtyRegion);
2123
Mathias Agopiancd60f992012-08-16 16:28:27 -07002124 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002125 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002126 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002127 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002128 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002129}
2130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131void SurfaceFlinger::postFramebuffer()
2132{
Mathias Agopian841cde52012-03-01 15:44:37 -08002133 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002135
Mathias Agopiana44b0412011-10-16 18:46:35 -07002136 const nsecs_t now = systemTime();
2137 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002138
Dan Stoza9e56aa02015-11-02 13:00:03 -08002139 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2140 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002141 if (!displayDevice->isDisplayOn()) {
2142 continue;
2143 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002144 const auto hwcId = displayDevice->getHwcDisplayId();
2145 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002146 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002147 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002148 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002149 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002151 // The layer buffer from the previous frame (if any) is released
2152 // by HWC only when the release fence from this frame (if any) is
2153 // signaled. Always get the release fence from HWC first.
2154 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002155 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002156
2157 // If the layer was client composited in the previous frame, we
2158 // need to merge with the previous client target acquire fence.
2159 // Since we do not track that, always merge with the current
2160 // client target acquire fence when it is available, even though
2161 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002163 releaseFence = Fence::merge("LayerRelease", releaseFence,
2164 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002165 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002166
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 layer->onLayerDisplayed(releaseFence);
2168 }
Chia-I Wu83806892017-11-16 10:50:20 -08002169
2170 // We've got a list of layers needing fences, that are disjoint with
2171 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2172 // supply them with the present fence.
2173 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002174 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002175 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2176 layer->onLayerDisplayed(presentFence);
2177 }
2178 }
2179
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002181 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002182 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002183 }
2184
Mathias Agopiana44b0412011-10-16 18:46:35 -07002185 mLastSwapBufferTime = systemTime() - now;
2186 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002187
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002188 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002189 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2190 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2191 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2192 logFrameStats();
2193 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002194 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002195}
2196
Mathias Agopian87baae12012-07-31 12:38:26 -07002197void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198{
Mathias Agopian841cde52012-03-01 15:44:37 -08002199 ATRACE_CALL();
2200
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002201 // here we keep a copy of the drawing state (that is the state that's
2202 // going to be overwritten by handleTransactionLocked()) outside of
2203 // mStateLock so that the side-effects of the State assignment
2204 // don't happen with mStateLock held (which can cause deadlocks).
2205 State drawingState(mDrawingState);
2206
Mathias Agopianca4d3602011-05-19 15:38:14 -07002207 Mutex::Autolock _l(mStateLock);
2208 const nsecs_t now = systemTime();
2209 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210
Mathias Agopianca4d3602011-05-19 15:38:14 -07002211 // Here we're guaranteed that some transaction flags are set
2212 // so we can call handleTransactionLocked() unconditionally.
2213 // We call getTransactionFlags(), which will also clear the flags,
2214 // with mStateLock held to guarantee that mCurrentState won't change
2215 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002216
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002217 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002218 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002219 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002220
Mathias Agopianca4d3602011-05-19 15:38:14 -07002221 mLastTransactionTime = systemTime() - now;
2222 mDebugInTransaction = 0;
2223 invalidateHwcGeometry();
2224 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002225}
2226
Lloyd Pique715a2c12017-12-14 17:18:08 -08002227DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002228 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002229 // Figure out whether the event is for the primary display or an
2230 // external display by matching the Hwc display id against one for a
2231 // connected display. If we did not find a match, we then check what
2232 // displays are not already connected to determine the type. If we don't
2233 // have a connected primary display, we assume the new display is meant to
2234 // be the primary display, and then if we don't have an external display,
2235 // we assume it is that.
2236 const auto primaryDisplayId =
2237 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2238 const auto externalDisplayId =
2239 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2240 if (primaryDisplayId && primaryDisplayId == display) {
2241 return DisplayDevice::DISPLAY_PRIMARY;
2242 } else if (externalDisplayId && externalDisplayId == display) {
2243 return DisplayDevice::DISPLAY_EXTERNAL;
2244 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2245 return DisplayDevice::DISPLAY_PRIMARY;
2246 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2247 return DisplayDevice::DISPLAY_EXTERNAL;
2248 }
2249
2250 return DisplayDevice::DISPLAY_ID_INVALID;
2251}
2252
Lloyd Piqueba04e622017-12-14 17:11:26 -08002253void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2254 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 auto displayType = determineDisplayType(event.display, event.connection);
2256 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2257 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2258 continue;
2259 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002260
2261 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2262 ALOGE("External displays are not supported by the vr hardware composer.");
2263 continue;
2264 }
2265
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002267
2268 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002269 if (!mBuiltinDisplays[displayType].get()) {
2270 ALOGV("Creating built in display %d", displayType);
2271 mBuiltinDisplays[displayType] = new BBinder();
2272 // All non-virtual displays are currently considered secure.
2273 DisplayDeviceState info(displayType, true);
2274 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2275 "Built-in Screen" : "External Screen";
2276 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002277 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002278 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002280 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281
Lloyd Piquefcd86612017-12-14 17:15:36 -08002282 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2283 if (idx >= 0) {
2284 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002285 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002286 mCurrentState.displays.removeItemsAt(idx);
2287 }
2288 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289 }
2290
2291 processDisplayChangesLocked();
2292 }
2293
2294 mPendingHotplugEvents.clear();
2295}
2296
Lloyd Pique09594832018-01-22 17:48:03 -08002297sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2298 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2299 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002301 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002302
Lloyd Pique09594832018-01-22 17:48:03 -08002303 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002305 for (ColorMode colorMode : modes) {
2306 switch (colorMode) {
2307 case ColorMode::DISPLAY_P3:
2308 case ColorMode::ADOBE_RGB:
2309 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002311 break;
2312 default:
2313 break;
2314 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315
2316 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2317 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002318 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002319 }
2320 }
2321
Peiyong Lin62665892018-04-16 11:07:44 -07002322 HdrCapabilities hdrCapabilities;
2323 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002324
2325 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2326 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2327
2328 /*
2329 * Create our display's surface
2330 */
2331 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2332 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2333 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2334 renderSurface->setNativeWindow(nativeWindow.get());
2335 const int displayWidth = renderSurface->queryWidth();
2336 const int displayHeight = renderSurface->queryHeight();
2337
2338 // Make sure that composition can never be stalled by a virtual display
2339 // consumer that isn't processing buffers fast enough. We have to do this
2340 // in two places:
2341 // * Here, in case the display is composed entirely by HWC.
2342 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2343 // window's swap interval in eglMakeCurrent, so they'll override the
2344 // interval we set here.
2345 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2346 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2347 }
2348
2349 // virtual displays are always considered enabled
2350 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2351 : HWC_POWER_MODE_OFF;
2352
2353 sp<DisplayDevice> hw =
2354 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2355 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002356 hasWideColorGamut, hdrCapabilities,
2357 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002358 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002359
2360 if (maxFrameBufferAcquiredBuffers >= 3) {
2361 nativeWindowSurface->preallocateBuffers();
2362 }
2363
2364 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002365 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2366 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002367 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002368 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002369 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002370 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2371 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002372 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2373 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2374 }
Lloyd Pique09594832018-01-22 17:48:03 -08002375 hw->setLayerStack(state.layerStack);
2376 hw->setProjection(state.orientation, state.viewport, state.frame);
2377 hw->setDisplayName(state.displayName);
2378
2379 return hw;
2380}
2381
Lloyd Pique347200f2017-12-14 17:00:15 -08002382void SurfaceFlinger::processDisplayChangesLocked() {
2383 // here we take advantage of Vector's copy-on-write semantics to
2384 // improve performance by skipping the transaction entirely when
2385 // know that the lists are identical
2386 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2387 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2388 if (!curr.isIdenticalTo(draw)) {
2389 mVisibleRegionsDirty = true;
2390 const size_t cc = curr.size();
2391 size_t dc = draw.size();
2392
2393 // find the displays that were removed
2394 // (ie: in drawing state but not in current state)
2395 // also handle displays that changed
2396 // (ie: displays that are in both lists)
2397 for (size_t i = 0; i < dc;) {
2398 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2399 if (j < 0) {
2400 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002401 // Call makeCurrent() on the primary display so we can
2402 // be sure that nothing associated with this display
2403 // is current.
2404 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2405 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2406 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2407 if (hw != nullptr) hw->disconnect(getHwComposer());
2408 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2409 mEventThread->onHotplugReceived(draw[i].type, false);
2410 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002411 } else {
2412 // this display is in both lists. see if something changed.
2413 const DisplayDeviceState& state(curr[j]);
2414 const wp<IBinder>& display(curr.keyAt(j));
2415 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2416 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2417 if (state_binder != draw_binder) {
2418 // changing the surface is like destroying and
2419 // recreating the DisplayDevice, so we just remove it
2420 // from the drawing state, so that it get re-added
2421 // below.
2422 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2423 if (hw != nullptr) hw->disconnect(getHwComposer());
2424 mDisplays.removeItem(display);
2425 mDrawingState.displays.removeItemsAt(i);
2426 dc--;
2427 // at this point we must loop to the next item
2428 continue;
2429 }
2430
2431 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2432 if (disp != nullptr) {
2433 if (state.layerStack != draw[i].layerStack) {
2434 disp->setLayerStack(state.layerStack);
2435 }
2436 if ((state.orientation != draw[i].orientation) ||
2437 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2438 disp->setProjection(state.orientation, state.viewport, state.frame);
2439 }
2440 if (state.width != draw[i].width || state.height != draw[i].height) {
2441 disp->setDisplaySize(state.width, state.height);
2442 }
2443 }
2444 }
2445 ++i;
2446 }
2447
2448 // find displays that were added
2449 // (ie: in current state but not in drawing state)
2450 for (size_t i = 0; i < cc; i++) {
2451 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2452 const DisplayDeviceState& state(curr[i]);
2453
2454 sp<DisplaySurface> dispSurface;
2455 sp<IGraphicBufferProducer> producer;
2456 sp<IGraphicBufferProducer> bqProducer;
2457 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002458 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002459
2460 int32_t hwcId = -1;
2461 if (state.isVirtualDisplay()) {
2462 // Virtual displays without a surface are dormant:
2463 // they have external state (layer stack, projection,
2464 // etc.) but no internal state (i.e. a DisplayDevice).
2465 if (state.surface != nullptr) {
2466 // Allow VR composer to use virtual displays.
2467 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2468 int width = 0;
2469 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2470 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2471 int height = 0;
2472 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2473 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2474 int intFormat = 0;
2475 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2476 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002477 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002478
2479 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2480 }
2481
2482 // TODO: Plumb requested format back up to consumer
2483
2484 sp<VirtualDisplaySurface> vds =
2485 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2486 bqProducer, bqConsumer,
2487 state.displayName);
2488
2489 dispSurface = vds;
2490 producer = vds;
2491 }
2492 } else {
2493 ALOGE_IF(state.surface != nullptr,
2494 "adding a supported display, but rendering "
2495 "surface is provided (%p), ignoring it",
2496 state.surface.get());
2497
2498 hwcId = state.type;
2499 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2500 producer = bqProducer;
2501 }
2502
2503 const wp<IBinder>& display(curr.keyAt(i));
2504 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002505 mDisplays.add(display,
2506 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2507 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 if (!state.isVirtualDisplay()) {
2509 mEventThread->onHotplugReceived(state.type, true);
2510 }
2511 }
2512 }
2513 }
2514 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002515
2516 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002517}
2518
Mathias Agopian87baae12012-07-31 12:38:26 -07002519void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002520{
Dan Stoza7dde5992015-05-22 09:51:44 -07002521 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002522 mCurrentState.traverseInZOrder([](Layer* layer) {
2523 layer->notifyAvailableFrames();
2524 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 /*
2527 * Traversal of the children
2528 * (perform the transaction for each of them if needed)
2529 */
2530
Mathias Agopian3559b072012-08-15 13:46:03 -07002531 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002532 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002534 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535
2536 const uint32_t flags = layer->doTransaction(0);
2537 if (flags & Layer::eVisibleRegion)
2538 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002539 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 }
2541
2542 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002543 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 */
2545
Mathias Agopiane57f2922012-08-09 16:29:12 -07002546 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002551 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002552 // The transform hint might have changed for some layers
2553 // (either because a display has changed, or because a layer
2554 // as changed).
2555 //
2556 // Walk through all the layers in currentLayers,
2557 // and update their transform hint.
2558 //
2559 // If a layer is visible only on a single display, then that
2560 // display is used to calculate the hint, otherwise we use the
2561 // default display.
2562 //
2563 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2564 // the hint is set before we acquire a buffer from the surface texture.
2565 //
2566 // NOTE: layer transactions have taken place already, so we use their
2567 // drawing state. However, SurfaceFlinger's own transaction has not
2568 // happened yet, so we must use the current state layer list
2569 // (soon to become the drawing state list).
2570 //
2571 sp<const DisplayDevice> disp;
2572 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002573 bool first = true;
2574 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002575 // NOTE: we rely on the fact that layers are sorted by
2576 // layerStack first (so we don't have to traverse the list
2577 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002579 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002580 currentlayerStack = layerStack;
2581 // figure out if this layerstack is mirrored
2582 // (more than one display) if so, pick the default display,
2583 // if not, pick the only display it's on.
2584 disp.clear();
2585 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2586 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002587 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002588 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002589 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002590 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002591 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002592 break;
2593 }
2594 }
2595 }
2596 }
Chet Haase91d25932013-04-11 15:24:55 -07002597
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002598 if (disp == nullptr) {
2599 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2600 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002601
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002602 // could be null when this layer is using a layerStack
2603 // that is not visible on any display. Also can occur at
2604 // screen off/on times.
2605 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002606 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002607
2608 // disp can be null if there is no display available at all to get
2609 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002610 if (disp != nullptr) {
2611 layer->updateTransformHint(disp);
2612 }
Robert Carr2047fae2016-11-28 14:09:09 -08002613
2614 first = false;
2615 });
Mathias Agopian84300952012-11-21 16:02:13 -08002616 }
2617
2618
Mathias Agopian3559b072012-08-15 13:46:03 -07002619 /*
2620 * Perform our own transaction if needed
2621 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622
2623 if (mLayersAdded) {
2624 mLayersAdded = false;
2625 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002626 mVisibleRegionsDirty = true;
2627 }
2628
2629 // some layers might have been removed, so
2630 // we need to update the regions they're exposing.
2631 if (mLayersRemoved) {
2632 mLayersRemoved = false;
2633 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002634 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002636 // this layer is not visible anymore
2637 // TODO: we could traverse the tree from front to back and
2638 // compute the actual visible region
2639 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 Region visibleReg;
2641 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002642 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002643 }
Robert Carr2047fae2016-11-28 14:09:09 -08002644 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 }
2646
2647 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002648
2649 updateCursorAsync();
2650}
2651
2652void SurfaceFlinger::updateCursorAsync()
2653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2655 auto& displayDevice = mDisplays[displayId];
2656 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002657 continue;
2658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659
2660 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2661 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002662 }
2663 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664}
2665
2666void SurfaceFlinger::commitTransaction()
2667{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002668 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002669 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002670 for (const auto& l : mLayersPendingRemoval) {
2671 recordBufferingStats(l->getName().string(),
2672 l->getOccupancyHistory(true));
2673 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674 }
2675 mLayersPendingRemoval.clear();
2676 }
2677
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002678 // If this transaction is part of a window animation then the next frame
2679 // we composite should be considered an animation as well.
2680 mAnimCompositionPending = mAnimTransactionPending;
2681
Mathias Agopian4fec8732012-06-29 14:12:52 -07002682 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002683 // clear the "changed" flags in current state
2684 mCurrentState.colorMatrixChanged = false;
2685
Robert Carr1f0a16a2016-10-24 16:27:39 -07002686 mDrawingState.traverseInZOrder([](Layer* layer) {
2687 layer->commitChildList();
2688 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002689 mTransactionPending = false;
2690 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002691 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692}
2693
Chia-I Wuab0c3192017-08-01 11:29:00 -07002694void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002695 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696{
Mathias Agopian841cde52012-03-01 15:44:37 -08002697 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 Region aboveOpaqueLayers;
2701 Region aboveCoveredLayers;
2702 Region dirty;
2703
Mathias Agopian87baae12012-07-31 12:38:26 -07002704 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705
Robert Carr2047fae2016-11-28 14:09:09 -08002706 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002708 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Jesse Hall01e29052013-02-19 16:13:35 -08002710 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002711 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002712 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 /*
2715 * opaqueRegion: area of a surface that is fully opaque.
2716 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002718
2719 /*
2720 * visibleRegion: area of a surface that is visible on screen
2721 * and not fully transparent. This is essentially the layer's
2722 * footprint minus the opaque regions above it.
2723 * Areas covered by a translucent surface are considered visible.
2724 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002726
2727 /*
2728 * coveredRegion: area of a surface that is covered by all
2729 * visible regions above it (which includes the translucent areas).
2730 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002732
Jesse Halla8026d22012-09-25 13:25:04 -07002733 /*
2734 * transparentRegion: area of a surface that is hinted to be completely
2735 * transparent. This is only used to tell when the layer has no visible
2736 * non-transparent regions and can be removed from the layer list. It
2737 * does not affect the visibleRegion of this layer or any layers
2738 * beneath it. The hint may not be correct if apps don't respect the
2739 * SurfaceView restrictions (which, sadly, some don't).
2740 */
2741 Region transparentRegion;
2742
Mathias Agopianab028732010-03-16 16:41:46 -07002743
2744 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002745 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002746 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002749 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002750 if (!visibleRegion.isEmpty()) {
2751 // Remove the transparent area from the visible region
2752 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002753 if (tr.preserveRects()) {
2754 // transform the transparent region
2755 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002756 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002757 // transformation too complex, can't do the
2758 // transparent region optimization.
2759 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 }
Mathias Agopianab028732010-03-16 16:41:46 -07002761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762
Mathias Agopianab028732010-03-16 16:41:46 -07002763 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002765 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002766 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2767 // the opaque region is the layer's footprint
2768 opaqueRegion = visibleRegion;
2769 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 }
2771 }
2772
Robert Carre5f4f692018-01-12 13:12:28 -08002773 if (visibleRegion.isEmpty()) {
2774 layer->clearVisibilityRegions();
2775 return;
2776 }
2777
Mathias Agopianab028732010-03-16 16:41:46 -07002778 // Clip the covered region to the visible region
2779 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2780
2781 // Update aboveCoveredLayers for next (lower) layer
2782 aboveCoveredLayers.orSelf(visibleRegion);
2783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 // subtract the opaque region covered by the layers above us
2785 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786
2787 // compute this layer's dirty region
2788 if (layer->contentDirty) {
2789 // we need to invalidate the whole region
2790 dirty = visibleRegion;
2791 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 layer->contentDirty = false;
2794 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002795 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002796 * the exposed region consists of two components:
2797 * 1) what's VISIBLE now and was COVERED before
2798 * 2) what's EXPOSED now less what was EXPOSED before
2799 *
2800 * note that (1) is conservative, we start with the whole
2801 * visible region but only keep what used to be covered by
2802 * something -- which mean it may have been exposed.
2803 *
2804 * (2) handles areas that were not covered by anything but got
2805 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002806 */
Mathias Agopianab028732010-03-16 16:41:46 -07002807 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 const Region oldVisibleRegion = layer->visibleRegion;
2809 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002810 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2811 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 }
2813 dirty.subtractSelf(aboveOpaqueLayers);
2814
2815 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002816 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
Mathias Agopianab028732010-03-16 16:41:46 -07002818 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002820
Jesse Halla8026d22012-09-25 13:25:04 -07002821 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 layer->setVisibleRegion(visibleRegion);
2823 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002824 layer->setVisibleNonTransparentRegion(
2825 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002826 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827
Mathias Agopian87baae12012-07-31 12:38:26 -07002828 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829}
2830
Chia-I Wuab0c3192017-08-01 11:29:00 -07002831void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002832 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002833 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002834 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002835 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002836 }
2837 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002838}
2839
Dan Stoza6b9454d2014-11-07 16:00:59 -08002840bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 ALOGV("handlePageFlip");
2843
Brian Andersond6927fb2016-07-23 23:37:30 -07002844 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002847 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002848 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002849
2850 // Store the set of layers that need updates. This set must not change as
2851 // buffers are being latched, as this could result in a deadlock.
2852 // Example: Two producers share the same command stream and:
2853 // 1.) Layer 0 is latched
2854 // 2.) Layer 0 gets a new frame
2855 // 2.) Layer 1 gets a new frame
2856 // 3.) Layer 1 is latched.
2857 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2858 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002859 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 if (layer->hasQueuedFrame()) {
2861 frameQueued = true;
2862 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002864 } else {
2865 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002866 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002867 } else {
2868 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002869 }
Robert Carr2047fae2016-11-28 14:09:09 -08002870 });
2871
Dan Stoza9e56aa02015-11-02 13:00:03 -08002872 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002873 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002874 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002875 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002876 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002877 newDataLatched = true;
2878 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002879 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002880
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002881 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002882
2883 // If we will need to wake up at some time in the future to deal with a
2884 // queued frame that shouldn't be displayed during this vsync period, wake
2885 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002886 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002887 signalLayerUpdate();
2888 }
2889
Chia-I Wuad8d8272018-06-26 10:18:18 +08002890 // enter boot animation on first buffer latch
2891 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2892 ALOGI("Enter boot animation");
2893 mBootStage = BootStage::BOOTANIMATION;
2894 }
2895
Dan Stoza6b9454d2014-11-07 16:00:59 -08002896 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002897 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898}
2899
Mathias Agopianad456f92011-01-13 17:53:01 -08002900void SurfaceFlinger::invalidateHwcGeometry()
2901{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002902 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002903}
2904
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002905
Fabien Sanglard830b8472016-11-30 16:35:58 -08002906void SurfaceFlinger::doDisplayComposition(
2907 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002908 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
Dan Stoza71433162014-02-04 16:22:36 -08002910 // We only need to actually compose the display if:
2911 // 1) It is being handled by hardware composer, which may need this to
2912 // keep its virtual display state machine in sync, or
2913 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002914 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002915 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002917 return;
2918 }
2919
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002921 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002922
2923 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002924 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925}
2926
Chia-I Wub02087d2017-11-09 10:19:54 -08002927bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002928{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002930
Chia-I Wub02087d2017-11-09 10:19:54 -08002931 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002932 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002934 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002935 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002936
Chia-I Wu8e50e692018-05-04 10:12:37 -07002937 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002938 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002939
Dan Stoza9e56aa02015-11-02 13:00:03 -08002940 if (hasClientComposition) {
2941 ALOGV("hasClientComposition");
2942
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002943 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002944 if (displayDevice->hasWideColorGamut()) {
2945 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002946 }
2947 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002948 getBE().mRenderEngine->setDisplayMaxLuminance(
2949 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002950
Chia-I Wu8e50e692018-05-04 10:12:37 -07002951 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2952 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2953 HWC2::Capability::SkipClientColorTransform);
2954
Chia-I Wu6d844112018-06-27 07:17:41 +08002955 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002956 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2957 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08002958 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002959 }
2960
Chia-I Wu6d844112018-06-27 07:17:41 +08002961 // The current enhanced saturation matrix is designed to enhance Display P3,
2962 // thus we only apply this matrix when the render intent is not colorimetric
2963 // and the output color space is Display P3.
2964 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002965 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08002966 outputDataspace == Dataspace::DISPLAY_P3);
2967 if (needsEnhancedColorMatrix) {
2968 colorMatrix *= mEnhancedSaturationMatrix;
2969 }
2970
2971 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002972
Chia-I Wu7f402902017-11-09 12:51:10 -08002973 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002974 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002976 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002977
2978 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002979 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002980 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2981 }
2982 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002983 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002984
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002985 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002987 // when using overlays, we assume a fully transparent framebuffer
2988 // NOTE: we could reduce how much we need to clear, for instance
2989 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002990 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002991 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002992 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002993 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002994 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002995 // we're left with the letterbox region
2996 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002998
2999 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003001
Mathias Agopianb9494d52012-04-18 02:28:45 -07003002 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003003 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003004 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003005 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003006 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003007 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003008
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003010 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003011 // scissor on the main display. It should never be needed
3012 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 const Rect& bounds(displayDevice->getBounds());
3014 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003015 if (scissor != bounds) {
3016 // scissor doesn't match the screen's dimensions, so we
3017 // need to clear everything outside of it and enable
3018 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003019
Mathias Agopianf45c5102012-10-24 16:29:17 -07003020 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003022 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003023 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003024 }
3025 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003026 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003027
Mathias Agopian85d751c2012-08-29 16:59:24 -07003028 /*
3029 * and then, render the layers targeted at the framebuffer
3030 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003031
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 ALOGV("Rendering client layers");
3033 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003034 bool firstLayer = true;
3035 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3036 const Region clip(bounds.intersect(
3037 displayTransform.transform(layer->visibleRegion)));
3038 ALOGV("Layer: %s", layer->getName().string());
3039 ALOGV(" Composition type: %s",
3040 to_string(layer->getCompositionType(hwcId)).c_str());
3041 if (!clip.isEmpty()) {
3042 switch (layer->getCompositionType(hwcId)) {
3043 case HWC2::Composition::Cursor:
3044 case HWC2::Composition::Device:
3045 case HWC2::Composition::Sideband:
3046 case HWC2::Composition::SolidColor: {
3047 const Layer::State& state(layer->getDrawingState());
3048 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3049 layer->isOpaque(state) && (state.color.a == 1.0f)
3050 && hasClientComposition) {
3051 // never clear the very first layer since we're
3052 // guaranteed the FB is already cleared
3053 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003054 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003055 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003056 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003058 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003059 break;
3060 }
3061 default:
3062 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003063 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003064 } else {
3065 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003066 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003068 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003069
Chia-I Wu6d844112018-06-27 07:17:41 +08003070 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003071 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003072 }
3073
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003075 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003076 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077}
3078
Fabien Sanglard830b8472016-11-30 16:35:58 -08003079void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3080 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003081 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003082 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Dan Stoza7d89d062015-04-30 13:29:25 -07003085status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003086 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003087 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 const sp<Layer>& lbc,
3089 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003090{
Dan Stoza7d89d062015-04-30 13:29:25 -07003091 // add this layer to the current state list
3092 {
3093 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003095 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3096 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003097 return NO_MEMORY;
3098 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 if (parent == nullptr) {
3100 mCurrentState.layersSortedByZ.add(lbc);
3101 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003102 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003103 ALOGE("addClientLayer called with a removed parent");
3104 return NAME_NOT_FOUND;
3105 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 parent->addChild(lbc);
3107 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003108
Yiwei Zhang243b3782018-05-15 17:40:04 -07003109 if (gbc != nullptr) {
3110 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3111 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3112 mMaxGraphicBufferProducerListSize,
3113 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3114 mGraphicBufferProducerList.size(),
3115 mMaxGraphicBufferProducerListSize, mNumLayers);
3116 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003117 mLayersAdded = true;
3118 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003119 }
3120
Mathias Agopian96f08192010-06-02 23:28:45 -07003121 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003122 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003123
Dan Stoza7d89d062015-04-30 13:29:25 -07003124 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003125}
3126
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003127status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003128 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003129 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3130}
Robert Carr7f9b8992017-03-10 11:08:39 -08003131
chaviwca27f252018-02-06 16:46:39 -08003132status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3133 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003134 if (layer->isPendingRemoval()) {
3135 return NO_ERROR;
3136 }
3137
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003139 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003140 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003141 if (topLevelOnly) {
3142 return NO_ERROR;
3143 }
3144
Chia-I Wu98f1c102017-05-30 14:54:08 -07003145 sp<Layer> ancestor = p;
3146 while (ancestor->getParent() != nullptr) {
3147 ancestor = ancestor->getParent();
3148 }
3149 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3150 ALOGE("removeLayer called with a layer whose parent has been removed");
3151 return NAME_NOT_FOUND;
3152 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003153
3154 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003155 } else {
3156 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003157 }
3158
Robert Carr136e2f62017-02-08 17:54:29 -08003159 // As a matter of normal operation, the LayerCleaner will produce a second
3160 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3161 // so we will succeed in promoting it, but it's already been removed
3162 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3163 // otherwise something has gone wrong and we are leaking the layer.
3164 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3166 layer->getName().string(),
3167 (p != nullptr) ? p->getName().string() : "no-parent");
3168 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003169 } else if (index < 0) {
3170 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003171 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172
Chia-I Wuc6657022017-08-15 11:18:17 -07003173 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003174 mLayersPendingRemoval.add(layer);
3175 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003176 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 setTransactionFlags(eTransactionNeeded);
3178 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179}
3180
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003181uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003182 return android_atomic_release_load(&mTransactionFlags);
3183}
3184
Mathias Agopian3f844832013-08-07 21:24:32 -07003185uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3187}
3188
Mathias Agopian3f844832013-08-07 21:24:32 -07003189uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003190 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3191}
3192
3193uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3194 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003196 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003198 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 }
3200 return old;
3201}
3202
chaviwca27f252018-02-06 16:46:39 -08003203bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3204 for (const ComposerState& state : states) {
3205 // Here we need to check that the interface we're given is indeed
3206 // one of our own. A malicious client could give us a nullptr
3207 // IInterface, or one of its own or even one of our own but a
3208 // different type. All these situations would cause us to crash.
3209 if (state.client == nullptr) {
3210 return true;
3211 }
3212
3213 sp<IBinder> binder = IInterface::asBinder(state.client);
3214 if (binder == nullptr) {
3215 return true;
3216 }
3217
3218 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3219 return true;
3220 }
3221 }
3222 return false;
3223}
3224
Mathias Agopian8b33f032012-07-24 20:43:54 -07003225void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003226 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003227 const Vector<DisplayState>& displays,
3228 uint32_t flags)
3229{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003230 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003231 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003232 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003233
chaviwca27f252018-02-06 16:46:39 -08003234 if (containsAnyInvalidClientState(states)) {
3235 return;
3236 }
3237
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003238 if (flags & eAnimation) {
3239 // For window updates that are part of an animation we must wait for
3240 // previous animation "frames" to be handled.
3241 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003242 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003243 if (CC_UNLIKELY(err != NO_ERROR)) {
3244 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003245 // caller after a few seconds.
3246 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3247 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003248 mAnimTransactionPending = false;
3249 break;
3250 }
3251 }
3252 }
3253
chaviwca27f252018-02-06 16:46:39 -08003254 for (const DisplayState& display : displays) {
3255 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003256 }
3257
chaviwca27f252018-02-06 16:46:39 -08003258 for (const ComposerState& state : states) {
3259 transactionFlags |= setClientStateLocked(state);
3260 }
3261
3262 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3263 // as destroyed should only occur after setting all other states. This is to allow for a
3264 // child re-parent to happen before marking its original parent as destroyed (which would
3265 // then mark the child as destroyed).
3266 for (const ComposerState& state : states) {
3267 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003268 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003269
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003270 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3271 // anyway. This can be used as a flush mechanism for previous async transactions.
3272 // Empty animation transaction can be used to simulate back-pressure, so also force a
3273 // transaction for empty animation transactions.
3274 if (transactionFlags == 0 &&
3275 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003276 transactionFlags = eTransactionNeeded;
3277 }
3278
Mathias Agopian386aa982011-11-07 21:58:03 -08003279 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003280 if (mInterceptor->isEnabled()) {
3281 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003282 }
Irvel468051e2016-06-13 16:44:44 -07003283
Mathias Agopian386aa982011-11-07 21:58:03 -08003284 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003285 const auto start = (flags & eEarlyWakeup)
3286 ? VSyncModulator::TransactionStart::EARLY
3287 : VSyncModulator::TransactionStart::NORMAL;
3288 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003289
3290 // if this is a synchronous transaction, wait for it to take effect
3291 // before returning.
3292 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003293 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003294 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003295 if (flags & eAnimation) {
3296 mAnimTransactionPending = true;
3297 }
3298 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003299 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3300 if (CC_UNLIKELY(err != NO_ERROR)) {
3301 // just in case something goes wrong in SF, return to the
3302 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003303 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3304 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003305 break;
3306 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003307 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003308 }
3309}
3310
Mathias Agopiane57f2922012-08-09 16:29:12 -07003311uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3312{
Jesse Hall9a143922012-10-04 16:29:19 -07003313 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3314 if (dpyIdx < 0)
3315 return 0;
3316
Mathias Agopiane57f2922012-08-09 16:29:12 -07003317 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003318 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003319 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003320 const uint32_t what = s.what;
3321 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003322 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003323 disp.surface = s.surface;
3324 flags |= eDisplayTransactionNeeded;
3325 }
3326 }
3327 if (what & DisplayState::eLayerStackChanged) {
3328 if (disp.layerStack != s.layerStack) {
3329 disp.layerStack = s.layerStack;
3330 flags |= eDisplayTransactionNeeded;
3331 }
3332 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003333 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003334 if (disp.orientation != s.orientation) {
3335 disp.orientation = s.orientation;
3336 flags |= eDisplayTransactionNeeded;
3337 }
3338 if (disp.frame != s.frame) {
3339 disp.frame = s.frame;
3340 flags |= eDisplayTransactionNeeded;
3341 }
3342 if (disp.viewport != s.viewport) {
3343 disp.viewport = s.viewport;
3344 flags |= eDisplayTransactionNeeded;
3345 }
3346 }
Michael Lentine47e45402014-07-18 15:34:25 -07003347 if (what & DisplayState::eDisplaySizeChanged) {
3348 if (disp.width != s.width) {
3349 disp.width = s.width;
3350 flags |= eDisplayTransactionNeeded;
3351 }
3352 if (disp.height != s.height) {
3353 disp.height = s.height;
3354 flags |= eDisplayTransactionNeeded;
3355 }
3356 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357 }
3358 return flags;
3359}
3360
Robert Carrd4ae7f32018-06-07 16:10:57 -07003361bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3362 IPCThreadState* ipc = IPCThreadState::self();
3363 const int pid = ipc->getCallingPid();
3364 const int uid = ipc->getCallingUid();
3365
3366 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3367 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3368 return false;
3369 }
3370 return true;
3371}
3372
chaviwca27f252018-02-06 16:46:39 -08003373uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3374 const layer_state_t& s = composerState.state;
3375 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3376
Mathias Agopian13127d82013-03-05 17:47:11 -08003377 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003378 if (layer == nullptr) {
3379 return 0;
3380 }
3381
3382 if (layer->isPendingRemoval()) {
3383 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3384 return 0;
3385 }
3386
3387 uint32_t flags = 0;
3388
3389 const uint32_t what = s.what;
3390 bool geometryAppliesWithResize =
3391 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003392
3393 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3394 // pending state will also be deferred.
3395 if (what & layer_state_t::eDeferTransaction) {
3396 layer->pushPendingState();
3397 }
3398
chaviw8b3871a2017-11-01 17:41:01 -07003399 if (what & layer_state_t::ePositionChanged) {
3400 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3401 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402 }
chaviw8b3871a2017-11-01 17:41:01 -07003403 }
3404 if (what & layer_state_t::eLayerChanged) {
3405 // NOTE: index needs to be calculated before we update the state
3406 const auto& p = layer->getParent();
3407 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003408 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003409 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003410 mCurrentState.layersSortedByZ.removeAt(idx);
3411 mCurrentState.layersSortedByZ.add(layer);
3412 // we need traversal (state changed)
3413 // AND transaction (list changed)
3414 flags |= eTransactionNeeded|eTraversalNeeded;
3415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 } else {
3417 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003418 flags |= eTransactionNeeded|eTraversalNeeded;
3419 }
3420 }
chaviw8b3871a2017-11-01 17:41:01 -07003421 }
3422 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003423 // NOTE: index needs to be calculated before we update the state
3424 const auto& p = layer->getParent();
3425 if (p == nullptr) {
3426 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3427 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3428 mCurrentState.layersSortedByZ.removeAt(idx);
3429 mCurrentState.layersSortedByZ.add(layer);
3430 // we need traversal (state changed)
3431 // AND transaction (list changed)
3432 flags |= eTransactionNeeded|eTraversalNeeded;
3433 }
3434 } else {
3435 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3436 flags |= eTransactionNeeded|eTraversalNeeded;
3437 }
chaviw8b3871a2017-11-01 17:41:01 -07003438 }
3439 }
3440 if (what & layer_state_t::eSizeChanged) {
3441 if (layer->setSize(s.w, s.h)) {
3442 flags |= eTraversalNeeded;
3443 }
3444 }
3445 if (what & layer_state_t::eAlphaChanged) {
3446 if (layer->setAlpha(s.alpha))
3447 flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eColorChanged) {
3450 if (layer->setColor(s.color))
3451 flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003454 // TODO: b/109894387
3455 //
3456 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3457 // rotation. To see the problem observe that if we have a square parent, and a child
3458 // of the same size, then we rotate the child 45 degrees around it's center, the child
3459 // must now be cropped to a non rectangular 8 sided region.
3460 //
3461 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3462 // private API, and the WindowManager only uses rotation in one case, which is on a top
3463 // level layer in which cropping is not an issue.
3464 //
3465 // However given that abuse of rotation matrices could lead to surfaces extending outside
3466 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3467 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3468 // transformations.
3469 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003470 flags |= eTraversalNeeded;
3471 }
3472 if (what & layer_state_t::eTransparentRegionChanged) {
3473 if (layer->setTransparentRegionHint(s.transparentRegion))
3474 flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eFlagsChanged) {
3477 if (layer->setFlags(s.flags, s.mask))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eCropChanged) {
3481 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eFinalCropChanged) {
3485 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eLayerStackChanged) {
3489 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3490 // We only allow setting layer stacks for top level layers,
3491 // everything else inherits layer stack from its parent.
3492 if (layer->hasParent()) {
3493 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3494 layer->getName().string());
3495 } else if (idx < 0) {
3496 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3497 "that also does not appear in the top level layer list. Something"
3498 " has gone wrong.", layer->getName().string());
3499 } else if (layer->setLayerStack(s.layerStack)) {
3500 mCurrentState.layersSortedByZ.removeAt(idx);
3501 mCurrentState.layersSortedByZ.add(layer);
3502 // we need traversal (state changed)
3503 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003504 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003505 }
3506 }
3507 if (what & layer_state_t::eDeferTransaction) {
3508 if (s.barrierHandle != nullptr) {
3509 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3510 } else if (s.barrierGbp != nullptr) {
3511 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3512 if (authenticateSurfaceTextureLocked(gbp)) {
3513 const auto& otherLayer =
3514 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3515 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3516 } else {
3517 ALOGE("Attempt to defer transaction to to an"
3518 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003519 }
3520 }
chaviw8b3871a2017-11-01 17:41:01 -07003521 // We don't trigger a traversal here because if no other state is
3522 // changed, we don't want this to cause any more work
3523 }
3524 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003525 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003527 if (!hadParent) {
3528 mCurrentState.layersSortedByZ.remove(layer);
3529 }
chaviw8b3871a2017-11-01 17:41:01 -07003530 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 }
3533 if (what & layer_state_t::eReparentChildren) {
3534 if (layer->reparentChildren(s.reparentHandle)) {
3535 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003536 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 if (what & layer_state_t::eDetachChildren) {
3539 layer->detachChildren();
3540 }
3541 if (what & layer_state_t::eOverrideScalingModeChanged) {
3542 layer->setOverrideScalingMode(s.overrideScalingMode);
3543 // We don't trigger a traversal here because if no other state is
3544 // changed, we don't want this to cause any more work
3545 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003546 return flags;
3547}
3548
chaviwca27f252018-02-06 16:46:39 -08003549void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3550 const layer_state_t& state = composerState.state;
3551 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3552
3553 sp<Layer> layer(client->getLayerUser(state.surface));
3554 if (layer == nullptr) {
3555 return;
3556 }
3557
3558 if (layer->isPendingRemoval()) {
3559 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3560 return;
3561 }
3562
3563 if (state.what & layer_state_t::eDestroySurface) {
3564 removeLayerLocked(mStateLock, layer);
3565 }
3566}
3567
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003568status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003569 const String8& name,
3570 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003572 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003573 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003575 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003576 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003577 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003579 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003580
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581 status_t result = NO_ERROR;
3582
3583 sp<Layer> layer;
3584
Cody Northropbc755282017-03-31 12:00:08 -06003585 String8 uniqueName = getUniqueLayerName(name);
3586
Mathias Agopian3165cc22012-08-08 19:42:09 -07003587 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3588 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003589 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003590 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593 break;
chaviw13fdc492017-06-27 12:40:18 -07003594 case ISurfaceComposerClient::eFXSurfaceColor:
3595 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003596 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003597 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 break;
3599 default:
3600 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601 break;
3602 }
3603
Dan Stoza7d89d062015-04-30 13:29:25 -07003604 if (result != NO_ERROR) {
3605 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003607
Chia-I Wuab0c3192017-08-01 11:29:00 -07003608 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3609 // TODO b/64227542
3610 if (windowType == 441731) {
3611 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3612 layer->setPrimaryDisplayOnly();
3613 }
3614
Albert Chaulk479c60c2017-01-27 14:21:34 -05003615 layer->setInfo(windowType, ownerUid);
3616
Robert Carr1f0a16a2016-10-24 16:27:39 -07003617 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003618 if (result != NO_ERROR) {
3619 return result;
3620 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003621 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003622
3623 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625}
3626
Cody Northropbc755282017-03-31 12:00:08 -06003627String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3628{
3629 bool matchFound = true;
3630 uint32_t dupeCounter = 0;
3631
3632 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3633 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3634
3635 // Loop over layers until we're sure there is no matching name
3636 while (matchFound) {
3637 matchFound = false;
3638 mDrawingState.traverseInZOrder([&](Layer* layer) {
3639 if (layer->getName() == uniqueName) {
3640 matchFound = true;
3641 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3642 }
3643 });
3644 }
3645
3646 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3647
3648 return uniqueName;
3649}
3650
David Sodman0c69cad2017-08-21 12:12:51 -07003651status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3653 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654{
3655 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003656 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657 case PIXEL_FORMAT_TRANSPARENT:
3658 case PIXEL_FORMAT_TRANSLUCENT:
3659 format = PIXEL_FORMAT_RGBA_8888;
3660 break;
3661 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003662 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663 break;
3664 }
3665
David Sodman0c69cad2017-08-21 12:12:51 -07003666 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3667 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003668 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003669 *handle = layer->getHandle();
3670 *gbp = layer->getProducer();
3671 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003673
David Sodman0c69cad2017-08-21 12:12:51 -07003674 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003675 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003676}
3677
chaviw13fdc492017-06-27 12:40:18 -07003678status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003680 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681{
chaviw13fdc492017-06-27 12:40:18 -07003682 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003683 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003685}
3686
Mathias Agopianac9fa422013-02-11 16:40:36 -08003687status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688{
Robert Carr9524cb32017-02-13 11:32:32 -08003689 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003690 status_t err = NO_ERROR;
3691 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003692 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003693 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003694 err = removeLayer(l);
3695 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3696 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003697 }
3698 return err;
3699}
3700
Mathias Agopian13127d82013-03-05 17:47:11 -08003701status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003702{
Mathias Agopian67106042013-03-14 19:18:13 -07003703 // called by ~LayerCleaner() when all references to the IBinder (handle)
3704 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003705 sp<Layer> l = layer.promote();
3706 if (l == nullptr) {
3707 // The layer has already been removed, carry on
3708 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003709 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003710 // If we have a parent, then we can continue to live as long as it does.
3711 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712}
3713
Mathias Agopianb60314a2012-04-10 22:09:54 -07003714// ---------------------------------------------------------------------------
3715
Andy McFadden13a082e2012-08-24 10:16:42 -07003716void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003717 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003718 Vector<ComposerState> state;
3719 Vector<DisplayState> displays;
3720 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003721 d.what = DisplayState::eDisplayProjectionChanged |
3722 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003723 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003724 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003725 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003726 d.frame.makeInvalid();
3727 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003728 d.width = 0;
3729 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003730 displays.add(d);
3731 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003732 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3733 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003734
David Sodman105b7dc2017-11-04 20:28:14 -07003735 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003736 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003737 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003738
Brian Andersond0010582017-03-07 13:20:31 -08003739 // Use phase of 0 since phase is not known.
3740 // Use latency of 0, which will snap to the ideal latency.
3741 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003742}
3743
3744void SurfaceFlinger::initializeDisplays() {
3745 class MessageScreenInitialized : public MessageBase {
3746 SurfaceFlinger* flinger;
3747 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003748 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003749 virtual bool handler() {
3750 flinger->onInitializeDisplays();
3751 return true;
3752 }
3753 };
3754 sp<MessageBase> msg = new MessageScreenInitialized(this);
3755 postMessageAsync(msg); // we may be called from main thread, use async message
3756}
3757
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003759 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3761 this);
3762 int32_t type = hw->getDisplayType();
3763 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003764
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003766 return;
3767 }
3768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 hw->setPowerMode(mode);
3770 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3771 ALOGW("Trying to set power mode for virtual display");
3772 return;
3773 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774
Lloyd Pique4d234852018-01-22 17:21:36 -08003775 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003776 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003777 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3778 if (idx < 0) {
3779 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3780 return;
3781 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003782 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003783 }
3784
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003786 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003788 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3789 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 // FIXME: eventthread only knows about the main display right now
3791 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003792 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003794
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003796 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003797 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003798
3799 struct sched_param param = {0};
3800 param.sched_priority = 1;
3801 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3802 ALOGW("Couldn't set SCHED_FIFO on display on");
3803 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003805 // Turn off the display
3806 struct sched_param param = {0};
3807 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3808 ALOGW("Couldn't set SCHED_OTHER on display off");
3809 }
3810
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003811 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3812 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003813 disableHardwareVsync(true); // also cancels any in-progress resync
3814
Mathias Agopiancde87a32012-09-13 14:09:01 -07003815 // FIXME: eventthread only knows about the main display right now
3816 mEventThread->onScreenReleased();
3817 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003818
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003819 getHwComposer().setPowerMode(type, mode);
3820 mVisibleRegionsDirty = true;
3821 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003822 } else if (mode == HWC_POWER_MODE_DOZE ||
3823 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003824 // Update display while dozing
3825 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003826 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3827 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003828 // FIXME: eventthread only knows about the main display right now
3829 mEventThread->onScreenAcquired();
3830 resyncToHardwareVsync(true);
3831 }
3832 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3833 // Leave display going to doze
3834 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3835 disableHardwareVsync(true); // also cancels any in-progress resync
3836 // FIXME: eventthread only knows about the main display right now
3837 mEventThread->onScreenReleased();
3838 }
3839 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003840 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003841 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003843 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003844 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003845}
3846
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3848 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003849 SurfaceFlinger& mFlinger;
3850 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 MessageSetPowerMode(SurfaceFlinger& flinger,
3854 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3855 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003856 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003858 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003860 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003861 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 ALOGW("Attempt to set power mode = %d for virtual display",
3863 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003864 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003865 mFlinger.setPowerModeInternal(
3866 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003867 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003868 return true;
3869 }
3870 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003872 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003873}
3874
3875// ---------------------------------------------------------------------------
3876
Lloyd Pique755e3192018-01-31 16:46:15 -08003877status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3878 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003880
Mathias Agopianbd115332013-04-18 16:41:04 -07003881 IPCThreadState* ipc = IPCThreadState::self();
3882 const int pid = ipc->getCallingPid();
3883 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003884
Mathias Agopianbd115332013-04-18 16:41:04 -07003885 if ((uid != AID_SHELL) &&
3886 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003887 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003888 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003890 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003891 // (this would indicate SF is stuck, but we want to be able to
3892 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003893 status_t err = mStateLock.timedLock(s2ns(1));
3894 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003895 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003896 result.appendFormat(
3897 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3898 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003899 }
3900
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003901 bool dumpAll = true;
3902 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003903 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003904
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003905 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003906 if ((index < numArgs) &&
3907 (args[index] == String16("--list"))) {
3908 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003910 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911 }
3912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003915 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003916 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003917 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--latency-clear"))) {
3922 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003924 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003926
3927 if ((index < numArgs) &&
3928 (args[index] == String16("--dispsync"))) {
3929 index++;
3930 mPrimaryDispSync.dump(result);
3931 dumpAll = false;
3932 }
Dan Stozab90cf072015-03-05 11:05:59 -08003933
3934 if ((index < numArgs) &&
3935 (args[index] == String16("--static-screen"))) {
3936 index++;
3937 dumpStaticScreenStats(result);
3938 dumpAll = false;
3939 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003940
3941 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003942 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003943 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003944 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003945 dumpAll = false;
3946 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003947
3948 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3949 index++;
3950 dumpWideColorInfo(result);
3951 dumpAll = false;
3952 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003953
3954 if ((index < numArgs) &&
3955 (args[index] == String16("--enable-layer-stats"))) {
3956 index++;
3957 mLayerStats.enable();
3958 dumpAll = false;
3959 }
3960
3961 if ((index < numArgs) &&
3962 (args[index] == String16("--disable-layer-stats"))) {
3963 index++;
3964 mLayerStats.disable();
3965 dumpAll = false;
3966 }
3967
3968 if ((index < numArgs) &&
3969 (args[index] == String16("--clear-layer-stats"))) {
3970 index++;
3971 mLayerStats.clear();
3972 dumpAll = false;
3973 }
3974
3975 if ((index < numArgs) &&
3976 (args[index] == String16("--dump-layer-stats"))) {
3977 index++;
3978 mLayerStats.dump(result);
3979 dumpAll = false;
3980 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003981
3982 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3983 index++;
3984 mTimeStats.parseArgs(asProto, args, index, result);
3985 dumpAll = false;
3986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003988
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003990 if (asProto) {
3991 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3992 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3993 } else {
3994 dumpAllLocked(args, index, result);
3995 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003996 }
3997
Mathias Agopian9795c422009-08-26 16:36:26 -07003998 if (locked) {
3999 mStateLock.unlock();
4000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 }
4002 write(fd, result.string(), result.size());
4003 return NO_ERROR;
4004}
4005
Dan Stozac7014012014-02-14 15:03:43 -08004006void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4007 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008{
Robert Carr2047fae2016-11-28 14:09:09 -08004009 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004010 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004011 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004012}
4013
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004016{
4017 String8 name;
4018 if (index < args.size()) {
4019 name = String8(args[index]);
4020 index++;
4021 }
4022
David Sodman105b7dc2017-11-04 20:28:14 -07004023 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004024 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004025 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004026
4027 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004028 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004029 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004030 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004031 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004032 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004033 }
Robert Carr2047fae2016-11-28 14:09:09 -08004034 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035 }
4036}
4037
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004038void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004039 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004040{
4041 String8 name;
4042 if (index < args.size()) {
4043 name = String8(args[index]);
4044 index++;
4045 }
4046
Robert Carr2047fae2016-11-28 14:09:09 -08004047 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004048 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004049 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050 }
Robert Carr2047fae2016-11-28 14:09:09 -08004051 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004052
Svetoslavd85084b2014-03-20 10:28:31 -07004053 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054}
4055
Jamie Gennis6547ff42013-07-16 20:12:42 -07004056// This should only be called from the main thread. Otherwise it would need
4057// the lock and should use mCurrentState rather than mDrawingState.
4058void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004059 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004060 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004061 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004062
4063 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4064}
4065
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004066void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004067{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004068 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004069
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004070 if (isLayerTripleBufferingDisabled())
4071 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004072
4073 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004074 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004075 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004076 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004077 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4078 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004079 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004080}
4081
Dan Stozab90cf072015-03-05 11:05:59 -08004082void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4083{
4084 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004085 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4086 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004087 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004088 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004089 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4090 b + 1, bucketTimeSec, percent);
4091 }
David Sodman4a36e932017-11-07 14:29:47 -08004092 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004093 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004094 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004095 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004096 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004097}
4098
Dan Stozae77c7662016-05-13 11:37:28 -07004099void SurfaceFlinger::recordBufferingStats(const char* layerName,
4100 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004101 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4102 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004103 for (const auto& segment : history) {
4104 if (!segment.usedThirdBuffer) {
4105 stats.twoBufferTime += segment.totalTime;
4106 }
4107 if (segment.occupancyAverage < 1.0f) {
4108 stats.doubleBufferedTime += segment.totalTime;
4109 } else if (segment.occupancyAverage < 2.0f) {
4110 stats.tripleBufferedTime += segment.totalTime;
4111 }
4112 ++stats.numSegments;
4113 stats.totalTime += segment.totalTime;
4114 }
4115}
4116
Brian Andersond6927fb2016-07-23 23:37:30 -07004117void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4118 result.appendFormat("Layer frame timestamps:\n");
4119
4120 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4121 const size_t count = currentLayers.size();
4122 for (size_t i=0 ; i<count ; i++) {
4123 currentLayers[i]->dumpFrameEvents(result);
4124 }
4125}
4126
Dan Stozae77c7662016-05-13 11:37:28 -07004127void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4128 result.append("Buffering stats:\n");
4129 result.append(" [Layer name] <Active time> <Two buffer> "
4130 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004131 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004132 typedef std::tuple<std::string, float, float, float> BufferTuple;
4133 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004134 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004135 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004136 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004137 if (stats.numSegments == 0) {
4138 continue;
4139 }
4140 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4141 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4142 stats.totalTime;
4143 float doubleBufferRatio = static_cast<float>(
4144 stats.doubleBufferedTime) / stats.totalTime;
4145 float tripleBufferRatio = static_cast<float>(
4146 stats.tripleBufferedTime) / stats.totalTime;
4147 sorted.insert({activeTime, {name, twoBufferRatio,
4148 doubleBufferRatio, tripleBufferRatio}});
4149 }
4150 for (const auto& sortedPair : sorted) {
4151 float activeTime = sortedPair.first;
4152 const BufferTuple& values = sortedPair.second;
4153 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4154 std::get<0>(values).c_str(), activeTime,
4155 std::get<1>(values), std::get<2>(values),
4156 std::get<3>(values));
4157 }
4158 result.append("\n");
4159}
4160
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004161void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4162 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004163 result.appendFormat("DisplayColorSetting: %s\n",
4164 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165
4166 // TODO: print out if wide-color mode is active or not
4167
4168 for (size_t d = 0; d < mDisplays.size(); d++) {
4169 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4170 int32_t hwcId = displayDevice->getHwcDisplayId();
4171 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4172 continue;
4173 }
4174
4175 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004176 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004177 for (auto&& mode : modes) {
4178 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4179 }
4180
Peiyong Lina52f0292018-03-14 17:26:31 -07004181 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004182 result.appendFormat(" Current color mode: %s (%d)\n",
4183 decodeColorMode(currentMode).c_str(), currentMode);
4184 }
4185 result.append("\n");
4186}
4187
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004188LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004189 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004190 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4191 const State& state = useDrawing ? mDrawingState : mCurrentState;
4192 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004193 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004194 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004195 });
4196
4197 return layersProto;
4198}
4199
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004200LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4201 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004202 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004203
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004204 SizeProto* resolution = layersProto.mutable_resolution();
4205 resolution->set_w(displayDevice->getWidth());
4206 resolution->set_h(displayDevice->getHeight());
4207
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004208 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4209 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4210 layersProto.set_global_transform(
4211 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4212
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004213 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004214 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004215 LayerProto* layerProto = layersProto.add_layers();
4216 layer->writeToProto(layerProto, hwcId);
4217 }
4218 });
4219
4220 return layersProto;
4221}
4222
Mathias Agopian74d211a2013-04-22 16:55:35 +02004223void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4224 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 bool colorize = false;
4227 if (index < args.size()
4228 && (args[index] == String16("--color"))) {
4229 colorize = true;
4230 index++;
4231 }
4232
4233 Colorizer colorizer(colorize);
4234
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235 // figure out if we're stuck somewhere
4236 const nsecs_t now = systemTime();
4237 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4238 const nsecs_t inTransaction(mDebugInTransaction);
4239 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4240 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4241
4242 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004243 * Dump library configuration.
4244 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245
4246 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004247 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004249 appendSfConfigString(result);
4250 appendUiConfigString(result);
4251 appendGuiConfigString(result);
4252 result.append("\n");
4253
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004254 result.append("\nWide-Color information:\n");
4255 dumpWideColorInfo(result);
4256
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004258 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004259 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004260 result.append(SyncFeatures::getInstance().toString());
4261 result.append("\n");
4262
David Sodman105b7dc2017-11-04 20:28:14 -07004263 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004264
Andy McFadden41d67d72014-04-25 16:58:34 -07004265 colorizer.bold(result);
4266 result.append("DispSync configuration: ");
4267 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004268 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4269 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4270 result.appendFormat(
4271 "app phase %" PRId64 " ns, "
4272 "sf phase %" PRId64 " ns, "
4273 "early app phase %" PRId64 " ns, "
4274 "early sf phase %" PRId64 " ns, "
4275 "early app gl phase %" PRId64 " ns, "
4276 "early sf gl phase %" PRId64 " ns, "
4277 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4278 vsyncPhaseOffsetNs,
4279 sfVsyncPhaseOffsetNs,
4280 appEarlyOffset,
4281 sfEarlyOffset,
4282 appEarlyGlOffset,
4283 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004284 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004285 result.append("\n");
4286
Dan Stozab90cf072015-03-05 11:05:59 -08004287 // Dump static screen stats
4288 result.append("\n");
4289 dumpStaticScreenStats(result);
4290 result.append("\n");
4291
Dan Stozae77c7662016-05-13 11:37:28 -07004292 dumpBufferingStats(result);
4293
Andy McFadden4803b742012-09-24 19:07:20 -07004294 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295 * Dump the visible layer list
4296 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004298 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004299 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4300 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004302
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004303 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004304 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004305 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004306 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307
4308 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004309 * Dump Display state
4310 */
4311
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004313 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004314 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004315 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4316 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004317 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004318 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004319 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004320
4321 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004322 * Dump SurfaceFlinger global state
4323 */
4324
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004326 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004327 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328
Mathias Agopian888c8222012-08-04 21:10:38 -07004329 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004330 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004331
David Sodmanbc815282017-11-05 18:57:52 -08004332 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004334 if (hw) {
4335 hw->undefinedRegion.dump(result, "undefinedRegion");
4336 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4337 hw->getOrientation(), hw->isDisplayOn());
4338 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004339 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340 " last eglSwapBuffers() time: %f us\n"
4341 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004342 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 " refresh-rate : %f fps\n"
4344 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004345 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004346 " gpu_to_cpu_unsupported : %d\n"
4347 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348 mLastSwapBufferTime/1000.0,
4349 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004350 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004351 1e9 / activeConfig->getVsyncPeriod(),
4352 activeConfig->getDpiX(),
4353 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004354 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
Mathias Agopian74d211a2013-04-22 16:55:35 +02004356 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004358
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361
4362 /*
4363 * VSYNC state
4364 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004366 result.append("\n");
4367
4368 /*
4369 * HWC layer minidump
4370 */
4371 for (size_t d = 0; d < mDisplays.size(); d++) {
4372 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4373 int32_t hwcId = displayDevice->getHwcDisplayId();
4374 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4375 continue;
4376 }
4377
4378 result.appendFormat("Display %d HWC layers:\n", hwcId);
4379 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004380 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004381 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004382 });
Dan Stozae22aec72016-08-01 13:20:59 -07004383 result.append("\n");
4384 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385
4386 /*
4387 * Dump HWComposer state
4388 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004389 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004390 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004391 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004392 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004393 result.appendFormat(" h/w composer %s\n",
4394 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004395 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396
4397 /*
4398 * Dump gralloc state
4399 */
4400 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4401 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004402
4403 /*
4404 * Dump VrFlinger state if in use.
4405 */
4406 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4407 result.append("VrFlinger state:\n");
4408 result.append(mVrFlinger->Dump().c_str());
4409 result.append("\n");
4410 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411}
4412
Mathias Agopian13127d82013-03-05 17:47:11 -08004413const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004414SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004415 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004416 wp<IBinder> dpy;
4417 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4418 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4419 dpy = mDisplays.keyAt(i);
4420 break;
4421 }
4422 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004423 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004424 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4425 // Just use the primary display so we have something to return
4426 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4427 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004428 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004429}
4430
Keun young Park63f165f2012-08-31 10:53:36 -07004431bool SurfaceFlinger::startDdmConnection()
4432{
4433 void* libddmconnection_dso =
4434 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4435 if (!libddmconnection_dso) {
4436 return false;
4437 }
4438 void (*DdmConnection_start)(const char* name);
4439 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004440 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004441 if (!DdmConnection_start) {
4442 dlclose(libddmconnection_dso);
4443 return false;
4444 }
4445 (*DdmConnection_start)(getServiceName());
4446 return true;
4447}
4448
Chia-I Wu28f320b2018-05-03 11:02:56 -07004449void SurfaceFlinger::updateColorMatrixLocked() {
4450 mat4 colorMatrix;
4451 if (mGlobalSaturationFactor != 1.0f) {
4452 // Rec.709 luma coefficients
4453 float3 luminance{0.213f, 0.715f, 0.072f};
4454 luminance *= 1.0f - mGlobalSaturationFactor;
4455 mat4 saturationMatrix = mat4(
4456 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4457 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4458 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4459 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4460 );
4461 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4462 } else {
4463 colorMatrix = mClientColorMatrix * mDaltonizer();
4464 }
4465
4466 if (mCurrentState.colorMatrix != colorMatrix) {
4467 mCurrentState.colorMatrix = colorMatrix;
4468 mCurrentState.colorMatrixChanged = true;
4469 setTransactionFlags(eTransactionNeeded);
4470 }
4471}
4472
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004473status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 switch (code) {
4475 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004476 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004478 case CLEAR_ANIMATION_FRAME_STATS:
4479 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004480 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004481 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004482 case ENABLE_VSYNC_INJECTIONS:
4483 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 {
4485 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004486 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4487 IPCThreadState* ipc = IPCThreadState::self();
4488 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4489 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004490 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004491 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004492 break;
4493 }
Robert Carr1db73f62016-12-21 12:58:51 -08004494 /*
4495 * Calling setTransactionState is safe, because you need to have been
4496 * granted a reference to Client* and Handle* to do anything with it.
4497 *
4498 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4499 */
4500 case SET_TRANSACTION_STATE:
4501 case CREATE_SCOPED_CONNECTION:
4502 {
4503 return OK;
4504 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004505 case CAPTURE_SCREEN:
4506 {
4507 // codes that require permission check
4508 IPCThreadState* ipc = IPCThreadState::self();
4509 const int pid = ipc->getCallingPid();
4510 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004511 if ((uid != AID_GRAPHICS) &&
4512 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004513 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004514 return PERMISSION_DENIED;
4515 }
4516 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 }
chaviwa76b2712017-09-20 12:02:26 -07004518 case CAPTURE_LAYERS: {
4519 IPCThreadState* ipc = IPCThreadState::self();
4520 const int pid = ipc->getCallingPid();
4521 const int uid = ipc->getCallingUid();
4522 if ((uid != AID_GRAPHICS) &&
4523 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4524 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4525 return PERMISSION_DENIED;
4526 }
4527 break;
4528 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004530 return OK;
4531}
4532
4533status_t SurfaceFlinger::onTransact(
4534 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4535{
4536 status_t credentialCheck = CheckTransactCodeCredentials(code);
4537 if (credentialCheck != OK) {
4538 return credentialCheck;
4539 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4542 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004543 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004544 IPCThreadState* ipc = IPCThreadState::self();
4545 const int uid = ipc->getCallingUid();
4546 if (CC_UNLIKELY(uid != AID_SYSTEM
4547 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004548 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004549 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004550 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 return PERMISSION_DENIED;
4552 }
4553 int n;
4554 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004555 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004556 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 return NO_ERROR;
4558 case 1002: // SHOW_UPDATES
4559 n = data.readInt32();
4560 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004561 invalidateHwcGeometry();
4562 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004565 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004566 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004568 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004569 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004570 setTransactionFlags(
4571 eTransactionNeeded|
4572 eDisplayTransactionNeeded|
4573 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004574 return NO_ERROR;
4575 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004576 case 1006:{ // send empty update
4577 signalRefresh();
4578 return NO_ERROR;
4579 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004580 case 1008: // toggle use of hw composer
4581 n = data.readInt32();
4582 mDebugDisableHWC = n ? 1 : 0;
4583 invalidateHwcGeometry();
4584 repaintEverything();
4585 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004586 case 1009: // toggle use of transform hint
4587 n = data.readInt32();
4588 mDebugDisableTransformHint = n ? 1 : 0;
4589 invalidateHwcGeometry();
4590 repaintEverything();
4591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004593 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 reply->writeInt32(0);
4595 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004596 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004597 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 return NO_ERROR;
4599 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004600 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004601 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004602 return NO_ERROR;
4603 }
4604 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004605 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004606 // daltonize
4607 n = data.readInt32();
4608 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004609 case 1:
4610 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4611 break;
4612 case 2:
4613 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4614 break;
4615 case 3:
4616 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4617 break;
4618 default:
4619 mDaltonizer.setType(ColorBlindnessType::None);
4620 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004621 }
4622 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004623 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004624 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004625 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004626 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004627
4628 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004629 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004630 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004633 // apply a color matrix
4634 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004636 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004637 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004638 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004639 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004640 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004642 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004643 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004644 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004645
4646 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4647 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004648 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004649 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4650 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4651 }
4652
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004654 return NO_ERROR;
4655 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004656 // This is an experimental interface
4657 // Needs to be shifted to proper binder interface when we productize
4658 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004659 n = data.readInt32();
4660 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004661 return NO_ERROR;
4662 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004663 case 1017: {
4664 n = data.readInt32();
4665 mForceFullDamage = static_cast<bool>(n);
4666 return NO_ERROR;
4667 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004668 case 1018: { // Modify Choreographer's phase offset
4669 n = data.readInt32();
4670 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4671 return NO_ERROR;
4672 }
4673 case 1019: { // Modify SurfaceFlinger's phase offset
4674 n = data.readInt32();
4675 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4676 return NO_ERROR;
4677 }
Irvel468051e2016-06-13 16:44:44 -07004678 case 1020: { // Layer updates interceptor
4679 n = data.readInt32();
4680 if (n) {
4681 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004682 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004683 }
4684 else{
4685 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004686 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004687 }
4688 return NO_ERROR;
4689 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004690 case 1021: { // Disable HWC virtual displays
4691 n = data.readInt32();
4692 mUseHwcVirtualDisplays = !n;
4693 return NO_ERROR;
4694 }
Romain Guy0147a172017-06-01 13:53:56 -07004695 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004697 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004698
Chia-I Wu28f320b2018-05-03 11:02:56 -07004699 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004700 return NO_ERROR;
4701 }
Romain Guy54f154a2017-10-24 21:40:32 +01004702 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004703 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004704 invalidateHwcGeometry();
4705 repaintEverything();
4706 return NO_ERROR;
4707 }
4708 case 1024: { // Is wide color gamut rendering/color management supported?
4709 reply->writeBool(hasWideColorDisplay);
4710 return NO_ERROR;
4711 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004712 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004713 n = data.readInt32();
4714 if (n) {
4715 ALOGV("LayerTracing enabled");
4716 mTracing.enable();
4717 doTracing("tracing.enable");
4718 reply->writeInt32(NO_ERROR);
4719 } else {
4720 ALOGV("LayerTracing disabled");
4721 status_t err = mTracing.disable();
4722 reply->writeInt32(err);
4723 }
4724 return NO_ERROR;
4725 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004726 case 1026: { // Get layer tracing status
4727 reply->writeBool(mTracing.isEnabled());
4728 return NO_ERROR;
4729 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004730 // Is a DisplayColorSetting supported?
4731 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004732 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4733 if (!hw) {
4734 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004736
4737 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4738 switch (setting) {
4739 case DisplayColorSetting::MANAGED:
4740 reply->writeBool(hasWideColorDisplay);
4741 break;
4742 case DisplayColorSetting::UNMANAGED:
4743 reply->writeBool(true);
4744 break;
4745 case DisplayColorSetting::ENHANCED:
4746 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4747 break;
4748 default: // vendor display color setting
4749 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4750 break;
4751 }
4752 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004753 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004754 }
4755 }
4756 return err;
4757}
4758
Steven Thomas6d8110b2017-08-31 18:24:21 -07004759void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004760 android_atomic_or(1, &mRepaintEverything);
4761 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004762}
4763
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004764// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4765class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004766public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004767 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4768 ~WindowDisconnector() {
4769 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004770 }
4771
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004772private:
4773 ANativeWindow* mWindow;
4774 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004775};
4776
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004777status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4778 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4779 int32_t minLayerZ, int32_t maxLayerZ,
4780 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004781 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004782 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004783
chaviwa76b2712017-09-20 12:02:26 -07004784 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4785
4786 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004787 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4788
chaviwa76b2712017-09-20 12:02:26 -07004789 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4790
4791 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4792 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004793 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004794}
4795
4796status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004797 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004798 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004799 ATRACE_CALL();
4800
4801 class LayerRenderArea : public RenderArea {
4802 public:
Robert Carr578038f2018-03-09 12:25:24 -08004803 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4804 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004805 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004806 mLayer(layer),
4807 mCrop(crop),
4808 mFlinger(flinger),
4809 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004810 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004811 Rect getBounds() const override {
4812 const Layer::State& layerState(mLayer->getDrawingState());
4813 return Rect(layerState.active.w, layerState.active.h);
4814 }
4815 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4816 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4817 bool isSecure() const override { return false; }
4818 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004819 Rect getSourceCrop() const override {
4820 if (mCrop.isEmpty()) {
4821 return getBounds();
4822 } else {
4823 return mCrop;
4824 }
4825 }
Robert Carr578038f2018-03-09 12:25:24 -08004826 class ReparentForDrawing {
4827 public:
4828 const sp<Layer>& oldParent;
4829 const sp<Layer>& newParent;
4830
4831 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4832 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004833 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004834 }
Robert Carr15eae092018-03-23 13:43:53 -07004835 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004836 };
4837
4838 void render(std::function<void()> drawLayers) override {
4839 if (!mChildrenOnly) {
4840 mTransform = mLayer->getTransform().inverse();
4841 drawLayers();
4842 } else {
4843 Rect bounds = getBounds();
4844 screenshotParentLayer =
4845 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4846 bounds.getWidth(), bounds.getHeight(), 0);
4847
4848 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4849 drawLayers();
4850 }
4851 }
chaviwa76b2712017-09-20 12:02:26 -07004852
chaviwa76b2712017-09-20 12:02:26 -07004853 private:
chaviw7206d492017-11-10 16:16:12 -08004854 const sp<Layer> mLayer;
4855 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004856
4857 // In the "childrenOnly" case we reparent the children to a screenshot
4858 // layer which has no properties set and which does not draw.
4859 sp<ContainerLayer> screenshotParentLayer;
4860 Transform mTransform;
4861
4862 SurfaceFlinger* mFlinger;
4863 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004864 };
4865
4866 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4867 auto parent = layerHandle->owner.promote();
4868
chaviw7206d492017-11-10 16:16:12 -08004869 if (parent == nullptr || parent->isPendingRemoval()) {
4870 ALOGE("captureLayers called with a removed parent");
4871 return NAME_NOT_FOUND;
4872 }
4873
Robert Carr578038f2018-03-09 12:25:24 -08004874 const int uid = IPCThreadState::self()->getCallingUid();
4875 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4876 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4877 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4878 return PERMISSION_DENIED;
4879 }
4880
chaviw7206d492017-11-10 16:16:12 -08004881 Rect crop(sourceCrop);
4882 if (sourceCrop.width() <= 0) {
4883 crop.left = 0;
4884 crop.right = parent->getCurrentState().active.w;
4885 }
4886
4887 if (sourceCrop.height() <= 0) {
4888 crop.top = 0;
4889 crop.bottom = parent->getCurrentState().active.h;
4890 }
4891
4892 int32_t reqWidth = crop.width() * frameScale;
4893 int32_t reqHeight = crop.height() * frameScale;
4894
Robert Carr578038f2018-03-09 12:25:24 -08004895 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004896
Robert Carr578038f2018-03-09 12:25:24 -08004897 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004898 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4899 if (!layer->isVisible()) {
4900 return;
Robert Carr578038f2018-03-09 12:25:24 -08004901 } else if (childrenOnly && layer == parent.get()) {
4902 return;
chaviwa76b2712017-09-20 12:02:26 -07004903 }
4904 visitor(layer);
4905 });
4906 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004907 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004908}
4909
4910status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4911 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004912 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004913 bool useIdentityTransform) {
4914 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004915
Iris Chang7501ed62018-04-30 14:45:42 +08004916 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004917
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004918 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4919 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4920 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4921 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004922
4923 // This mutex protects syncFd and captureResult for communication of the return values from the
4924 // main thread back to this Binder thread
4925 std::mutex captureMutex;
4926 std::condition_variable captureCondition;
4927 std::unique_lock<std::mutex> captureLock(captureMutex);
4928 int syncFd = -1;
4929 std::optional<status_t> captureResult;
4930
Robert Carr03480e22018-01-04 16:02:06 -08004931 const int uid = IPCThreadState::self()->getCallingUid();
4932 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4933
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004934 sp<LambdaMessage> message = new LambdaMessage([&]() {
4935 // If there is a refresh pending, bug out early and tell the binder thread to try again
4936 // after the refresh.
4937 if (mRefreshPending) {
4938 ATRACE_NAME("Skipping screenshot for now");
4939 std::unique_lock<std::mutex> captureLock(captureMutex);
4940 captureResult = std::make_optional<status_t>(EAGAIN);
4941 captureCondition.notify_one();
4942 return;
4943 }
4944
4945 status_t result = NO_ERROR;
4946 int fd = -1;
4947 {
4948 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004949 renderArea.render([&]() {
4950 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4951 useIdentityTransform, forSystem, &fd);
4952 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004953 }
4954
4955 {
4956 std::unique_lock<std::mutex> captureLock(captureMutex);
4957 syncFd = fd;
4958 captureResult = std::make_optional<status_t>(result);
4959 captureCondition.notify_one();
4960 }
4961 });
4962
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004963 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004964 if (result == NO_ERROR) {
4965 captureCondition.wait(captureLock, [&]() { return captureResult; });
4966 while (*captureResult == EAGAIN) {
4967 captureResult.reset();
4968 result = postMessageAsync(message);
4969 if (result != NO_ERROR) {
4970 return result;
4971 }
4972 captureCondition.wait(captureLock, [&]() { return captureResult; });
4973 }
4974 result = *captureResult;
4975 }
4976
4977 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004978 sync_wait(syncFd, -1);
4979 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004982 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004983}
4984
chaviwa76b2712017-09-20 12:02:26 -07004985void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4986 TraverseLayersFunction traverseLayers, bool yswap,
4987 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004989
Lloyd Pique144e1162017-12-20 16:44:52 -08004990 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004991
4992 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004993 const auto raWidth = renderArea.getWidth();
4994 const auto raHeight = renderArea.getHeight();
4995
4996 const auto reqWidth = renderArea.getReqWidth();
4997 const auto reqHeight = renderArea.getReqHeight();
4998 Rect sourceCrop = renderArea.getSourceCrop();
4999
Iris Chang7501ed62018-04-30 14:45:42 +08005000 bool filtering = false;
5001 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5002 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5003 static_cast<int32_t>(reqHeight) != raWidth;
5004 } else {
5005 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5006 static_cast<int32_t>(reqHeight) != raHeight;
5007 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005008
Dan Stozac1879002014-05-22 15:59:05 -07005009 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005010 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005011 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005012 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005013 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5014 Transform tr;
5015 uint32_t flags = 0x00;
5016 switch (mPrimaryDisplayOrientation) {
5017 case DisplayState::eOrientation90:
5018 flags = Transform::ROT_90;
5019 break;
5020 case DisplayState::eOrientation180:
5021 flags = Transform::ROT_180;
5022 break;
5023 case DisplayState::eOrientation270:
5024 flags = Transform::ROT_270;
5025 break;
5026 }
5027 tr.set(flags, raWidth, raHeight);
5028 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005029 }
5030
5031 // ensure that sourceCrop is inside screen
5032 if (sourceCrop.left < 0) {
5033 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5034 }
chaviwa76b2712017-09-20 12:02:26 -07005035 if (sourceCrop.right > raWidth) {
5036 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005037 }
5038 if (sourceCrop.top < 0) {
5039 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5040 }
chaviwa76b2712017-09-20 12:02:26 -07005041 if (sourceCrop.bottom > raHeight) {
5042 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005043 }
5044
Chia-I Wu36574d92018-05-16 10:54:36 -07005045 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5046 engine.setOutputDataSpace(Dataspace::SRGB);
5047 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005048
Mathias Agopian180f10d2013-04-10 22:55:41 -07005049 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005050 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005051
Iris Chang7501ed62018-04-30 14:45:42 +08005052 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5053 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5054 // convert hw orientation into flag presentation
5055 // here inverse transform needed
5056 uint8_t hw_rot_90 = 0x00;
5057 uint8_t hw_flip_hv = 0x00;
5058 switch (mPrimaryDisplayOrientation) {
5059 case DisplayState::eOrientation90:
5060 hw_rot_90 = Transform::ROT_90;
5061 hw_flip_hv = Transform::ROT_180;
5062 break;
5063 case DisplayState::eOrientation180:
5064 hw_flip_hv = Transform::ROT_180;
5065 break;
5066 case DisplayState::eOrientation270:
5067 hw_rot_90 = Transform::ROT_90;
5068 break;
5069 }
5070
5071 // transform flags operation
5072 // 1) flip H V if both have ROT_90 flag
5073 // 2) XOR these flags
5074 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5075 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5076 if (rotation_rot_90 & hw_rot_90) {
5077 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5078 }
5079 rotation = static_cast<Transform::orientation_flags>
5080 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5081 }
5082
Mathias Agopian180f10d2013-04-10 22:55:41 -07005083 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005084 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005085 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005086 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005087
chaviw50da5042018-04-09 13:49:37 -07005088 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005089 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005090 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005091
chaviwa76b2712017-09-20 12:02:26 -07005092 traverseLayers([&](Layer* layer) {
5093 if (filtering) layer->setFiltering(true);
5094 layer->draw(renderArea, useIdentityTransform);
5095 if (filtering) layer->setFiltering(false);
5096 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005097}
5098
chaviwa76b2712017-09-20 12:02:26 -07005099status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5100 TraverseLayersFunction traverseLayers,
5101 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005102 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005103 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005104 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005105 ATRACE_CALL();
5106
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005107 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005108
5109 traverseLayers([&](Layer* layer) {
5110 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5111 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005112
Robert Carr03480e22018-01-04 16:02:06 -08005113 // We allow the system server to take screenshots of secure layers for
5114 // use in situations like the Screen-rotation animation and place
5115 // the impetus on WindowManager to not persist them.
5116 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005117 ALOGW("FB is protected: PERMISSION_DENIED");
5118 return PERMISSION_DENIED;
5119 }
5120
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005121 // this binds the given EGLImage as a framebuffer for the
5122 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005123 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005124 if (bufferBond.getStatus() != NO_ERROR) {
5125 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005126 return INVALID_OPERATION;
5127 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005128
Dan Stozaabcda352017-06-01 14:37:39 -07005129 // this will in fact render into our dequeued buffer
5130 // via an FBO, which means we didn't have to create
5131 // an EGLSurface and therefore we're not
5132 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005133 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005134
Dan Stozaabcda352017-06-01 14:37:39 -07005135 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005136 getRenderEngine().finish();
5137 *outSyncFd = -1;
5138
chaviwa76b2712017-09-20 12:02:26 -07005139 const auto reqWidth = renderArea.getReqWidth();
5140 const auto reqHeight = renderArea.getReqHeight();
5141
Dan Stozaabcda352017-06-01 14:37:39 -07005142 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5143 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005144 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005145 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005146 } else {
5147 base::unique_fd syncFd = getRenderEngine().flush();
5148 if (syncFd < 0) {
5149 getRenderEngine().finish();
5150 }
5151 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005152 }
5153
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005154 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005155}
5156
Mathias Agopiand5556842013-09-19 17:08:37 -07005157void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005158 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005159 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005160 for (size_t y = 0; y < h; y++) {
5161 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5162 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005163 if (p[x] != 0xFF000000) return;
5164 }
5165 }
chaviwa76b2712017-09-20 12:02:26 -07005166 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005167
Robert Carr2047fae2016-11-28 14:09:09 -08005168 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005169 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005170 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005171 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5172 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5173 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5174 static_cast<float>(state.color.a));
5175 i++;
5176 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005177 }
5178}
5179
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005180// ---------------------------------------------------------------------------
5181
Dan Stoza412903f2017-04-27 13:42:17 -07005182void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5183 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005184}
5185
Dan Stoza412903f2017-04-27 13:42:17 -07005186void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5187 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005188}
5189
chaviwa76b2712017-09-20 12:02:26 -07005190void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5191 int32_t maxLayerZ,
5192 const LayerVector::Visitor& visitor) {
5193 // We loop through the first level of layers without traversing,
5194 // as we need to interpret min/max layer Z in the top level Z space.
5195 for (const auto& layer : mDrawingState.layersSortedByZ) {
5196 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5197 continue;
5198 }
5199 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005200 // relative layers are traversed in Layer::traverseInZOrder
5201 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005202 continue;
5203 }
5204 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005205 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5206 return;
5207 }
chaviwa76b2712017-09-20 12:02:26 -07005208 if (!layer->isVisible()) {
5209 return;
5210 }
5211 visitor(layer);
5212 });
5213 }
5214}
5215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005216}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005217
5218
5219#if defined(__gl_h_)
5220#error "don't include gl/gl.h in this file"
5221#endif
5222
5223#if defined(__gl2_h_)
5224#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005225#endif