blob: 6ebff31a7612498f2e7f822f7fb33a5094074528 [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
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700506uint32_t SurfaceFlinger::getNewTexture() {
507 {
508 std::lock_guard lock(mTexturePoolMutex);
509 if (!mTexturePool.empty()) {
510 uint32_t name = mTexturePool.back();
511 mTexturePool.pop_back();
512 ATRACE_INT("TexturePoolSize", mTexturePool.size());
513 return name;
514 }
515
516 // The pool was too small, so increase it for the future
517 ++mTexturePoolSize;
518 }
519
520 // The pool was empty, so we need to get a new texture name directly using a
521 // blocking call to the main thread
522 uint32_t name = 0;
523 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
524 return name;
525}
526
Mathias Agopian3f844832013-08-07 21:24:32 -0700527void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800529 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700530 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700531 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800532 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
533 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700534 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700535 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700536 return true;
537 }
538 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700539 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540}
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700544 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000545 const char* name) :
546 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700548 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
550 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 mDispSync(dispSync),
552 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700553 mVsyncMutex(),
554 mPhaseOffset(phaseOffset),
555 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700556
Lloyd Piquee83f9312018-02-01 12:53:17 -0800557 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000562 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 static_cast<DispSync::Callback*>(this));
564 if (err != NO_ERROR) {
565 ALOGE("error registering vsync callback: %s (%d)",
566 strerror(-err), err);
567 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700568 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 } else {
570 status_t err = mDispSync->removeEventListener(
571 static_cast<DispSync::Callback*>(this));
572 if (err != NO_ERROR) {
573 ALOGE("error unregistering vsync callback: %s (%d)",
574 strerror(-err), err);
575 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 }
580
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700582 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 mCallback = callback;
584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700587 Mutex::Autolock lock(mVsyncMutex);
588
589 // Normalize phaseOffset to [0, period)
590 auto period = mDispSync->getPeriod();
591 phaseOffset %= period;
592 if (phaseOffset < 0) {
593 // If we're here, then phaseOffset is in (-period, 0). After this
594 // operation, it will be in (0, period)
595 phaseOffset += period;
596 }
597 mPhaseOffset = phaseOffset;
598
599 // If we're not enabled, we don't need to mess with the listeners
600 if (!mEnabled) {
601 return;
602 }
603
Dan Stoza2713c302018-03-28 17:07:36 -0700604 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
605 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700607 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 strerror(-err), err);
609 }
610 }
611
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612private:
613 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700616 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 callback = mCallback;
618
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700619 if (mTraceVsync) {
620 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700621 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700622 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 }
624
Peiyong Lin566a3b42018-01-09 18:22:43 -0800625 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 callback->onVSyncEvent(when);
627 }
628 }
629
Tim Murray4a4e4a22016-04-19 16:29:23 +0000630 const char* const mName;
631
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632 int mValue;
633
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700634 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700635 const String8 mVsyncOnLabel;
636 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700637
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700639
640 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800641 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700642
643 Mutex mVsyncMutex; // Protects the following
644 nsecs_t mPhaseOffset;
645 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700646};
647
Lloyd Piquee83f9312018-02-01 12:53:17 -0800648class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700649public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800650 InjectVSyncSource() = default;
651 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700652
Lloyd Piquee83f9312018-02-01 12:53:17 -0800653 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654 std::lock_guard<std::mutex> lock(mCallbackMutex);
655 mCallback = callback;
656 }
657
Lloyd Piquee83f9312018-02-01 12:53:17 -0800658 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700659 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700660 if (mCallback) {
661 mCallback->onVSyncEvent(when);
662 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700663 }
664
Lloyd Piquee83f9312018-02-01 12:53:17 -0800665 void setVSyncEnabled(bool) override {}
666 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700667
668private:
669 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800670 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671};
672
Wei Wangf9b05ee2017-07-19 20:59:39 -0700673// Do not call property_set on main thread which will be blocked by init
674// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700675void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700676 ALOGI( "SurfaceFlinger's main thread ready to run. "
677 "Initializing graphics H/W...");
678
Thierry Strudel2924d012017-08-14 15:19:37 -0700679 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900680
Steven Thomasb02664d2017-07-26 18:48:28 -0700681 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682
Steven Thomasb02664d2017-07-26 18:48:28 -0700683 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800684 mEventThreadSource =
685 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
686 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800687 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
688 [this]() { resyncWithRateLimit(); },
689 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800690 "appEventThread");
691 mSfEventThreadSource =
692 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
693 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800694
Lloyd Pique24b0a482018-03-09 18:52:26 -0800695 mSFEventThread =
696 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
697 [this]() { resyncWithRateLimit(); },
698 [this](nsecs_t timestamp) {
699 mInterceptor->saveVSyncEvent(timestamp);
700 },
701 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800702 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200703 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704
Steven Thomasb02664d2017-07-26 18:48:28 -0700705 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800706 getBE().mRenderEngine =
707 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
708 hasWideColorDisplay
709 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
710 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800711 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700712
713 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
714 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800715 getBE().mHwc.reset(
716 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700717 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800718 // Process any initial hotplug and resulting display changes.
719 processDisplayHotplugEventsLocked();
720 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
721 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800722
Lloyd Piquefcd86612017-12-14 17:15:36 -0800723 // make the default display GLContext current so that we can create textures
724 // when creating Layers (which may happens before we render something)
725 getDefaultDisplayDeviceLocked()->makeCurrent();
726
Steven Thomas050b2c82017-03-06 11:45:16 -0800727 if (useVrFlinger) {
728 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700729 // This callback is called from the vr flinger dispatch thread. We
730 // need to call signalTransaction(), which requires holding
731 // mStateLock when we're not on the main thread. Acquiring
732 // mStateLock from the vr flinger dispatch thread might trigger a
733 // deadlock in surface flinger (see b/66916578), so post a message
734 // to be handled on the main thread instead.
735 sp<LambdaMessage> message = new LambdaMessage([=]() {
736 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
737 mVrFlingerRequestsDisplay = requestDisplay;
738 signalTransaction();
739 });
740 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800741 };
David Sodman105b7dc2017-11-04 20:28:14 -0700742 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
743 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800744 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800745 if (!mVrFlinger) {
746 ALOGE("Failed to start vrflinger");
747 }
748 }
749
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800750 mEventControlThread = std::make_unique<impl::EventControlThread>(
751 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700752
Mathias Agopian92a979a2012-08-02 18:32:23 -0700753 // initialize our drawing state
754 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700755
Andy McFadden13a082e2012-08-24 10:16:42 -0700756 // set initial conditions (e.g. unblank default device)
757 initializeDisplays();
758
David Sodmanbc815282017-11-05 18:57:52 -0800759 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700760
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 // Inform native graphics APIs whether the present timestamp is supported:
762 if (getHwComposer().hasCapability(
763 HWC2::Capability::PresentFenceIsNotReliable)) {
764 mStartPropertySetThread = new StartPropertySetThread(false);
765 } else {
766 mStartPropertySetThread = new StartPropertySetThread(true);
767 }
768
769 if (mStartPropertySetThread->Start() != NO_ERROR) {
770 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772
Chia-I Wu6d844112018-06-27 07:17:41 +0800773 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
774 // is used to saturate legacy sRGB content. However, to make sure the same color under
775 // Display P3 will be saturated to the same color, we intentionally break the API spec
776 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
777 // such saturation matrix on Display P3 is understood fully, the API should always return
778 // identify matrix.
779 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800780 Dataspace::SRGB_LINEAR);
781
Chia-I Wu6d844112018-06-27 07:17:41 +0800782 // we will apply this on Display P3.
783 if (mEnhancedSaturationMatrix != mat4()) {
784 ColorSpace srgb(ColorSpace::sRGB());
785 ColorSpace displayP3(ColorSpace::DisplayP3());
786 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
787 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
788 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
789 }
790
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700792}
793
Romain Guy11d63f42017-07-20 12:47:14 -0700794void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 Mutex::Autolock _l(mStateLock);
796
Romain Guy11d63f42017-07-20 12:47:14 -0700797 char value[PROPERTY_VALUE_MAX];
798
799 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800800 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700801 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800802 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100803
804 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700805 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700806}
807
Mathias Agopiana67e4182012-06-19 17:26:12 -0700808void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800809 // Start boot animation service by setting a property mailbox
810 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700811 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800812 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700813 if (mStartPropertySetThread->join() != NO_ERROR) {
814 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800815 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700816}
817
Mathias Agopian875d8e12013-06-07 15:35:48 -0700818size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800819 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700820}
821
Mathias Agopian875d8e12013-06-07 15:35:48 -0700822size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800823 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700824}
825
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800827
Jamie Gennis582270d2011-08-17 18:19:00 -0700828bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800830 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800831 return authenticateSurfaceTextureLocked(bufferProducer);
832}
833
834bool SurfaceFlinger::authenticateSurfaceTextureLocked(
835 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800836 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800837 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800838}
839
Brian Anderson6b376712017-04-04 10:51:39 -0700840status_t SurfaceFlinger::getSupportedFrameTimestamps(
841 std::vector<FrameEvent>* outSupported) const {
842 *outSupported = {
843 FrameEvent::REQUESTED_PRESENT,
844 FrameEvent::ACQUIRE,
845 FrameEvent::LATCH,
846 FrameEvent::FIRST_REFRESH_START,
847 FrameEvent::LAST_REFRESH_START,
848 FrameEvent::GPU_COMPOSITION_DONE,
849 FrameEvent::DEQUEUE_READY,
850 FrameEvent::RELEASE,
851 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700852 ConditionalLock _l(mStateLock,
853 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700854 if (!getHwComposer().hasCapability(
855 HWC2::Capability::PresentFenceIsNotReliable)) {
856 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
857 }
858 return NO_ERROR;
859}
860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
862 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800863 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return BAD_VALUE;
865 }
866
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500867 if (!display.get())
868 return NAME_NOT_FOUND;
869
Jesse Hall692c7232012-11-08 15:41:56 -0800870 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700871 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800872 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700873 type = i;
874 break;
875 }
876 }
877
878 if (type < 0) {
879 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700880 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700881
Mathias Agopian8b736f12012-08-13 17:54:26 -0700882 // TODO: Not sure if display density should handled by SF any longer
883 class Density {
884 static int getDensityFromProperty(char const* propName) {
885 char property[PROPERTY_VALUE_MAX];
886 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800887 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700888 density = atoi(property);
889 }
890 return density;
891 }
892 public:
893 static int getEmuDensity() {
894 return getDensityFromProperty("qemu.sf.lcd_density"); }
895 static int getBuildDensity() {
896 return getDensityFromProperty("ro.sf.lcd_density"); }
897 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700900
Steven Thomas6d8110b2017-08-31 18:24:21 -0700901 ConditionalLock _l(mStateLock,
902 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 DisplayInfo info = DisplayInfo();
905
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 float xdpi = hwConfig->getDpiX();
907 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 if (type == DisplayDevice::DISPLAY_PRIMARY) {
910 // The density of the device is provided by a build property
911 float density = Density::getBuildDensity() / 160.0f;
912 if (density == 0) {
913 // the build doesn't provide a density -- this is wrong!
914 // use xdpi instead
915 ALOGE("ro.sf.lcd_density must be defined as a build property");
916 density = xdpi / 160.0f;
917 }
918 if (Density::getEmuDensity()) {
919 // if "qemu.sf.lcd_density" is specified, it overrides everything
920 xdpi = ydpi = density = Density::getEmuDensity();
921 density /= 160.0f;
922 }
923 info.density = density;
924
925 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800927 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 } else {
929 // TODO: where should this value come from?
930 static const int TV_DENSITY = 213;
931 info.density = TV_DENSITY / 160.0f;
932 info.orientation = 0;
933 }
934
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 info.w = hwConfig->getWidth();
936 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700937 info.xdpi = xdpi;
938 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900940 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800941
Andy McFadden91b2ca82014-06-13 14:04:23 -0700942 // This is how far in advance a buffer must be queued for
943 // presentation at a given time. If you want a buffer to appear
944 // on the screen at time N, you must submit the buffer before
945 // (N - presentationDeadline).
946 //
947 // Normally it's one full refresh period (to give SF a chance to
948 // latch the buffer), but this can be reduced by configuring a
949 // DispSync offset. Any additional delays introduced by the hardware
950 // composer or panel must be accounted for here.
951 //
952 // We add an additional 1ms to allow for processing time and
953 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800955 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700956
957 // All non-virtual displays are currently considered secure.
958 info.secure = true;
959
Iris Chang7501ed62018-04-30 14:45:42 +0800960 if (type == DisplayDevice::DISPLAY_PRIMARY &&
961 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
962 std::swap(info.w, info.h);
963 }
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700966 }
967
Dan Stoza7f7da322014-05-02 15:26:25 -0700968 return NO_ERROR;
969}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700970
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800971status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700972 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800973 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700974 return BAD_VALUE;
975 }
976
977 // FIXME for now we always return stats for the primary display
978 memset(stats, 0, sizeof(*stats));
979 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
980 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
981 return NO_ERROR;
982}
983
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800985 if (display == nullptr) {
986 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800987 return BAD_VALUE;
988 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700989
990 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800991 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700992 return device->getActiveConfig();
993 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700994
Dan Stoza24a42e92015-03-09 10:04:11 -0700995 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700996}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700997
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700998void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
999 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
1000 this);
1001 int32_t type = hw->getDisplayType();
1002 int currentMode = hw->getActiveConfig();
1003
1004 if (mode == currentMode) {
1005 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
1006 return;
1007 }
1008
1009 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1010 ALOGW("Trying to set config for virtual display");
1011 return;
1012 }
1013
1014 hw->setActiveConfig(mode);
1015 getHwComposer().setActiveConfig(type, mode);
1016}
1017
1018status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
1019 class MessageSetActiveConfig: public MessageBase {
1020 SurfaceFlinger& mFlinger;
1021 sp<IBinder> mDisplay;
1022 int mMode;
1023 public:
1024 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1025 int mode) :
1026 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1027 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001028 Vector<DisplayInfo> configs;
1029 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001030 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001031 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001032 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001033 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001034 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001035 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001036 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001037 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001038 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001039 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1040 ALOGW("Attempt to set active config = %d for virtual display",
1041 mMode);
1042 } else {
1043 mFlinger.setActiveConfigInternal(hw, mMode);
1044 }
1045 return true;
1046 }
1047 };
1048 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1049 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001050 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001051}
Michael Wright28f24d02016-07-12 13:30:53 -07001052status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001054 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1055 return BAD_VALUE;
1056 }
1057
1058 if (!display.get()) {
1059 return NAME_NOT_FOUND;
1060 }
1061
1062 int32_t type = NAME_NOT_FOUND;
1063 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1064 if (display == mBuiltinDisplays[i]) {
1065 type = i;
1066 break;
1067 }
1068 }
1069
1070 if (type < 0) {
1071 return type;
1072 }
1073
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 {
1076 ConditionalLock _l(mStateLock,
1077 std::this_thread::get_id() != mMainThreadId);
1078 modes = getHwComposer().getColorModes(type);
1079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
1081 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1082
1083 return NO_ERROR;
1084}
1085
Peiyong Lina52f0292018-03-14 17:26:31 -07001086ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001087 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001088 if (device != nullptr) {
1089 return device->getActiveColorMode();
1090 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001091 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001092}
1093
1094void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001095 ColorMode mode, Dataspace dataSpace,
1096 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001097 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001098 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001099 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001100 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001101
Peiyong Lin38e9a562018-04-10 16:24:20 -07001102 if (mode == currentMode && dataSpace == currentDataSpace &&
1103 renderIntent == currentRenderIntent) {
1104 return;
1105 }
1106
1107 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1108 ALOGW("Trying to set config for virtual display");
1109 return;
1110 }
1111
1112 hw->setActiveColorMode(mode);
1113 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001114 hw->setActiveRenderIntent(renderIntent);
1115 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1116
1117 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1118 decodeColorMode(mode).c_str(), mode,
1119 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1120 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001121}
1122
1123
1124status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001125 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001126 class MessageSetActiveColorMode: public MessageBase {
1127 SurfaceFlinger& mFlinger;
1128 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001129 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001130 public:
1131 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001133 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1134 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001135 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001136 mFlinger.getDisplayColorModes(mDisplay, &modes);
1137 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001138 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001139 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1140 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001141 return true;
1142 }
1143 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1144 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001145 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1146 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001147 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001148 ALOGW("Attempt to set active color mode %s %d for virtual display",
1149 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001150 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001151 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1152 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001153 }
1154 return true;
1155 }
1156 };
1157 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1158 postMessageSync(msg);
1159 return NO_ERROR;
1160}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001161
Svetoslavd85084b2014-03-20 10:28:31 -07001162status_t SurfaceFlinger::clearAnimationFrameStats() {
1163 Mutex::Autolock _l(mStateLock);
1164 mAnimFrameTracker.clearStats();
1165 return NO_ERROR;
1166}
1167
1168status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1169 Mutex::Autolock _l(mStateLock);
1170 mAnimFrameTracker.getStats(outStats);
1171 return NO_ERROR;
1172}
1173
Dan Stozac4f471e2016-03-24 09:31:08 -07001174status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1175 HdrCapabilities* outCapabilities) const {
1176 Mutex::Autolock _l(mStateLock);
1177
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001178 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001179 if (displayDevice == nullptr) {
1180 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1181 return BAD_VALUE;
1182 }
1183
Peiyong Linfb069302018-04-25 14:34:31 -07001184 // At this point the DisplayDeivce should already be set up,
1185 // meaning the luminance information is already queried from
1186 // hardware composer and stored properly.
1187 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1188 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1189 capabilities.getDesiredMaxLuminance(),
1190 capabilities.getDesiredMaxAverageLuminance(),
1191 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001192
1193 return NO_ERROR;
1194}
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1198 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 if (mInjectVSyncs == enable) {
1201 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203
1204 if (enable) {
1205 ALOGV("VSync Injections enabled");
1206 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001207 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001208 mInjectorEventThread = std::make_unique<
1209 impl::EventThread>(mVSyncInjector.get(),
1210 [this]() { resyncWithRateLimit(); },
1211 impl::EventThread::InterceptVSyncsCallback(),
1212 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001213 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001214 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215 } else {
1216 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001217 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218 }
1219
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001220 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 });
1222 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001223 return NO_ERROR;
1224}
1225
1226status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001227 Mutex::Autolock _l(mStateLock);
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229 if (!mInjectVSyncs) {
1230 ALOGE("VSync Injections not enabled");
1231 return BAD_VALUE;
1232 }
1233 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1234 ALOGV("Injecting VSync inside SurfaceFlinger");
1235 mVSyncInjector->onInjectSyncEvent(when);
1236 }
1237 return NO_ERROR;
1238}
1239
Lloyd Pique755e3192018-01-31 16:46:15 -08001240status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1241 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001242 IPCThreadState* ipc = IPCThreadState::self();
1243 const int pid = ipc->getCallingPid();
1244 const int uid = ipc->getCallingUid();
1245 if ((uid != AID_SHELL) &&
1246 !PermissionCache::checkPermission(sDump, pid, uid)) {
1247 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1248 return PERMISSION_DENIED;
1249 }
1250
1251 // Try to acquire a lock for 1s, fail gracefully
1252 const status_t err = mStateLock.timedLock(s2ns(1));
1253 const bool locked = (err == NO_ERROR);
1254 if (!locked) {
1255 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1256 return TIMED_OUT;
1257 }
1258
1259 outLayers->clear();
1260 mCurrentState.traverseInZOrder([&](Layer* layer) {
1261 outLayers->push_back(layer->getLayerDebugInfo());
1262 });
1263
1264 mStateLock.unlock();
1265 return NO_ERROR;
1266}
1267
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001268// ----------------------------------------------------------------------------
1269
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001270sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1271 ISurfaceComposer::VsyncSource vsyncSource) {
1272 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1273 return mSFEventThread->createEventConnection();
1274 } else {
1275 return mEventThread->createEventConnection();
1276 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001277}
1278
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001279// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001280
1281void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001282 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001286 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287}
1288
1289void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001290 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001291}
1292
1293void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001294 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001295 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001296}
1297
1298status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001299 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001300 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301}
1302
1303status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001304 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001305 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001306 if (res == NO_ERROR) {
1307 msg->wait();
1308 }
1309 return res;
1310}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001311
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001312void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001313 do {
1314 waitForEvent();
1315 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001316}
1317
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318void SurfaceFlinger::enableHardwareVsync() {
1319 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001320 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001322 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1323 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001325 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326}
1327
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 Mutex::Autolock _l(mHWVsyncLock);
1330
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331 if (makeAvailable) {
1332 mHWVsyncAvailable = true;
1333 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001334 // Hardware vsync is not currently available, so abort the resync
1335 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001336 return;
1337 }
1338
David Sodman105b7dc2017-11-04 20:28:14 -07001339 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001340 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341
1342 mPrimaryDispSync.reset();
1343 mPrimaryDispSync.setPeriod(period);
1344
1345 if (!mPrimaryHWVsyncEnabled) {
1346 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001347 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1348 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349 mPrimaryHWVsyncEnabled = true;
1350 }
1351}
1352
Jesse Hall948fe0c2013-10-14 12:56:09 -07001353void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354 Mutex::Autolock _l(mHWVsyncLock);
1355 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001356 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1357 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358 mPrimaryDispSync.endResync();
1359 mPrimaryHWVsyncEnabled = false;
1360 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001361 if (makeUnavailable) {
1362 mHWVsyncAvailable = false;
1363 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001364}
1365
Tim Murray4a4e4a22016-04-19 16:29:23 +00001366void SurfaceFlinger::resyncWithRateLimit() {
1367 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001368
1369 // No explicit locking is needed here since EventThread holds a lock while calling this method
1370 static nsecs_t sLastResyncAttempted = 0;
1371 const nsecs_t now = systemTime();
1372 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001373 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001374 }
Dan Stoza57164302017-05-08 14:03:54 -07001375 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001376}
1377
Steven Thomasb02664d2017-07-26 18:48:28 -07001378void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1379 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001382 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 return;
1384 }
1385
1386 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001387 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 return;
1389 }
1390
Jamie Gennisd1700752013-10-14 12:22:52 -07001391 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392
Jamie Gennisd1700752013-10-14 12:22:52 -07001393 { // Scope for the lock
1394 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001396 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001397 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001398 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001399
1400 if (needsHwVsync) {
1401 enableHardwareVsync();
1402 } else {
1403 disableHardwareVsync(false);
1404 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001405}
1406
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001408 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1409 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410}
1411
Lloyd Pique715a2c12017-12-14 17:18:08 -08001412void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1413 HWC2::Connection connection) {
1414 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1415 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416
Lloyd Piqueba04e622017-12-14 17:11:26 -08001417 // Ignore events that do not have the right sequenceId.
1418 if (sequenceId != getBE().mComposerSequenceId) {
1419 return;
1420 }
1421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 // Only lock if we're not on the main thread. This function is normally
1423 // called on a hwbinder thread, but for the primary display it's called on
1424 // the main thread with the state lock already held, so don't attempt to
1425 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001426 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001427
Lloyd Pique715a2c12017-12-14 17:18:08 -08001428 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001429
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001430 if (std::this_thread::get_id() == mMainThreadId) {
1431 // Process all pending hot plug events immediately if we are on the main thread.
1432 processDisplayHotplugEventsLocked();
1433 }
1434
Lloyd Piqueba04e622017-12-14 17:11:26 -08001435 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001436}
1437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438void SurfaceFlinger::onRefreshReceived(int sequenceId,
1439 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001440 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001441 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001443 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001444 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001445}
1446
Dan Stoza9e56aa02015-11-02 13:00:03 -08001447void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001448 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 getHwComposer().setVsyncEnabled(disp,
1451 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001452}
1453
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001455void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001456 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 // Clear the drawing state so that the logic inside of
1458 // handleTransactionLocked will fire. It will determine the delta between
1459 // mCurrentState and mDrawingState and re-apply all changes when we make the
1460 // transition.
1461 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001462 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463 mDisplays.clear();
1464}
1465
Steven Thomas050b2c82017-03-06 11:45:16 -08001466void SurfaceFlinger::updateVrFlinger() {
1467 if (!mVrFlinger)
1468 return;
1469 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001470 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001471 return;
1472 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001473
David Sodman105b7dc2017-11-04 20:28:14 -07001474 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 ALOGE("Vr flinger is only supported for remote hardware composer"
1476 " service connections. Ignoring request to transition to vr"
1477 " flinger.");
1478 mVrFlingerRequestsDisplay = false;
1479 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001480 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001481
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001483
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 int currentDisplayPowerMode = getDisplayDeviceLocked(
1485 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001486
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001488 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001492 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001493 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1494 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001495 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001496
David Sodman105b7dc2017-11-04 20:28:14 -07001497 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1498 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001499
1500 if (vrFlingerRequestsDisplay) {
1501 mVrFlinger->GrantDisplayOwnership();
1502 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505
1506 mVisibleRegionsDirty = true;
1507 invalidateHwcGeometry();
1508
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001509 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1511 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1512 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001513
Steven Thomasb02664d2017-07-26 18:48:28 -07001514 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001515 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 const nsecs_t period = activeConfig->getVsyncPeriod();
1517 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001518
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 // Use phase of 0 since phase is not known.
1520 // Use latency of 0, which will snap to the ideal latency.
1521 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001522
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523 android_atomic_or(1, &mRepaintEverything);
1524 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001525}
1526
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001528 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001530 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001531 bool frameMissed = !mHadClientComposition &&
1532 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 (mPreviousPresentFence->getSignalTime() ==
1534 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001535 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001536 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001537 mTimeStats.incrementMissedFrames();
1538 if (mPropagateBackpressure) {
1539 signalLayerUpdate();
1540 break;
1541 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001542 }
Dan Stoza50182882016-07-08 12:02:20 -07001543
Steven Thomas050b2c82017-03-06 11:45:16 -08001544 // Now that we're going to make it to the handleMessageTransaction()
1545 // call below it's safe to call updateVrFlinger(), which will
1546 // potentially trigger a display handoff.
1547 updateVrFlinger();
1548
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 bool refreshNeeded = handleMessageTransaction();
1550 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001551 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001552 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001553 // Signal a refresh if a transaction modified the window state,
1554 // a new buffer was latched, or if HWC has requested a full
1555 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 signalRefresh();
1557 }
1558 break;
1559 }
1560 case MessageQueue::REFRESH: {
1561 handleMessageRefresh();
1562 break;
1563 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001564 }
1565}
1566
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001568 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001570 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001572 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001573 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574}
1575
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001578 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579}
1580
1581void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001583
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001584 mRefreshPending = false;
1585
Pablo Ceballos40845df2016-01-25 17:41:15 -08001586 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001587
Brian Andersond6927fb2016-07-23 23:37:30 -07001588 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001589 rebuildLayerStacks();
1590 setUpHWComposer();
1591 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001592 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001593 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001594 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001595 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001596
David Sodman105b7dc2017-11-04 20:28:14 -07001597 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001598
1599 mHadClientComposition = false;
1600 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1601 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1602 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001603 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001604 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001605 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001606
Dan Stoza9e56aa02015-11-02 13:00:03 -08001607 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001609
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610void SurfaceFlinger::doDebugFlashRegions()
1611{
1612 // is debugging enabled
1613 if (CC_LIKELY(!mDebugRegion))
1614 return;
1615
1616 const bool repaintEverything = mRepaintEverything;
1617 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1618 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001619 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620 // transform the dirty region into this screen's coordinate space
1621 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1622 if (!dirtyRegion.isEmpty()) {
1623 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001624 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625
1626 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001628 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001629 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1630
Mathias Agopianda27af92012-09-13 18:17:13 -07001631 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632 }
1633 }
1634 }
1635
1636 postFramebuffer();
1637
1638 if (mDebugRegion > 1) {
1639 usleep(mDebugRegion * 1000);
1640 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001641
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001643 auto& displayDevice = mDisplays[displayId];
1644 if (!displayDevice->isDisplayOn()) {
1645 continue;
1646 }
1647
David Sodman105b7dc2017-11-04 20:28:14 -07001648 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1649 ALOGE_IF(result != NO_ERROR,
1650 "prepareFrame for display %zd failed:"
1651 " %d (%s)",
1652 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001653 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001654}
1655
Adrian Roos1e1a1282017-11-01 19:05:31 +01001656void SurfaceFlinger::doTracing(const char* where) {
1657 ATRACE_CALL();
1658 ATRACE_NAME(where);
1659 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001660 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001661 }
1662}
1663
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001664void SurfaceFlinger::logLayerStats() {
1665 ATRACE_CALL();
1666 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1667 int32_t hwcId = -1;
1668 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1669 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1670 if (displayDevice->isPrimary()) {
1671 hwcId = displayDevice->getHwcDisplayId();
1672 break;
1673 }
1674 }
1675 if (hwcId < 0) {
1676 ALOGE("LayerStats: Hmmm, no primary display?");
1677 return;
1678 }
1679 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1680 }
1681}
1682
Brian Andersond6927fb2016-07-23 23:37:30 -07001683void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001685 ATRACE_CALL();
1686 ALOGV("preComposition");
1687
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001689 mDrawingState.traverseInZOrder([&](Layer* layer) {
1690 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691 needExtraInvalidate = true;
1692 }
Robert Carr2047fae2016-11-28 14:09:09 -08001693 });
1694
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695 if (needExtraInvalidate) {
1696 signalLayerUpdate();
1697 }
1698}
1699
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700void SurfaceFlinger::updateCompositorTiming(
1701 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1702 std::shared_ptr<FenceTime>& presentFenceTime) {
1703 // Update queue of past composite+present times and determine the
1704 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001705 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001707 while (!getBE().mCompositePresentTimes.empty()) {
1708 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 // Cached values should have been updated before calling this method,
1710 // which helps avoid duplicate syscalls.
1711 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1712 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1713 break;
1714 }
1715 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001716 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717 }
1718
1719 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001720 while (getBE().mCompositePresentTimes.size() > 16) {
1721 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722 }
1723
Brian Andersond0010582017-03-07 13:20:31 -08001724 setCompositorTimingSnapped(
1725 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1726}
1727
1728void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1729 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001730 // Integer division and modulo round toward 0 not -inf, so we need to
1731 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001732 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1734 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1735
Brian Andersond0010582017-03-07 13:20:31 -08001736 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1737 if (idealLatency <= 0) {
1738 idealLatency = vsyncInterval;
1739 }
1740
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741 // Snap the latency to a value that removes scheduling jitter from the
1742 // composition and present times, which often have >1ms of jitter.
1743 // Reducing jitter is important if an app attempts to extrapolate
1744 // something (such as user input) to an accurate diasplay time.
1745 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1746 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001747 nsecs_t bias = vsyncInterval / 2;
1748 int64_t extraVsyncs =
1749 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1750 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1751 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001752
David Sodman99974d22017-11-28 12:04:33 -08001753 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1754 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1755 getBE().mCompositorTiming.interval = vsyncInterval;
1756 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001757}
1758
1759void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 ATRACE_CALL();
1762 ALOGV("postComposition");
1763
Brian Anderson3546a3f2016-07-14 11:51:14 -07001764 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001765 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001766 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001767 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001768 }
1769
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001770 // |mStateLock| not needed as we are on the main thread
1771 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772
David Sodman73beded2017-11-15 11:56:06 -08001773 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001775 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776 glCompositionDoneFenceTime =
1777 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001778 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001779 } else {
1780 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1781 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001782
David Sodman73beded2017-11-15 11:56:06 -08001783 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001784 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001785 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001786 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001787
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1789 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1790
1791 // We use the refreshStartTime which might be sampled a little later than
1792 // when we started doing work for this frame, but that should be okay
1793 // since updateCompositorTiming has snapping logic.
1794 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001795 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001796 CompositorTiming compositorTiming;
1797 {
David Sodman99974d22017-11-28 12:04:33 -08001798 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1799 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001800 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801
Robert Carr2047fae2016-11-28 14:09:09 -08001802 mDrawingState.traverseInZOrder([&](Layer* layer) {
1803 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001804 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001805 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001806 recordBufferingStats(layer->getName().string(),
1807 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001808 }
Robert Carr2047fae2016-11-28 14:09:09 -08001809 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001810
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001811 if (presentFenceTime->isValid()) {
1812 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001813 enableHardwareVsync();
1814 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001815 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001816 }
1817 }
1818
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001819 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001820 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001821 enableHardwareVsync();
1822 }
1823 }
1824
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001825 if (mAnimCompositionPending) {
1826 mAnimCompositionPending = false;
1827
Brian Anderson4e606e32017-03-16 15:34:57 -07001828 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001830 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001831 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001832 // The HWC doesn't support present fences, so use the refresh
1833 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001835 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001836 mAnimFrameTracker.setActualPresentTime(presentTime);
1837 }
1838 mAnimFrameTracker.advanceFrame();
1839 }
Dan Stozab90cf072015-03-05 11:05:59 -08001840
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001841 mTimeStats.incrementTotalFrames();
1842 if (mHadClientComposition) {
1843 mTimeStats.incrementClientCompositionFrames();
1844 }
1845
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001846 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1847 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001848 return;
1849 }
1850
1851 nsecs_t currentTime = systemTime();
1852 if (mHasPoweredOff) {
1853 mHasPoweredOff = false;
1854 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001855 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001856 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001857 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1858 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001859 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001860 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001861 }
David Sodman4a36e932017-11-07 14:29:47 -08001862 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001863 }
David Sodman4a36e932017-11-07 14:29:47 -08001864 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001865
1866 {
1867 std::lock_guard lock(mTexturePoolMutex);
1868 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1869 if (refillCount > 0) {
1870 const size_t offset = mTexturePool.size();
1871 mTexturePool.resize(mTexturePoolSize);
1872 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1873 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1874 }
1875 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876}
1877
1878void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 ATRACE_CALL();
1880 ALOGV("rebuildLayerStacks");
1881
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001883 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001884 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 mVisibleRegionsDirty = false;
1886 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001887
Jeff Sharkey76488112017-02-27 14:15:18 -07001888 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1889 Region opaqueRegion;
1890 Region dirtyRegion;
1891 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001892 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001893 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1894 const Transform& tr(displayDevice->getTransform());
1895 const Rect bounds(displayDevice->getBounds());
1896 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001897 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001898
Jeff Sharkey76488112017-02-27 14:15:18 -07001899 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001900 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001901 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1902 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001903 Region drawRegion(tr.transform(
1904 layer->visibleNonTransparentRegion));
1905 drawRegion.andSelf(bounds);
1906 if (!drawRegion.isEmpty()) {
1907 layersSortedByZ.add(layer);
1908 } else {
1909 // Clear out the HWC layer if this layer was
1910 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001911 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001912 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001913 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001914 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001915 // WM changes displayDevice->layerStack upon sleep/awake.
1916 // Here we make sure we delete the HWC layers even if
1917 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001918 hwcLayerDestroyed = layer->destroyHwcLayer(
1919 displayDevice->getHwcDisplayId());
1920 }
1921
1922 // If a layer is not going to get a release fence because
1923 // it is invisible, but it is also going to release its
1924 // old buffer, add it to the list of layers needing
1925 // fences.
1926 if (hwcLayerDestroyed) {
1927 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1928 mLayersWithQueuedFrames.cend(), layer);
1929 if (found != mLayersWithQueuedFrames.cend()) {
1930 layersNeedingFences.add(layer);
1931 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001932 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001933 });
1934 }
1935 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001936 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001937 displayDevice->undefinedRegion.set(bounds);
1938 displayDevice->undefinedRegion.subtractSelf(
1939 tr.transform(opaqueRegion));
1940 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001941 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001942 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001943}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001944
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001945// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001946// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001947// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001948// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001949// The returned HDR data space is one of
1950// - Dataspace::UNKNOWN
1951// - Dataspace::BT2020_HLG
1952// - Dataspace::BT2020_PQ
1953Dataspace SurfaceFlinger::getBestDataspace(
1954 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1955 Dataspace bestDataSpace = Dataspace::SRGB;
1956 *outHdrDataSpace = Dataspace::UNKNOWN;
1957
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001958 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001959 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 case Dataspace::V0_SCRGB:
1961 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001962 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001963 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001964 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001965 case Dataspace::BT2020_PQ:
1966 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001967 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001969 case Dataspace::BT2020_HLG:
1970 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001971 // When there's mixed PQ content and HLG content, we set the HDR
1972 // data space to be BT2020_PQ and convert HLG to PQ.
1973 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1974 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001975 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 break;
1977 default:
1978 break;
1979 }
Romain Guy54f154a2017-10-24 21:40:32 +01001980 }
1981
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001982 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001983}
1984
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001985// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001986void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001987 ColorMode* outMode, Dataspace* outDataSpace,
1988 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001989 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1990 *outMode = ColorMode::NATIVE;
1991 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001992 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001993 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001994 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001995
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001996 Dataspace hdrDataSpace;
1997 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1998
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001999 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002000 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002001 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002002 if (isHdr) {
2003 bestDataSpace = hdrDataSpace;
2004 }
2005
Chia-I Wu0d711262018-05-21 15:19:35 -07002006 RenderIntent intent;
2007 switch (mDisplayColorSetting) {
2008 case DisplayColorSetting::MANAGED:
2009 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002010 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002011 break;
2012 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002013 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002014 break;
2015 default: // vendor display color setting
2016 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2017 break;
2018 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002019
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002020 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002021}
2022
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 ATRACE_CALL();
2025 ALOGV("setUpHWComposer");
2026
Jesse Hall028dc8f2013-08-20 16:35:32 -07002027 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002028 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002029 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2030 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2031
2032 // If nothing has changed (!dirty), don't recompose.
2033 // If something changed, but we don't currently have any visible layers,
2034 // and didn't when we last did a composition, then skip it this time.
2035 // The second rule does two things:
2036 // - When all layers are removed from a display, we'll emit one black
2037 // frame, then nothing more until we get new layers.
2038 // - When a display is created with a private layer stack, we won't
2039 // emit any black frames until a layer is added to the layer stack.
2040 bool mustRecompose = dirty && !(empty && wasEmpty);
2041
2042 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2043 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2044 mustRecompose ? "doing" : "skipping",
2045 dirty ? "+" : "-",
2046 empty ? "+" : "-",
2047 wasEmpty ? "+" : "-");
2048
Dan Stoza71433162014-02-04 16:22:36 -08002049 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002050
2051 if (mustRecompose) {
2052 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2053 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002054 }
2055
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 // build the h/w work list
2057 if (CC_UNLIKELY(mGeometryInvalid)) {
2058 mGeometryInvalid = false;
2059 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2060 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2061 const auto hwcId = displayDevice->getHwcDisplayId();
2062 if (hwcId >= 0) {
2063 const Vector<sp<Layer>>& currentLayers(
2064 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002065 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002066 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002068 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002071 }
2072 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002073
Robert Carrae060832016-11-28 10:51:00 -08002074 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002075 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002077 }
2078 }
2079 }
2080 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 }
Riley Andrews03414a12014-07-01 14:22:59 -07002082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 // Set the per-frame data
2084 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2085 auto& displayDevice = mDisplays[displayId];
2086 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002087
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 if (hwcId < 0) {
2089 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002090 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002091 if (mDrawingState.colorMatrixChanged) {
2092 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2093 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002094 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2095 "display %zd: %d", displayId, result);
2096 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002098 if (layer->isHdrY410()) {
2099 layer->forceClientComposition(hwcId);
2100 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2101 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002102 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002103 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002104 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2105 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002106 !displayDevice->hasHLGSupport()) {
2107 layer->forceClientComposition(hwcId);
2108 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002109
chaviwc9232ed2017-11-14 15:31:15 -08002110 if (layer->getForceClientComposition(hwcId)) {
2111 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2112 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2113 continue;
2114 }
2115
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 layer->setPerFrameData(displayDevice);
2117 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002118
2119 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002120 ColorMode colorMode;
2121 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002122 RenderIntent renderIntent;
2123 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2124 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002125 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 }
2127
Chia-I Wu28f320b2018-05-03 11:02:56 -07002128 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002129
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002131 auto& displayDevice = mDisplays[displayId];
2132 if (!displayDevice->isDisplayOn()) {
2133 continue;
2134 }
2135
David Sodman105b7dc2017-11-04 20:28:14 -07002136 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2138 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002139 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002140}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002141
Mathias Agopiancd60f992012-08-16 16:28:27 -07002142void SurfaceFlinger::doComposition() {
2143 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002144 ALOGV("doComposition");
2145
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002146 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002147 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002148 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002149 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150 // transform the dirty region into this screen's coordinate space
2151 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002152
2153 // repaint the framebuffer (if needed)
2154 doDisplayComposition(hw, dirtyRegion);
2155
Mathias Agopiancd60f992012-08-16 16:28:27 -07002156 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002157 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002158 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002159 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002160 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002161}
2162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163void SurfaceFlinger::postFramebuffer()
2164{
Mathias Agopian841cde52012-03-01 15:44:37 -08002165 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002167
Mathias Agopiana44b0412011-10-16 18:46:35 -07002168 const nsecs_t now = systemTime();
2169 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002170
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2172 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002173 if (!displayDevice->isDisplayOn()) {
2174 continue;
2175 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 const auto hwcId = displayDevice->getHwcDisplayId();
2177 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002178 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002179 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002180 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002181 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu99b46192018-06-21 15:52:50 +08002183 sp<Fence> releaseFence = Fence::NO_FENCE;
2184
Chia-I Wu7b549592017-11-15 09:14:57 -08002185 // The layer buffer from the previous frame (if any) is released
2186 // by HWC only when the release fence from this frame (if any) is
2187 // signaled. Always get the release fence from HWC first.
2188 auto hwcLayer = layer->getHwcLayer(hwcId);
Chia-I Wu99b46192018-06-21 15:52:50 +08002189 if (hwcId >= 0) {
2190 releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2191 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002192
2193 // If the layer was client composited in the previous frame, we
2194 // need to merge with the previous client target acquire fence.
2195 // Since we do not track that, always merge with the current
2196 // client target acquire fence when it is available, even though
2197 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002199 releaseFence = Fence::merge("LayerRelease", releaseFence,
2200 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002201 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002202
Dan Stoza9e56aa02015-11-02 13:00:03 -08002203 layer->onLayerDisplayed(releaseFence);
2204 }
Chia-I Wu83806892017-11-16 10:50:20 -08002205
2206 // We've got a list of layers needing fences, that are disjoint with
2207 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2208 // supply them with the present fence.
2209 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002210 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002211 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2212 layer->onLayerDisplayed(presentFence);
2213 }
2214 }
2215
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002217 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002218 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002219 }
2220
Mathias Agopiana44b0412011-10-16 18:46:35 -07002221 mLastSwapBufferTime = systemTime() - now;
2222 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002223
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002224 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002225 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2226 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2227 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2228 logFrameStats();
2229 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231}
2232
Mathias Agopian87baae12012-07-31 12:38:26 -07002233void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234{
Mathias Agopian841cde52012-03-01 15:44:37 -08002235 ATRACE_CALL();
2236
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002237 // here we keep a copy of the drawing state (that is the state that's
2238 // going to be overwritten by handleTransactionLocked()) outside of
2239 // mStateLock so that the side-effects of the State assignment
2240 // don't happen with mStateLock held (which can cause deadlocks).
2241 State drawingState(mDrawingState);
2242
Mathias Agopianca4d3602011-05-19 15:38:14 -07002243 Mutex::Autolock _l(mStateLock);
2244 const nsecs_t now = systemTime();
2245 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 // Here we're guaranteed that some transaction flags are set
2248 // so we can call handleTransactionLocked() unconditionally.
2249 // We call getTransactionFlags(), which will also clear the flags,
2250 // with mStateLock held to guarantee that mCurrentState won't change
2251 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002252
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002253 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002254 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002255 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002256
Mathias Agopianca4d3602011-05-19 15:38:14 -07002257 mLastTransactionTime = systemTime() - now;
2258 mDebugInTransaction = 0;
2259 invalidateHwcGeometry();
2260 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002261}
2262
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002264 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002265 // Figure out whether the event is for the primary display or an
2266 // external display by matching the Hwc display id against one for a
2267 // connected display. If we did not find a match, we then check what
2268 // displays are not already connected to determine the type. If we don't
2269 // have a connected primary display, we assume the new display is meant to
2270 // be the primary display, and then if we don't have an external display,
2271 // we assume it is that.
2272 const auto primaryDisplayId =
2273 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2274 const auto externalDisplayId =
2275 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2276 if (primaryDisplayId && primaryDisplayId == display) {
2277 return DisplayDevice::DISPLAY_PRIMARY;
2278 } else if (externalDisplayId && externalDisplayId == display) {
2279 return DisplayDevice::DISPLAY_EXTERNAL;
2280 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2281 return DisplayDevice::DISPLAY_PRIMARY;
2282 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2283 return DisplayDevice::DISPLAY_EXTERNAL;
2284 }
2285
2286 return DisplayDevice::DISPLAY_ID_INVALID;
2287}
2288
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2290 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002291 auto displayType = determineDisplayType(event.display, event.connection);
2292 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2293 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2294 continue;
2295 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296
2297 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2298 ALOGE("External displays are not supported by the vr hardware composer.");
2299 continue;
2300 }
2301
Lloyd Pique715a2c12017-12-14 17:18:08 -08002302 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303
2304 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002305 if (!mBuiltinDisplays[displayType].get()) {
2306 ALOGV("Creating built in display %d", displayType);
2307 mBuiltinDisplays[displayType] = new BBinder();
2308 // All non-virtual displays are currently considered secure.
2309 DisplayDeviceState info(displayType, true);
2310 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2311 "Built-in Screen" : "External Screen";
2312 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002313 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002314 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002316 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002317
Lloyd Piquefcd86612017-12-14 17:15:36 -08002318 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2319 if (idx >= 0) {
2320 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002321 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002322 mCurrentState.displays.removeItemsAt(idx);
2323 }
2324 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002325 }
2326
2327 processDisplayChangesLocked();
2328 }
2329
2330 mPendingHotplugEvents.clear();
2331}
2332
Lloyd Pique09594832018-01-22 17:48:03 -08002333sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2334 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2335 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002337 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu99b46192018-06-21 15:52:50 +08002338 HdrCapabilities hdrCapabilities;
2339 int32_t supportedPerFrameMetadata = 0;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002340
Chia-I Wu99b46192018-06-21 15:52:50 +08002341 if (hasWideColorDisplay && hwcId >= 0) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002343 for (ColorMode colorMode : modes) {
2344 switch (colorMode) {
2345 case ColorMode::DISPLAY_P3:
2346 case ColorMode::ADOBE_RGB:
2347 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002349 break;
2350 default:
2351 break;
2352 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353
2354 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2355 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002356 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002357 }
2358 }
2359
Chia-I Wu99b46192018-06-21 15:52:50 +08002360 if (hwcId >= 0) {
2361 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
2362 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(hwcId);
2363 }
Lloyd Pique09594832018-01-22 17:48:03 -08002364
2365 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2366 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2367
2368 /*
2369 * Create our display's surface
2370 */
2371 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2372 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2373 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2374 renderSurface->setNativeWindow(nativeWindow.get());
2375 const int displayWidth = renderSurface->queryWidth();
2376 const int displayHeight = renderSurface->queryHeight();
2377
2378 // Make sure that composition can never be stalled by a virtual display
2379 // consumer that isn't processing buffers fast enough. We have to do this
2380 // in two places:
2381 // * Here, in case the display is composed entirely by HWC.
2382 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2383 // window's swap interval in eglMakeCurrent, so they'll override the
2384 // interval we set here.
2385 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2386 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2387 }
2388
2389 // virtual displays are always considered enabled
2390 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2391 : HWC_POWER_MODE_OFF;
2392
2393 sp<DisplayDevice> hw =
2394 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2395 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002396 hasWideColorGamut, hdrCapabilities,
Chia-I Wu99b46192018-06-21 15:52:50 +08002397 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002398
2399 if (maxFrameBufferAcquiredBuffers >= 3) {
2400 nativeWindowSurface->preallocateBuffers();
2401 }
2402
2403 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002404 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2405 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002406 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002407 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002408 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002409 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2410 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002411 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2412 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2413 }
Lloyd Pique09594832018-01-22 17:48:03 -08002414 hw->setLayerStack(state.layerStack);
2415 hw->setProjection(state.orientation, state.viewport, state.frame);
2416 hw->setDisplayName(state.displayName);
2417
2418 return hw;
2419}
2420
Lloyd Pique347200f2017-12-14 17:00:15 -08002421void SurfaceFlinger::processDisplayChangesLocked() {
2422 // here we take advantage of Vector's copy-on-write semantics to
2423 // improve performance by skipping the transaction entirely when
2424 // know that the lists are identical
2425 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2426 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2427 if (!curr.isIdenticalTo(draw)) {
2428 mVisibleRegionsDirty = true;
2429 const size_t cc = curr.size();
2430 size_t dc = draw.size();
2431
2432 // find the displays that were removed
2433 // (ie: in drawing state but not in current state)
2434 // also handle displays that changed
2435 // (ie: displays that are in both lists)
2436 for (size_t i = 0; i < dc;) {
2437 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2438 if (j < 0) {
2439 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002440 // Call makeCurrent() on the primary display so we can
2441 // be sure that nothing associated with this display
2442 // is current.
2443 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2444 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2445 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2446 if (hw != nullptr) hw->disconnect(getHwComposer());
2447 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2448 mEventThread->onHotplugReceived(draw[i].type, false);
2449 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 } else {
2451 // this display is in both lists. see if something changed.
2452 const DisplayDeviceState& state(curr[j]);
2453 const wp<IBinder>& display(curr.keyAt(j));
2454 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2455 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2456 if (state_binder != draw_binder) {
2457 // changing the surface is like destroying and
2458 // recreating the DisplayDevice, so we just remove it
2459 // from the drawing state, so that it get re-added
2460 // below.
2461 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2462 if (hw != nullptr) hw->disconnect(getHwComposer());
2463 mDisplays.removeItem(display);
2464 mDrawingState.displays.removeItemsAt(i);
2465 dc--;
2466 // at this point we must loop to the next item
2467 continue;
2468 }
2469
2470 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2471 if (disp != nullptr) {
2472 if (state.layerStack != draw[i].layerStack) {
2473 disp->setLayerStack(state.layerStack);
2474 }
2475 if ((state.orientation != draw[i].orientation) ||
2476 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2477 disp->setProjection(state.orientation, state.viewport, state.frame);
2478 }
2479 if (state.width != draw[i].width || state.height != draw[i].height) {
2480 disp->setDisplaySize(state.width, state.height);
2481 }
2482 }
2483 }
2484 ++i;
2485 }
2486
2487 // find displays that were added
2488 // (ie: in current state but not in drawing state)
2489 for (size_t i = 0; i < cc; i++) {
2490 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2491 const DisplayDeviceState& state(curr[i]);
2492
2493 sp<DisplaySurface> dispSurface;
2494 sp<IGraphicBufferProducer> producer;
2495 sp<IGraphicBufferProducer> bqProducer;
2496 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002497 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002498
2499 int32_t hwcId = -1;
2500 if (state.isVirtualDisplay()) {
2501 // Virtual displays without a surface are dormant:
2502 // they have external state (layer stack, projection,
2503 // etc.) but no internal state (i.e. a DisplayDevice).
2504 if (state.surface != nullptr) {
2505 // Allow VR composer to use virtual displays.
2506 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2507 int width = 0;
2508 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2509 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2510 int height = 0;
2511 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2512 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2513 int intFormat = 0;
2514 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2515 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002516 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517
2518 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2519 }
2520
2521 // TODO: Plumb requested format back up to consumer
2522
2523 sp<VirtualDisplaySurface> vds =
2524 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2525 bqProducer, bqConsumer,
2526 state.displayName);
2527
2528 dispSurface = vds;
2529 producer = vds;
2530 }
2531 } else {
2532 ALOGE_IF(state.surface != nullptr,
2533 "adding a supported display, but rendering "
2534 "surface is provided (%p), ignoring it",
2535 state.surface.get());
2536
2537 hwcId = state.type;
2538 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2539 producer = bqProducer;
2540 }
2541
2542 const wp<IBinder>& display(curr.keyAt(i));
2543 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002544 mDisplays.add(display,
2545 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2546 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 if (!state.isVirtualDisplay()) {
2548 mEventThread->onHotplugReceived(state.type, true);
2549 }
2550 }
2551 }
2552 }
2553 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554
2555 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002556}
2557
Mathias Agopian87baae12012-07-31 12:38:26 -07002558void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002559{
Dan Stoza7dde5992015-05-22 09:51:44 -07002560 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002561 mCurrentState.traverseInZOrder([](Layer* layer) {
2562 layer->notifyAvailableFrames();
2563 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002564
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 /*
2566 * Traversal of the children
2567 * (perform the transaction for each of them if needed)
2568 */
2569
Mathias Agopian3559b072012-08-15 13:46:03 -07002570 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002571 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002573 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574
2575 const uint32_t flags = layer->doTransaction(0);
2576 if (flags & Layer::eVisibleRegion)
2577 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002578 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 }
2580
2581 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 */
2584
Mathias Agopiane57f2922012-08-09 16:29:12 -07002585 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002590 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002591 // The transform hint might have changed for some layers
2592 // (either because a display has changed, or because a layer
2593 // as changed).
2594 //
2595 // Walk through all the layers in currentLayers,
2596 // and update their transform hint.
2597 //
2598 // If a layer is visible only on a single display, then that
2599 // display is used to calculate the hint, otherwise we use the
2600 // default display.
2601 //
2602 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2603 // the hint is set before we acquire a buffer from the surface texture.
2604 //
2605 // NOTE: layer transactions have taken place already, so we use their
2606 // drawing state. However, SurfaceFlinger's own transaction has not
2607 // happened yet, so we must use the current state layer list
2608 // (soon to become the drawing state list).
2609 //
2610 sp<const DisplayDevice> disp;
2611 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002612 bool first = true;
2613 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002614 // NOTE: we rely on the fact that layers are sorted by
2615 // layerStack first (so we don't have to traverse the list
2616 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002617 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002618 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002619 currentlayerStack = layerStack;
2620 // figure out if this layerstack is mirrored
2621 // (more than one display) if so, pick the default display,
2622 // if not, pick the only display it's on.
2623 disp.clear();
2624 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2625 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002626 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002627 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002628 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002629 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002630 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002631 break;
2632 }
2633 }
2634 }
2635 }
Chet Haase91d25932013-04-11 15:24:55 -07002636
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002637 if (disp == nullptr) {
2638 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2639 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002640
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002641 // could be null when this layer is using a layerStack
2642 // that is not visible on any display. Also can occur at
2643 // screen off/on times.
2644 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002645 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002646
2647 // disp can be null if there is no display available at all to get
2648 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002649 if (disp != nullptr) {
2650 layer->updateTransformHint(disp);
2651 }
Robert Carr2047fae2016-11-28 14:09:09 -08002652
2653 first = false;
2654 });
Mathias Agopian84300952012-11-21 16:02:13 -08002655 }
2656
2657
Mathias Agopian3559b072012-08-15 13:46:03 -07002658 /*
2659 * Perform our own transaction if needed
2660 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661
2662 if (mLayersAdded) {
2663 mLayersAdded = false;
2664 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002665 mVisibleRegionsDirty = true;
2666 }
2667
2668 // some layers might have been removed, so
2669 // we need to update the regions they're exposing.
2670 if (mLayersRemoved) {
2671 mLayersRemoved = false;
2672 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002673 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002675 // this layer is not visible anymore
2676 // TODO: we could traverse the tree from front to back and
2677 // compute the actual visible region
2678 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 Region visibleReg;
2680 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002681 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002682 }
Robert Carr2047fae2016-11-28 14:09:09 -08002683 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 }
2685
2686 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002687
2688 updateCursorAsync();
2689}
2690
2691void SurfaceFlinger::updateCursorAsync()
2692{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2694 auto& displayDevice = mDisplays[displayId];
2695 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002696 continue;
2697 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698
2699 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2700 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002701 }
2702 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002703}
2704
2705void SurfaceFlinger::commitTransaction()
2706{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002707 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002708 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002709 for (const auto& l : mLayersPendingRemoval) {
2710 recordBufferingStats(l->getName().string(),
2711 l->getOccupancyHistory(true));
2712 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 }
2714 mLayersPendingRemoval.clear();
2715 }
2716
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002717 // If this transaction is part of a window animation then the next frame
2718 // we composite should be considered an animation as well.
2719 mAnimCompositionPending = mAnimTransactionPending;
2720
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002722 // clear the "changed" flags in current state
2723 mCurrentState.colorMatrixChanged = false;
2724
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 mDrawingState.traverseInZOrder([](Layer* layer) {
2726 layer->commitChildList();
2727 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002728 mTransactionPending = false;
2729 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731}
2732
Chia-I Wuab0c3192017-08-01 11:29:00 -07002733void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002734 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735{
Mathias Agopian841cde52012-03-01 15:44:37 -08002736 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002738
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 Region aboveOpaqueLayers;
2740 Region aboveCoveredLayers;
2741 Region dirty;
2742
Mathias Agopian87baae12012-07-31 12:38:26 -07002743 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744
Robert Carr2047fae2016-11-28 14:09:09 -08002745 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002747 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Jesse Hall01e29052013-02-19 16:13:35 -08002749 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002750 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002751 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002752
Mathias Agopianab028732010-03-16 16:41:46 -07002753 /*
2754 * opaqueRegion: area of a surface that is fully opaque.
2755 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002757
2758 /*
2759 * visibleRegion: area of a surface that is visible on screen
2760 * and not fully transparent. This is essentially the layer's
2761 * footprint minus the opaque regions above it.
2762 * Areas covered by a translucent surface are considered visible.
2763 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002765
2766 /*
2767 * coveredRegion: area of a surface that is covered by all
2768 * visible regions above it (which includes the translucent areas).
2769 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002771
Jesse Halla8026d22012-09-25 13:25:04 -07002772 /*
2773 * transparentRegion: area of a surface that is hinted to be completely
2774 * transparent. This is only used to tell when the layer has no visible
2775 * non-transparent regions and can be removed from the layer list. It
2776 * does not affect the visibleRegion of this layer or any layers
2777 * beneath it. The hint may not be correct if apps don't respect the
2778 * SurfaceView restrictions (which, sadly, some don't).
2779 */
2780 Region transparentRegion;
2781
Mathias Agopianab028732010-03-16 16:41:46 -07002782
2783 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002784 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002785 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002789 if (!visibleRegion.isEmpty()) {
2790 // Remove the transparent area from the visible region
2791 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002792 if (tr.preserveRects()) {
2793 // transform the transparent region
2794 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002796 // transformation too complex, can't do the
2797 // transparent region optimization.
2798 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 }
Mathias Agopianab028732010-03-16 16:41:46 -07002800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801
Mathias Agopianab028732010-03-16 16:41:46 -07002802 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002804 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002805 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2806 // the opaque region is the layer's footprint
2807 opaqueRegion = visibleRegion;
2808 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 }
2810 }
2811
Robert Carre5f4f692018-01-12 13:12:28 -08002812 if (visibleRegion.isEmpty()) {
2813 layer->clearVisibilityRegions();
2814 return;
2815 }
2816
Mathias Agopianab028732010-03-16 16:41:46 -07002817 // Clip the covered region to the visible region
2818 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2819
2820 // Update aboveCoveredLayers for next (lower) layer
2821 aboveCoveredLayers.orSelf(visibleRegion);
2822
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 // subtract the opaque region covered by the layers above us
2824 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825
2826 // compute this layer's dirty region
2827 if (layer->contentDirty) {
2828 // we need to invalidate the whole region
2829 dirty = visibleRegion;
2830 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 layer->contentDirty = false;
2833 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002834 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002835 * the exposed region consists of two components:
2836 * 1) what's VISIBLE now and was COVERED before
2837 * 2) what's EXPOSED now less what was EXPOSED before
2838 *
2839 * note that (1) is conservative, we start with the whole
2840 * visible region but only keep what used to be covered by
2841 * something -- which mean it may have been exposed.
2842 *
2843 * (2) handles areas that were not covered by anything but got
2844 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002845 */
Mathias Agopianab028732010-03-16 16:41:46 -07002846 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 const Region oldVisibleRegion = layer->visibleRegion;
2848 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002849 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2850 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 }
2852 dirty.subtractSelf(aboveOpaqueLayers);
2853
2854 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002855 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856
Mathias Agopianab028732010-03-16 16:41:46 -07002857 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002859
Jesse Halla8026d22012-09-25 13:25:04 -07002860 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 layer->setVisibleRegion(visibleRegion);
2862 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002863 layer->setVisibleNonTransparentRegion(
2864 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002865 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
Mathias Agopian87baae12012-07-31 12:38:26 -07002867 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868}
2869
Chia-I Wuab0c3192017-08-01 11:29:00 -07002870void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002871 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002872 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002873 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002874 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002875 }
2876 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002877}
2878
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 ALOGV("handlePageFlip");
2882
Brian Andersond6927fb2016-07-23 23:37:30 -07002883 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884
Mathias Agopian4fec8732012-06-29 14:12:52 -07002885 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002886 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002887 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002888
2889 // Store the set of layers that need updates. This set must not change as
2890 // buffers are being latched, as this could result in a deadlock.
2891 // Example: Two producers share the same command stream and:
2892 // 1.) Layer 0 is latched
2893 // 2.) Layer 0 gets a new frame
2894 // 2.) Layer 1 gets a new frame
2895 // 3.) Layer 1 is latched.
2896 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2897 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002898 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002899 if (layer->hasQueuedFrame()) {
2900 frameQueued = true;
2901 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002902 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002903 } else {
2904 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002906 } else {
2907 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908 }
Robert Carr2047fae2016-11-28 14:09:09 -08002909 });
2910
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002912 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002913 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002914 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002915 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002916 newDataLatched = true;
2917 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002918 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002919
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002920 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921
2922 // If we will need to wake up at some time in the future to deal with a
2923 // queued frame that shouldn't be displayed during this vsync period, wake
2924 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002925 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002926 signalLayerUpdate();
2927 }
2928
Chia-I Wuad8d8272018-06-26 10:18:18 +08002929 // enter boot animation on first buffer latch
2930 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2931 ALOGI("Enter boot animation");
2932 mBootStage = BootStage::BOOTANIMATION;
2933 }
2934
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002936 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937}
2938
Mathias Agopianad456f92011-01-13 17:53:01 -08002939void SurfaceFlinger::invalidateHwcGeometry()
2940{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002942}
2943
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002944
Fabien Sanglard830b8472016-11-30 16:35:58 -08002945void SurfaceFlinger::doDisplayComposition(
2946 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002947 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948{
Dan Stoza71433162014-02-04 16:22:36 -08002949 // We only need to actually compose the display if:
2950 // 1) It is being handled by hardware composer, which may need this to
2951 // keep its virtual display state machine in sync, or
2952 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002953 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002954 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002956 return;
2957 }
2958
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002960 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002961
2962 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002963 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Chia-I Wub02087d2017-11-09 10:19:54 -08002966bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002967{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002969
Chia-I Wub02087d2017-11-09 10:19:54 -08002970 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002971 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002973 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002974 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002975
Chia-I Wu8e50e692018-05-04 10:12:37 -07002976 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002977 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002978
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 if (hasClientComposition) {
2980 ALOGV("hasClientComposition");
2981
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002982 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002983 if (displayDevice->hasWideColorGamut()) {
2984 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002985 }
2986 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002987 getBE().mRenderEngine->setDisplayMaxLuminance(
2988 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002989
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2991 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2992 HWC2::Capability::SkipClientColorTransform);
2993
Chia-I Wu6d844112018-06-27 07:17:41 +08002994 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002995 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2996 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08002997 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002998 }
2999
Chia-I Wu6d844112018-06-27 07:17:41 +08003000 // The current enhanced saturation matrix is designed to enhance Display P3,
3001 // thus we only apply this matrix when the render intent is not colorimetric
3002 // and the output color space is Display P3.
3003 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07003004 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08003005 outputDataspace == Dataspace::DISPLAY_P3);
3006 if (needsEnhancedColorMatrix) {
3007 colorMatrix *= mEnhancedSaturationMatrix;
3008 }
3009
3010 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003011
Chia-I Wu7f402902017-11-09 12:51:10 -08003012 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003013 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003015 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003016
3017 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003018 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003019 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3020 }
3021 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003022 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003023
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003024 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003026 // when using overlays, we assume a fully transparent framebuffer
3027 // NOTE: we could reduce how much we need to clear, for instance
3028 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003029 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003030 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003031 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003032 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003033 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003034 // we're left with the letterbox region
3035 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003037
3038 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003040
Mathias Agopianb9494d52012-04-18 02:28:45 -07003041 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003042 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003043 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003045 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003046 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003047
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003049 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003050 // scissor on the main display. It should never be needed
3051 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 const Rect& bounds(displayDevice->getBounds());
3053 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003054 if (scissor != bounds) {
3055 // scissor doesn't match the screen's dimensions, so we
3056 // need to clear everything outside of it and enable
3057 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003058
Mathias Agopianf45c5102012-10-24 16:29:17 -07003059 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003060 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003061 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003062 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003063 }
3064 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003065 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003066
Mathias Agopian85d751c2012-08-29 16:59:24 -07003067 /*
3068 * and then, render the layers targeted at the framebuffer
3069 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003070
Dan Stoza9e56aa02015-11-02 13:00:03 -08003071 ALOGV("Rendering client layers");
3072 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 bool firstLayer = true;
3074 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3075 const Region clip(bounds.intersect(
3076 displayTransform.transform(layer->visibleRegion)));
3077 ALOGV("Layer: %s", layer->getName().string());
3078 ALOGV(" Composition type: %s",
3079 to_string(layer->getCompositionType(hwcId)).c_str());
3080 if (!clip.isEmpty()) {
3081 switch (layer->getCompositionType(hwcId)) {
3082 case HWC2::Composition::Cursor:
3083 case HWC2::Composition::Device:
3084 case HWC2::Composition::Sideband:
3085 case HWC2::Composition::SolidColor: {
3086 const Layer::State& state(layer->getDrawingState());
3087 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3088 layer->isOpaque(state) && (state.color.a == 1.0f)
3089 && hasClientComposition) {
3090 // never clear the very first layer since we're
3091 // guaranteed the FB is already cleared
3092 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003093 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003094 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003095 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003096 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003097 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 break;
3099 }
3100 default:
3101 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003102 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 } else {
3104 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003107 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003108
Chia-I Wu6d844112018-06-27 07:17:41 +08003109 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003110 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003111 }
3112
Mathias Agopianf45c5102012-10-24 16:29:17 -07003113 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003114 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003115 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116}
3117
Fabien Sanglard830b8472016-11-30 16:35:58 -08003118void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3119 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003120 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003121 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122}
3123
Dan Stoza7d89d062015-04-30 13:29:25 -07003124status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003125 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003126 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 const sp<Layer>& lbc,
3128 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003129{
Dan Stoza7d89d062015-04-30 13:29:25 -07003130 // add this layer to the current state list
3131 {
3132 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003134 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3135 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003136 return NO_MEMORY;
3137 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 if (parent == nullptr) {
3139 mCurrentState.layersSortedByZ.add(lbc);
3140 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003141 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003142 ALOGE("addClientLayer called with a removed parent");
3143 return NAME_NOT_FOUND;
3144 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 parent->addChild(lbc);
3146 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003147
Yiwei Zhang243b3782018-05-15 17:40:04 -07003148 if (gbc != nullptr) {
3149 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3150 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3151 mMaxGraphicBufferProducerListSize,
3152 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3153 mGraphicBufferProducerList.size(),
3154 mMaxGraphicBufferProducerListSize, mNumLayers);
3155 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003156 mLayersAdded = true;
3157 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003158 }
3159
Mathias Agopian96f08192010-06-02 23:28:45 -07003160 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003161 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003162
Dan Stoza7d89d062015-04-30 13:29:25 -07003163 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003164}
3165
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003166status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003167 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003168 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3169}
Robert Carr7f9b8992017-03-10 11:08:39 -08003170
chaviwca27f252018-02-06 16:46:39 -08003171status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3172 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003173 if (layer->isPendingRemoval()) {
3174 return NO_ERROR;
3175 }
3176
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003178 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003179 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003180 if (topLevelOnly) {
3181 return NO_ERROR;
3182 }
3183
Chia-I Wu98f1c102017-05-30 14:54:08 -07003184 sp<Layer> ancestor = p;
3185 while (ancestor->getParent() != nullptr) {
3186 ancestor = ancestor->getParent();
3187 }
3188 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3189 ALOGE("removeLayer called with a layer whose parent has been removed");
3190 return NAME_NOT_FOUND;
3191 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003192
3193 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003194 } else {
3195 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003196 }
3197
Robert Carr136e2f62017-02-08 17:54:29 -08003198 // As a matter of normal operation, the LayerCleaner will produce a second
3199 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3200 // so we will succeed in promoting it, but it's already been removed
3201 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3202 // otherwise something has gone wrong and we are leaking the layer.
3203 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003204 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3205 layer->getName().string(),
3206 (p != nullptr) ? p->getName().string() : "no-parent");
3207 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003208 } else if (index < 0) {
3209 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003210 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211
Chia-I Wuc6657022017-08-15 11:18:17 -07003212 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 mLayersPendingRemoval.add(layer);
3214 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003215 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003216 setTransactionFlags(eTransactionNeeded);
3217 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218}
3219
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003220uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003221 return android_atomic_release_load(&mTransactionFlags);
3222}
3223
Mathias Agopian3f844832013-08-07 21:24:32 -07003224uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3226}
3227
Mathias Agopian3f844832013-08-07 21:24:32 -07003228uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003229 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3230}
3231
3232uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3233 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003235 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003237 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 }
3239 return old;
3240}
3241
chaviwca27f252018-02-06 16:46:39 -08003242bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3243 for (const ComposerState& state : states) {
3244 // Here we need to check that the interface we're given is indeed
3245 // one of our own. A malicious client could give us a nullptr
3246 // IInterface, or one of its own or even one of our own but a
3247 // different type. All these situations would cause us to crash.
3248 if (state.client == nullptr) {
3249 return true;
3250 }
3251
3252 sp<IBinder> binder = IInterface::asBinder(state.client);
3253 if (binder == nullptr) {
3254 return true;
3255 }
3256
3257 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3258 return true;
3259 }
3260 }
3261 return false;
3262}
3263
Mathias Agopian8b33f032012-07-24 20:43:54 -07003264void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003265 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003266 const Vector<DisplayState>& displays,
3267 uint32_t flags)
3268{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003269 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003270 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003271 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003272
chaviwca27f252018-02-06 16:46:39 -08003273 if (containsAnyInvalidClientState(states)) {
3274 return;
3275 }
3276
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003277 if (flags & eAnimation) {
3278 // For window updates that are part of an animation we must wait for
3279 // previous animation "frames" to be handled.
3280 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003281 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003282 if (CC_UNLIKELY(err != NO_ERROR)) {
3283 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003284 // caller after a few seconds.
3285 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3286 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003287 mAnimTransactionPending = false;
3288 break;
3289 }
3290 }
3291 }
3292
chaviwca27f252018-02-06 16:46:39 -08003293 for (const DisplayState& display : displays) {
3294 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003295 }
3296
chaviwca27f252018-02-06 16:46:39 -08003297 for (const ComposerState& state : states) {
3298 transactionFlags |= setClientStateLocked(state);
3299 }
3300
3301 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3302 // as destroyed should only occur after setting all other states. This is to allow for a
3303 // child re-parent to happen before marking its original parent as destroyed (which would
3304 // then mark the child as destroyed).
3305 for (const ComposerState& state : states) {
3306 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003307 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003308
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003309 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3310 // anyway. This can be used as a flush mechanism for previous async transactions.
3311 // Empty animation transaction can be used to simulate back-pressure, so also force a
3312 // transaction for empty animation transactions.
3313 if (transactionFlags == 0 &&
3314 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003315 transactionFlags = eTransactionNeeded;
3316 }
3317
Mathias Agopian386aa982011-11-07 21:58:03 -08003318 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003319 if (mInterceptor->isEnabled()) {
3320 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003321 }
Irvel468051e2016-06-13 16:44:44 -07003322
Mathias Agopian386aa982011-11-07 21:58:03 -08003323 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003324 const auto start = (flags & eEarlyWakeup)
3325 ? VSyncModulator::TransactionStart::EARLY
3326 : VSyncModulator::TransactionStart::NORMAL;
3327 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003328
3329 // if this is a synchronous transaction, wait for it to take effect
3330 // before returning.
3331 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003332 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003334 if (flags & eAnimation) {
3335 mAnimTransactionPending = true;
3336 }
3337 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3339 if (CC_UNLIKELY(err != NO_ERROR)) {
3340 // just in case something goes wrong in SF, return to the
3341 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003342 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3343 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 break;
3345 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347 }
3348}
3349
Mathias Agopiane57f2922012-08-09 16:29:12 -07003350uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3351{
Jesse Hall9a143922012-10-04 16:29:19 -07003352 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3353 if (dpyIdx < 0)
3354 return 0;
3355
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003357 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003358 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003359 const uint32_t what = s.what;
3360 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003361 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 disp.surface = s.surface;
3363 flags |= eDisplayTransactionNeeded;
3364 }
3365 }
3366 if (what & DisplayState::eLayerStackChanged) {
3367 if (disp.layerStack != s.layerStack) {
3368 disp.layerStack = s.layerStack;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003372 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 if (disp.orientation != s.orientation) {
3374 disp.orientation = s.orientation;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 if (disp.frame != s.frame) {
3378 disp.frame = s.frame;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 if (disp.viewport != s.viewport) {
3382 disp.viewport = s.viewport;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 }
Michael Lentine47e45402014-07-18 15:34:25 -07003386 if (what & DisplayState::eDisplaySizeChanged) {
3387 if (disp.width != s.width) {
3388 disp.width = s.width;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 if (disp.height != s.height) {
3392 disp.height = s.height;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003396 }
3397 return flags;
3398}
3399
Robert Carrd4ae7f32018-06-07 16:10:57 -07003400bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3401 IPCThreadState* ipc = IPCThreadState::self();
3402 const int pid = ipc->getCallingPid();
3403 const int uid = ipc->getCallingUid();
3404
3405 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3406 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3407 return false;
3408 }
3409 return true;
3410}
3411
chaviwca27f252018-02-06 16:46:39 -08003412uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3413 const layer_state_t& s = composerState.state;
3414 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3415
Mathias Agopian13127d82013-03-05 17:47:11 -08003416 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003417 if (layer == nullptr) {
3418 return 0;
3419 }
3420
3421 if (layer->isPendingRemoval()) {
3422 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3423 return 0;
3424 }
3425
3426 uint32_t flags = 0;
3427
3428 const uint32_t what = s.what;
3429 bool geometryAppliesWithResize =
3430 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003431
3432 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3433 // pending state will also be deferred.
3434 if (what & layer_state_t::eDeferTransaction) {
3435 layer->pushPendingState();
3436 }
3437
chaviw8b3871a2017-11-01 17:41:01 -07003438 if (what & layer_state_t::ePositionChanged) {
3439 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3440 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 }
3443 if (what & layer_state_t::eLayerChanged) {
3444 // NOTE: index needs to be calculated before we update the state
3445 const auto& p = layer->getParent();
3446 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003447 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003448 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003449 mCurrentState.layersSortedByZ.removeAt(idx);
3450 mCurrentState.layersSortedByZ.add(layer);
3451 // we need traversal (state changed)
3452 // AND transaction (list changed)
3453 flags |= eTransactionNeeded|eTraversalNeeded;
3454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 } else {
3456 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003457 flags |= eTransactionNeeded|eTraversalNeeded;
3458 }
3459 }
chaviw8b3871a2017-11-01 17:41:01 -07003460 }
3461 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003462 // NOTE: index needs to be calculated before we update the state
3463 const auto& p = layer->getParent();
3464 if (p == nullptr) {
3465 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3466 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3467 mCurrentState.layersSortedByZ.removeAt(idx);
3468 mCurrentState.layersSortedByZ.add(layer);
3469 // we need traversal (state changed)
3470 // AND transaction (list changed)
3471 flags |= eTransactionNeeded|eTraversalNeeded;
3472 }
3473 } else {
3474 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3475 flags |= eTransactionNeeded|eTraversalNeeded;
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 }
3478 }
3479 if (what & layer_state_t::eSizeChanged) {
3480 if (layer->setSize(s.w, s.h)) {
3481 flags |= eTraversalNeeded;
3482 }
3483 }
3484 if (what & layer_state_t::eAlphaChanged) {
3485 if (layer->setAlpha(s.alpha))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eColorChanged) {
3489 if (layer->setColor(s.color))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003493 // TODO: b/109894387
3494 //
3495 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3496 // rotation. To see the problem observe that if we have a square parent, and a child
3497 // of the same size, then we rotate the child 45 degrees around it's center, the child
3498 // must now be cropped to a non rectangular 8 sided region.
3499 //
3500 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3501 // private API, and the WindowManager only uses rotation in one case, which is on a top
3502 // level layer in which cropping is not an issue.
3503 //
3504 // However given that abuse of rotation matrices could lead to surfaces extending outside
3505 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3506 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3507 // transformations.
3508 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003509 flags |= eTraversalNeeded;
3510 }
3511 if (what & layer_state_t::eTransparentRegionChanged) {
3512 if (layer->setTransparentRegionHint(s.transparentRegion))
3513 flags |= eTraversalNeeded;
3514 }
3515 if (what & layer_state_t::eFlagsChanged) {
3516 if (layer->setFlags(s.flags, s.mask))
3517 flags |= eTraversalNeeded;
3518 }
3519 if (what & layer_state_t::eCropChanged) {
3520 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3521 flags |= eTraversalNeeded;
3522 }
3523 if (what & layer_state_t::eFinalCropChanged) {
3524 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3525 flags |= eTraversalNeeded;
3526 }
3527 if (what & layer_state_t::eLayerStackChanged) {
3528 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3529 // We only allow setting layer stacks for top level layers,
3530 // everything else inherits layer stack from its parent.
3531 if (layer->hasParent()) {
3532 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3533 layer->getName().string());
3534 } else if (idx < 0) {
3535 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3536 "that also does not appear in the top level layer list. Something"
3537 " has gone wrong.", layer->getName().string());
3538 } else if (layer->setLayerStack(s.layerStack)) {
3539 mCurrentState.layersSortedByZ.removeAt(idx);
3540 mCurrentState.layersSortedByZ.add(layer);
3541 // we need traversal (state changed)
3542 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003543 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003544 }
3545 }
3546 if (what & layer_state_t::eDeferTransaction) {
3547 if (s.barrierHandle != nullptr) {
3548 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3549 } else if (s.barrierGbp != nullptr) {
3550 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3551 if (authenticateSurfaceTextureLocked(gbp)) {
3552 const auto& otherLayer =
3553 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3554 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3555 } else {
3556 ALOGE("Attempt to defer transaction to to an"
3557 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003558 }
3559 }
chaviw8b3871a2017-11-01 17:41:01 -07003560 // We don't trigger a traversal here because if no other state is
3561 // changed, we don't want this to cause any more work
3562 }
3563 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003564 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003565 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003566 if (!hadParent) {
3567 mCurrentState.layersSortedByZ.remove(layer);
3568 }
chaviw8b3871a2017-11-01 17:41:01 -07003569 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 }
3572 if (what & layer_state_t::eReparentChildren) {
3573 if (layer->reparentChildren(s.reparentHandle)) {
3574 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003575 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 if (what & layer_state_t::eDetachChildren) {
3578 layer->detachChildren();
3579 }
3580 if (what & layer_state_t::eOverrideScalingModeChanged) {
3581 layer->setOverrideScalingMode(s.overrideScalingMode);
3582 // We don't trigger a traversal here because if no other state is
3583 // changed, we don't want this to cause any more work
3584 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585 return flags;
3586}
3587
chaviwca27f252018-02-06 16:46:39 -08003588void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3589 const layer_state_t& state = composerState.state;
3590 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3591
3592 sp<Layer> layer(client->getLayerUser(state.surface));
3593 if (layer == nullptr) {
3594 return;
3595 }
3596
3597 if (layer->isPendingRemoval()) {
3598 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3599 return;
3600 }
3601
3602 if (state.what & layer_state_t::eDestroySurface) {
3603 removeLayerLocked(mStateLock, layer);
3604 }
3605}
3606
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003608 const String8& name,
3609 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003611 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003612 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003614 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003615 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003616 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003618 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003619
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 status_t result = NO_ERROR;
3621
3622 sp<Layer> layer;
3623
Cody Northropbc755282017-03-31 12:00:08 -06003624 String8 uniqueName = getUniqueLayerName(name);
3625
Mathias Agopian3165cc22012-08-08 19:42:09 -07003626 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3627 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003628 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003629 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632 break;
chaviw13fdc492017-06-27 12:40:18 -07003633 case ISurfaceComposerClient::eFXSurfaceColor:
3634 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003635 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003636 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003637 break;
3638 default:
3639 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640 break;
3641 }
3642
Dan Stoza7d89d062015-04-30 13:29:25 -07003643 if (result != NO_ERROR) {
3644 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003646
Chia-I Wuab0c3192017-08-01 11:29:00 -07003647 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3648 // TODO b/64227542
3649 if (windowType == 441731) {
3650 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3651 layer->setPrimaryDisplayOnly();
3652 }
3653
Albert Chaulk479c60c2017-01-27 14:21:34 -05003654 layer->setInfo(windowType, ownerUid);
3655
Robert Carr1f0a16a2016-10-24 16:27:39 -07003656 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003657 if (result != NO_ERROR) {
3658 return result;
3659 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003660 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003661
3662 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003664}
3665
Cody Northropbc755282017-03-31 12:00:08 -06003666String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3667{
3668 bool matchFound = true;
3669 uint32_t dupeCounter = 0;
3670
3671 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3672 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3673
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003674 // Grab the state lock since we're accessing mCurrentState
3675 Mutex::Autolock lock(mStateLock);
3676
Cody Northropbc755282017-03-31 12:00:08 -06003677 // Loop over layers until we're sure there is no matching name
3678 while (matchFound) {
3679 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003680 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003681 if (layer->getName() == uniqueName) {
3682 matchFound = true;
3683 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3684 }
3685 });
3686 }
3687
3688 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3689
3690 return uniqueName;
3691}
3692
David Sodman0c69cad2017-08-21 12:12:51 -07003693status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3695 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696{
3697 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003698 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699 case PIXEL_FORMAT_TRANSPARENT:
3700 case PIXEL_FORMAT_TRANSLUCENT:
3701 format = PIXEL_FORMAT_RGBA_8888;
3702 break;
3703 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003704 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 break;
3706 }
3707
David Sodman0c69cad2017-08-21 12:12:51 -07003708 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3709 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003710 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003711 *handle = layer->getHandle();
3712 *gbp = layer->getProducer();
3713 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003715
David Sodman0c69cad2017-08-21 12:12:51 -07003716 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003717 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003718}
3719
chaviw13fdc492017-06-27 12:40:18 -07003720status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003721 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003722 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723{
chaviw13fdc492017-06-27 12:40:18 -07003724 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003725 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003727}
3728
Mathias Agopianac9fa422013-02-11 16:40:36 -08003729status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730{
Robert Carr9524cb32017-02-13 11:32:32 -08003731 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003732 status_t err = NO_ERROR;
3733 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003734 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003735 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003736 err = removeLayer(l);
3737 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3738 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003739 }
3740 return err;
3741}
3742
Mathias Agopian13127d82013-03-05 17:47:11 -08003743status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003744{
Mathias Agopian67106042013-03-14 19:18:13 -07003745 // called by ~LayerCleaner() when all references to the IBinder (handle)
3746 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003747 sp<Layer> l = layer.promote();
3748 if (l == nullptr) {
3749 // The layer has already been removed, carry on
3750 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003751 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003752 // If we have a parent, then we can continue to live as long as it does.
3753 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754}
3755
Mathias Agopianb60314a2012-04-10 22:09:54 -07003756// ---------------------------------------------------------------------------
3757
Andy McFadden13a082e2012-08-24 10:16:42 -07003758void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003759 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003760 Vector<ComposerState> state;
3761 Vector<DisplayState> displays;
3762 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003763 d.what = DisplayState::eDisplayProjectionChanged |
3764 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003765 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003766 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003767 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003768 d.frame.makeInvalid();
3769 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003770 d.width = 0;
3771 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003772 displays.add(d);
3773 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003774 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3775 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003776
David Sodman105b7dc2017-11-04 20:28:14 -07003777 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003778 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003779 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003780
Brian Andersond0010582017-03-07 13:20:31 -08003781 // Use phase of 0 since phase is not known.
3782 // Use latency of 0, which will snap to the ideal latency.
3783 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003784}
3785
3786void SurfaceFlinger::initializeDisplays() {
3787 class MessageScreenInitialized : public MessageBase {
3788 SurfaceFlinger* flinger;
3789 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003790 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003791 virtual bool handler() {
3792 flinger->onInitializeDisplays();
3793 return true;
3794 }
3795 };
3796 sp<MessageBase> msg = new MessageScreenInitialized(this);
3797 postMessageAsync(msg); // we may be called from main thread, use async message
3798}
3799
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003801 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3803 this);
3804 int32_t type = hw->getDisplayType();
3805 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003806
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003807 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003808 return;
3809 }
3810
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003811 hw->setPowerMode(mode);
3812 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3813 ALOGW("Trying to set power mode for virtual display");
3814 return;
3815 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003816
Lloyd Pique4d234852018-01-22 17:21:36 -08003817 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003818 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003819 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3820 if (idx < 0) {
3821 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3822 return;
3823 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003824 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003825 }
3826
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003827 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003828 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003829 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003830 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3831 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003832 // FIXME: eventthread only knows about the main display right now
3833 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003834 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003837 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003838 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003839 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003840
3841 struct sched_param param = {0};
3842 param.sched_priority = 1;
3843 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3844 ALOGW("Couldn't set SCHED_FIFO on display on");
3845 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003847 // Turn off the display
3848 struct sched_param param = {0};
3849 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3850 ALOGW("Couldn't set SCHED_OTHER on display off");
3851 }
3852
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003853 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3854 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003855 disableHardwareVsync(true); // also cancels any in-progress resync
3856
Mathias Agopiancde87a32012-09-13 14:09:01 -07003857 // FIXME: eventthread only knows about the main display right now
3858 mEventThread->onScreenReleased();
3859 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003860
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861 getHwComposer().setPowerMode(type, mode);
3862 mVisibleRegionsDirty = true;
3863 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003864 } else if (mode == HWC_POWER_MODE_DOZE ||
3865 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003866 // Update display while dozing
3867 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003868 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3869 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003870 // FIXME: eventthread only knows about the main display right now
3871 mEventThread->onScreenAcquired();
3872 resyncToHardwareVsync(true);
3873 }
3874 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3875 // Leave display going to doze
3876 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3877 disableHardwareVsync(true); // also cancels any in-progress resync
3878 // FIXME: eventthread only knows about the main display right now
3879 mEventThread->onScreenReleased();
3880 }
3881 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003882 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003883 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003884 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003885 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003886 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003887}
3888
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3890 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003891 SurfaceFlinger& mFlinger;
3892 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003893 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003894 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003895 MessageSetPowerMode(SurfaceFlinger& flinger,
3896 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3897 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003898 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003899 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003900 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003902 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003903 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 ALOGW("Attempt to set power mode = %d for virtual display",
3905 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003906 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003907 mFlinger.setPowerModeInternal(
3908 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003909 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003910 return true;
3911 }
3912 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003913 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003914 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003915}
3916
3917// ---------------------------------------------------------------------------
3918
Lloyd Pique755e3192018-01-31 16:46:15 -08003919status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3920 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003921 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003922
Mathias Agopianbd115332013-04-18 16:41:04 -07003923 IPCThreadState* ipc = IPCThreadState::self();
3924 const int pid = ipc->getCallingPid();
3925 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003926
Mathias Agopianbd115332013-04-18 16:41:04 -07003927 if ((uid != AID_SHELL) &&
3928 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003929 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003930 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003932 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003933 // (this would indicate SF is stuck, but we want to be able to
3934 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003935 status_t err = mStateLock.timedLock(s2ns(1));
3936 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003937 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003938 result.appendFormat(
3939 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3940 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003941 }
3942
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943 bool dumpAll = true;
3944 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003945 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003946
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948 if ((index < numArgs) &&
3949 (args[index] == String16("--list"))) {
3950 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003952 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953 }
3954
3955 if ((index < numArgs) &&
3956 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003958 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003959 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003961
3962 if ((index < numArgs) &&
3963 (args[index] == String16("--latency-clear"))) {
3964 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003965 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003966 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003968
3969 if ((index < numArgs) &&
3970 (args[index] == String16("--dispsync"))) {
3971 index++;
3972 mPrimaryDispSync.dump(result);
3973 dumpAll = false;
3974 }
Dan Stozab90cf072015-03-05 11:05:59 -08003975
3976 if ((index < numArgs) &&
3977 (args[index] == String16("--static-screen"))) {
3978 index++;
3979 dumpStaticScreenStats(result);
3980 dumpAll = false;
3981 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003982
3983 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003984 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003985 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003986 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003987 dumpAll = false;
3988 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003989
3990 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3991 index++;
3992 dumpWideColorInfo(result);
3993 dumpAll = false;
3994 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003995
3996 if ((index < numArgs) &&
3997 (args[index] == String16("--enable-layer-stats"))) {
3998 index++;
3999 mLayerStats.enable();
4000 dumpAll = false;
4001 }
4002
4003 if ((index < numArgs) &&
4004 (args[index] == String16("--disable-layer-stats"))) {
4005 index++;
4006 mLayerStats.disable();
4007 dumpAll = false;
4008 }
4009
4010 if ((index < numArgs) &&
4011 (args[index] == String16("--clear-layer-stats"))) {
4012 index++;
4013 mLayerStats.clear();
4014 dumpAll = false;
4015 }
4016
4017 if ((index < numArgs) &&
4018 (args[index] == String16("--dump-layer-stats"))) {
4019 index++;
4020 mLayerStats.dump(result);
4021 dumpAll = false;
4022 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004023
4024 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4025 index++;
4026 mTimeStats.parseArgs(asProto, args, index, result);
4027 dumpAll = false;
4028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004029 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004030
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004031 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004032 if (asProto) {
4033 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4034 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4035 } else {
4036 dumpAllLocked(args, index, result);
4037 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004038 }
4039
Mathias Agopian9795c422009-08-26 16:36:26 -07004040 if (locked) {
4041 mStateLock.unlock();
4042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 }
4044 write(fd, result.string(), result.size());
4045 return NO_ERROR;
4046}
4047
Dan Stozac7014012014-02-14 15:03:43 -08004048void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4049 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004050{
Robert Carr2047fae2016-11-28 14:09:09 -08004051 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004052 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004053 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054}
4055
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004056void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004057 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004058{
4059 String8 name;
4060 if (index < args.size()) {
4061 name = String8(args[index]);
4062 index++;
4063 }
4064
David Sodman105b7dc2017-11-04 20:28:14 -07004065 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004066 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004067 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004068
4069 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004070 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004071 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004072 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004073 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004074 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004075 }
Robert Carr2047fae2016-11-28 14:09:09 -08004076 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004077 }
4078}
4079
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004080void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004081 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004082{
4083 String8 name;
4084 if (index < args.size()) {
4085 name = String8(args[index]);
4086 index++;
4087 }
4088
Robert Carr2047fae2016-11-28 14:09:09 -08004089 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004090 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004091 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004092 }
Robert Carr2047fae2016-11-28 14:09:09 -08004093 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004094
Svetoslavd85084b2014-03-20 10:28:31 -07004095 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004096}
4097
Jamie Gennis6547ff42013-07-16 20:12:42 -07004098// This should only be called from the main thread. Otherwise it would need
4099// the lock and should use mCurrentState rather than mDrawingState.
4100void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004101 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004102 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004103 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004104
4105 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4106}
4107
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004108void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004109{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004110 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004111
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004112 if (isLayerTripleBufferingDisabled())
4113 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004114
4115 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004116 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004117 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004118 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004119 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4120 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004121 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004122}
4123
Dan Stozab90cf072015-03-05 11:05:59 -08004124void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4125{
4126 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004127 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4128 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004129 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004130 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004131 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4132 b + 1, bucketTimeSec, percent);
4133 }
David Sodman4a36e932017-11-07 14:29:47 -08004134 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004135 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004136 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004137 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004138 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004139}
4140
Dan Stozae77c7662016-05-13 11:37:28 -07004141void SurfaceFlinger::recordBufferingStats(const char* layerName,
4142 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004143 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4144 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004145 for (const auto& segment : history) {
4146 if (!segment.usedThirdBuffer) {
4147 stats.twoBufferTime += segment.totalTime;
4148 }
4149 if (segment.occupancyAverage < 1.0f) {
4150 stats.doubleBufferedTime += segment.totalTime;
4151 } else if (segment.occupancyAverage < 2.0f) {
4152 stats.tripleBufferedTime += segment.totalTime;
4153 }
4154 ++stats.numSegments;
4155 stats.totalTime += segment.totalTime;
4156 }
4157}
4158
Brian Andersond6927fb2016-07-23 23:37:30 -07004159void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4160 result.appendFormat("Layer frame timestamps:\n");
4161
4162 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4163 const size_t count = currentLayers.size();
4164 for (size_t i=0 ; i<count ; i++) {
4165 currentLayers[i]->dumpFrameEvents(result);
4166 }
4167}
4168
Dan Stozae77c7662016-05-13 11:37:28 -07004169void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4170 result.append("Buffering stats:\n");
4171 result.append(" [Layer name] <Active time> <Two buffer> "
4172 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004173 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004174 typedef std::tuple<std::string, float, float, float> BufferTuple;
4175 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004176 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004177 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004178 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004179 if (stats.numSegments == 0) {
4180 continue;
4181 }
4182 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4183 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4184 stats.totalTime;
4185 float doubleBufferRatio = static_cast<float>(
4186 stats.doubleBufferedTime) / stats.totalTime;
4187 float tripleBufferRatio = static_cast<float>(
4188 stats.tripleBufferedTime) / stats.totalTime;
4189 sorted.insert({activeTime, {name, twoBufferRatio,
4190 doubleBufferRatio, tripleBufferRatio}});
4191 }
4192 for (const auto& sortedPair : sorted) {
4193 float activeTime = sortedPair.first;
4194 const BufferTuple& values = sortedPair.second;
4195 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4196 std::get<0>(values).c_str(), activeTime,
4197 std::get<1>(values), std::get<2>(values),
4198 std::get<3>(values));
4199 }
4200 result.append("\n");
4201}
4202
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004203void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4204 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004205 result.appendFormat("DisplayColorSetting: %s\n",
4206 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004207
4208 // TODO: print out if wide-color mode is active or not
4209
4210 for (size_t d = 0; d < mDisplays.size(); d++) {
4211 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4212 int32_t hwcId = displayDevice->getHwcDisplayId();
4213 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4214 continue;
4215 }
4216
4217 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004218 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004219 for (auto&& mode : modes) {
4220 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4221 }
4222
Peiyong Lina52f0292018-03-14 17:26:31 -07004223 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004224 result.appendFormat(" Current color mode: %s (%d)\n",
4225 decodeColorMode(currentMode).c_str(), currentMode);
4226 }
4227 result.append("\n");
4228}
4229
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004230LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004231 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004232 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4233 const State& state = useDrawing ? mDrawingState : mCurrentState;
4234 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004235 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004236 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004237 });
4238
4239 return layersProto;
4240}
4241
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004242LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4243 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004244 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004245
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004246 SizeProto* resolution = layersProto.mutable_resolution();
4247 resolution->set_w(displayDevice->getWidth());
4248 resolution->set_h(displayDevice->getHeight());
4249
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004250 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4251 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4252 layersProto.set_global_transform(
4253 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4254
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004255 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004256 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004257 LayerProto* layerProto = layersProto.add_layers();
4258 layer->writeToProto(layerProto, hwcId);
4259 }
4260 });
4261
4262 return layersProto;
4263}
4264
Mathias Agopian74d211a2013-04-22 16:55:35 +02004265void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4266 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 bool colorize = false;
4269 if (index < args.size()
4270 && (args[index] == String16("--color"))) {
4271 colorize = true;
4272 index++;
4273 }
4274
4275 Colorizer colorizer(colorize);
4276
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004277 // figure out if we're stuck somewhere
4278 const nsecs_t now = systemTime();
4279 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4280 const nsecs_t inTransaction(mDebugInTransaction);
4281 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4282 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4283
4284 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004285 * Dump library configuration.
4286 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287
4288 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004289 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004291 appendSfConfigString(result);
4292 appendUiConfigString(result);
4293 appendGuiConfigString(result);
4294 result.append("\n");
4295
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004296 result.append("\nWide-Color information:\n");
4297 dumpWideColorInfo(result);
4298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004300 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004302 result.append(SyncFeatures::getInstance().toString());
4303 result.append("\n");
4304
David Sodman105b7dc2017-11-04 20:28:14 -07004305 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004306
Andy McFadden41d67d72014-04-25 16:58:34 -07004307 colorizer.bold(result);
4308 result.append("DispSync configuration: ");
4309 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004310 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4311 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4312 result.appendFormat(
4313 "app phase %" PRId64 " ns, "
4314 "sf phase %" PRId64 " ns, "
4315 "early app phase %" PRId64 " ns, "
4316 "early sf phase %" PRId64 " ns, "
4317 "early app gl phase %" PRId64 " ns, "
4318 "early sf gl phase %" PRId64 " ns, "
4319 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4320 vsyncPhaseOffsetNs,
4321 sfVsyncPhaseOffsetNs,
4322 appEarlyOffset,
4323 sfEarlyOffset,
4324 appEarlyGlOffset,
4325 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004326 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004327 result.append("\n");
4328
Dan Stozab90cf072015-03-05 11:05:59 -08004329 // Dump static screen stats
4330 result.append("\n");
4331 dumpStaticScreenStats(result);
4332 result.append("\n");
4333
Dan Stozae77c7662016-05-13 11:37:28 -07004334 dumpBufferingStats(result);
4335
Andy McFadden4803b742012-09-24 19:07:20 -07004336 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337 * Dump the visible layer list
4338 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004339 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004340 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004341 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4342 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004344
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004345 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004346 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004347 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004348 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349
4350 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004351 * Dump Display state
4352 */
4353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004355 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004357 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4358 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004360 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004361 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004362
4363 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364 * Dump SurfaceFlinger global state
4365 */
4366
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004368 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004369 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370
Mathias Agopian888c8222012-08-04 21:10:38 -07004371 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004372 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004373
David Sodmanbc815282017-11-05 18:57:52 -08004374 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004375
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004376 if (hw) {
4377 hw->undefinedRegion.dump(result, "undefinedRegion");
4378 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4379 hw->getOrientation(), hw->isDisplayOn());
4380 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382 " last eglSwapBuffers() time: %f us\n"
4383 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004384 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385 " refresh-rate : %f fps\n"
4386 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004387 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004388 " gpu_to_cpu_unsupported : %d\n"
4389 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 mLastSwapBufferTime/1000.0,
4391 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004392 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004393 1e9 / activeConfig->getVsyncPeriod(),
4394 activeConfig->getDpiX(),
4395 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004396 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397
Mathias Agopian74d211a2013-04-22 16:55:35 +02004398 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400
Mathias Agopian74d211a2013-04-22 16:55:35 +02004401 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004402 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403
4404 /*
4405 * VSYNC state
4406 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004407 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004408 result.append("\n");
4409
4410 /*
4411 * HWC layer minidump
4412 */
4413 for (size_t d = 0; d < mDisplays.size(); d++) {
4414 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4415 int32_t hwcId = displayDevice->getHwcDisplayId();
4416 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4417 continue;
4418 }
4419
4420 result.appendFormat("Display %d HWC layers:\n", hwcId);
4421 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004422 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004423 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004424 });
Dan Stozae22aec72016-08-01 13:20:59 -07004425 result.append("\n");
4426 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427
4428 /*
4429 * Dump HWComposer state
4430 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004431 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004432 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004433 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004434 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004435 result.appendFormat(" h/w composer %s\n",
4436 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004437 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438
4439 /*
4440 * Dump gralloc state
4441 */
4442 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4443 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004444
4445 /*
4446 * Dump VrFlinger state if in use.
4447 */
4448 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4449 result.append("VrFlinger state:\n");
4450 result.append(mVrFlinger->Dump().c_str());
4451 result.append("\n");
4452 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004453}
4454
Mathias Agopian13127d82013-03-05 17:47:11 -08004455const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004456SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004457 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004458 wp<IBinder> dpy;
4459 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4460 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4461 dpy = mDisplays.keyAt(i);
4462 break;
4463 }
4464 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004465 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004466 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4467 // Just use the primary display so we have something to return
4468 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4469 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004470 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004471}
4472
Keun young Park63f165f2012-08-31 10:53:36 -07004473bool SurfaceFlinger::startDdmConnection()
4474{
4475 void* libddmconnection_dso =
4476 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4477 if (!libddmconnection_dso) {
4478 return false;
4479 }
4480 void (*DdmConnection_start)(const char* name);
4481 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004482 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004483 if (!DdmConnection_start) {
4484 dlclose(libddmconnection_dso);
4485 return false;
4486 }
4487 (*DdmConnection_start)(getServiceName());
4488 return true;
4489}
4490
Chia-I Wu28f320b2018-05-03 11:02:56 -07004491void SurfaceFlinger::updateColorMatrixLocked() {
4492 mat4 colorMatrix;
4493 if (mGlobalSaturationFactor != 1.0f) {
4494 // Rec.709 luma coefficients
4495 float3 luminance{0.213f, 0.715f, 0.072f};
4496 luminance *= 1.0f - mGlobalSaturationFactor;
4497 mat4 saturationMatrix = mat4(
4498 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4499 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4500 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4501 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4502 );
4503 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4504 } else {
4505 colorMatrix = mClientColorMatrix * mDaltonizer();
4506 }
4507
4508 if (mCurrentState.colorMatrix != colorMatrix) {
4509 mCurrentState.colorMatrix = colorMatrix;
4510 mCurrentState.colorMatrixChanged = true;
4511 setTransactionFlags(eTransactionNeeded);
4512 }
4513}
4514
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004515status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 switch (code) {
4517 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004518 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004520 case CLEAR_ANIMATION_FRAME_STATS:
4521 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004522 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004523 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004524 case ENABLE_VSYNC_INJECTIONS:
4525 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 {
4527 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004528 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4529 IPCThreadState* ipc = IPCThreadState::self();
4530 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4531 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004532 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004534 break;
4535 }
Robert Carr1db73f62016-12-21 12:58:51 -08004536 /*
4537 * Calling setTransactionState is safe, because you need to have been
4538 * granted a reference to Client* and Handle* to do anything with it.
4539 *
4540 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4541 */
4542 case SET_TRANSACTION_STATE:
4543 case CREATE_SCOPED_CONNECTION:
4544 {
4545 return OK;
4546 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004547 case CAPTURE_SCREEN:
4548 {
4549 // codes that require permission check
4550 IPCThreadState* ipc = IPCThreadState::self();
4551 const int pid = ipc->getCallingPid();
4552 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004553 if ((uid != AID_GRAPHICS) &&
4554 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004555 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004556 return PERMISSION_DENIED;
4557 }
4558 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 }
chaviwa76b2712017-09-20 12:02:26 -07004560 case CAPTURE_LAYERS: {
4561 IPCThreadState* ipc = IPCThreadState::self();
4562 const int pid = ipc->getCallingPid();
4563 const int uid = ipc->getCallingUid();
4564 if ((uid != AID_GRAPHICS) &&
4565 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4566 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4567 return PERMISSION_DENIED;
4568 }
4569 break;
4570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004571 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004572 return OK;
4573}
4574
4575status_t SurfaceFlinger::onTransact(
4576 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4577{
4578 status_t credentialCheck = CheckTransactCodeCredentials(code);
4579 if (credentialCheck != OK) {
4580 return credentialCheck;
4581 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004583 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4584 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004585 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004586 IPCThreadState* ipc = IPCThreadState::self();
4587 const int uid = ipc->getCallingUid();
4588 if (CC_UNLIKELY(uid != AID_SYSTEM
4589 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004590 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004591 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004592 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 return PERMISSION_DENIED;
4594 }
4595 int n;
4596 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004597 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004598 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599 return NO_ERROR;
4600 case 1002: // SHOW_UPDATES
4601 n = data.readInt32();
4602 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004603 invalidateHwcGeometry();
4604 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004607 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004609 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004610 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004611 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004612 setTransactionFlags(
4613 eTransactionNeeded|
4614 eDisplayTransactionNeeded|
4615 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004616 return NO_ERROR;
4617 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004618 case 1006:{ // send empty update
4619 signalRefresh();
4620 return NO_ERROR;
4621 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 case 1008: // toggle use of hw composer
4623 n = data.readInt32();
4624 mDebugDisableHWC = n ? 1 : 0;
4625 invalidateHwcGeometry();
4626 repaintEverything();
4627 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004628 case 1009: // toggle use of transform hint
4629 n = data.readInt32();
4630 mDebugDisableTransformHint = n ? 1 : 0;
4631 invalidateHwcGeometry();
4632 repaintEverything();
4633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004635 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636 reply->writeInt32(0);
4637 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004638 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004639 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 return NO_ERROR;
4641 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004642 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004643 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004644 return NO_ERROR;
4645 }
4646 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004647 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004648 // daltonize
4649 n = data.readInt32();
4650 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004651 case 1:
4652 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4653 break;
4654 case 2:
4655 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4656 break;
4657 case 3:
4658 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4659 break;
4660 default:
4661 mDaltonizer.setType(ColorBlindnessType::None);
4662 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004663 }
4664 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004665 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004666 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004667 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004668 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004669
4670 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004671 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004673 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004675 // apply a color matrix
4676 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004677 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004678 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004679 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004680 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004681 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004682 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004683 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004684 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004685 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004686 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004687
4688 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4689 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004690 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004691 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4692 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4693 }
4694
Chia-I Wu28f320b2018-05-03 11:02:56 -07004695 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004696 return NO_ERROR;
4697 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004698 // This is an experimental interface
4699 // Needs to be shifted to proper binder interface when we productize
4700 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004701 n = data.readInt32();
4702 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004703 return NO_ERROR;
4704 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004705 case 1017: {
4706 n = data.readInt32();
4707 mForceFullDamage = static_cast<bool>(n);
4708 return NO_ERROR;
4709 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004710 case 1018: { // Modify Choreographer's phase offset
4711 n = data.readInt32();
4712 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4713 return NO_ERROR;
4714 }
4715 case 1019: { // Modify SurfaceFlinger's phase offset
4716 n = data.readInt32();
4717 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4718 return NO_ERROR;
4719 }
Irvel468051e2016-06-13 16:44:44 -07004720 case 1020: { // Layer updates interceptor
4721 n = data.readInt32();
4722 if (n) {
4723 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004724 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004725 }
4726 else{
4727 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004728 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004729 }
4730 return NO_ERROR;
4731 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004732 case 1021: { // Disable HWC virtual displays
4733 n = data.readInt32();
4734 mUseHwcVirtualDisplays = !n;
4735 return NO_ERROR;
4736 }
Romain Guy0147a172017-06-01 13:53:56 -07004737 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004738 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004739 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004740
Chia-I Wu28f320b2018-05-03 11:02:56 -07004741 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004742 return NO_ERROR;
4743 }
Romain Guy54f154a2017-10-24 21:40:32 +01004744 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004745 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004746 invalidateHwcGeometry();
4747 repaintEverything();
4748 return NO_ERROR;
4749 }
4750 case 1024: { // Is wide color gamut rendering/color management supported?
4751 reply->writeBool(hasWideColorDisplay);
4752 return NO_ERROR;
4753 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004754 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004755 n = data.readInt32();
4756 if (n) {
4757 ALOGV("LayerTracing enabled");
4758 mTracing.enable();
4759 doTracing("tracing.enable");
4760 reply->writeInt32(NO_ERROR);
4761 } else {
4762 ALOGV("LayerTracing disabled");
4763 status_t err = mTracing.disable();
4764 reply->writeInt32(err);
4765 }
4766 return NO_ERROR;
4767 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004768 case 1026: { // Get layer tracing status
4769 reply->writeBool(mTracing.isEnabled());
4770 return NO_ERROR;
4771 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004772 // Is a DisplayColorSetting supported?
4773 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004774 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4775 if (!hw) {
4776 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004777 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004778
4779 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4780 switch (setting) {
4781 case DisplayColorSetting::MANAGED:
4782 reply->writeBool(hasWideColorDisplay);
4783 break;
4784 case DisplayColorSetting::UNMANAGED:
4785 reply->writeBool(true);
4786 break;
4787 case DisplayColorSetting::ENHANCED:
4788 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4789 break;
4790 default: // vendor display color setting
4791 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4792 break;
4793 }
4794 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 }
4797 }
4798 return err;
4799}
4800
Steven Thomas6d8110b2017-08-31 18:24:21 -07004801void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004802 android_atomic_or(1, &mRepaintEverything);
4803 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004804}
4805
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004806// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4807class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004808public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4810 ~WindowDisconnector() {
4811 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004812 }
4813
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814private:
4815 ANativeWindow* mWindow;
4816 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004817};
4818
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004819status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4820 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4821 int32_t minLayerZ, int32_t maxLayerZ,
4822 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004823 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004824 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004825
chaviwa76b2712017-09-20 12:02:26 -07004826 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4827
4828 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004829 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4830
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004831 const Rect& dispScissor = device->getScissor();
4832 if (!dispScissor.isEmpty()) {
4833 sourceCrop.set(dispScissor);
4834 // adb shell screencap will default reqWidth and reqHeight to zeros.
4835 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhang9ad73bc2018-08-21 22:11:37 -07004836 reqWidth = uint32_t(device->getViewport().width());
4837 reqHeight = uint32_t(device->getViewport().height());
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004838 }
4839 }
4840
chaviwa76b2712017-09-20 12:02:26 -07004841 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4842
4843 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4844 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004845 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004846}
4847
4848status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004849 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004850 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004851 ATRACE_CALL();
4852
4853 class LayerRenderArea : public RenderArea {
4854 public:
Robert Carr578038f2018-03-09 12:25:24 -08004855 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4856 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004857 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004858 mLayer(layer),
4859 mCrop(crop),
4860 mFlinger(flinger),
4861 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004862 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004863 Rect getBounds() const override {
4864 const Layer::State& layerState(mLayer->getDrawingState());
4865 return Rect(layerState.active.w, layerState.active.h);
4866 }
4867 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4868 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4869 bool isSecure() const override { return false; }
4870 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004871 Rect getSourceCrop() const override {
4872 if (mCrop.isEmpty()) {
4873 return getBounds();
4874 } else {
4875 return mCrop;
4876 }
4877 }
Robert Carr578038f2018-03-09 12:25:24 -08004878 class ReparentForDrawing {
4879 public:
4880 const sp<Layer>& oldParent;
4881 const sp<Layer>& newParent;
4882
4883 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4884 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004885 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004886 }
Robert Carr15eae092018-03-23 13:43:53 -07004887 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004888 };
4889
4890 void render(std::function<void()> drawLayers) override {
4891 if (!mChildrenOnly) {
4892 mTransform = mLayer->getTransform().inverse();
4893 drawLayers();
4894 } else {
4895 Rect bounds = getBounds();
4896 screenshotParentLayer =
4897 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4898 bounds.getWidth(), bounds.getHeight(), 0);
4899
4900 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4901 drawLayers();
4902 }
4903 }
chaviwa76b2712017-09-20 12:02:26 -07004904
chaviwa76b2712017-09-20 12:02:26 -07004905 private:
chaviw7206d492017-11-10 16:16:12 -08004906 const sp<Layer> mLayer;
4907 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004908
4909 // In the "childrenOnly" case we reparent the children to a screenshot
4910 // layer which has no properties set and which does not draw.
4911 sp<ContainerLayer> screenshotParentLayer;
4912 Transform mTransform;
4913
4914 SurfaceFlinger* mFlinger;
4915 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004916 };
4917
4918 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4919 auto parent = layerHandle->owner.promote();
4920
chaviw7206d492017-11-10 16:16:12 -08004921 if (parent == nullptr || parent->isPendingRemoval()) {
4922 ALOGE("captureLayers called with a removed parent");
4923 return NAME_NOT_FOUND;
4924 }
4925
Robert Carr578038f2018-03-09 12:25:24 -08004926 const int uid = IPCThreadState::self()->getCallingUid();
4927 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4928 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4929 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4930 return PERMISSION_DENIED;
4931 }
4932
chaviw7206d492017-11-10 16:16:12 -08004933 Rect crop(sourceCrop);
4934 if (sourceCrop.width() <= 0) {
4935 crop.left = 0;
4936 crop.right = parent->getCurrentState().active.w;
4937 }
4938
4939 if (sourceCrop.height() <= 0) {
4940 crop.top = 0;
4941 crop.bottom = parent->getCurrentState().active.h;
4942 }
4943
4944 int32_t reqWidth = crop.width() * frameScale;
4945 int32_t reqHeight = crop.height() * frameScale;
4946
Robert Carr578038f2018-03-09 12:25:24 -08004947 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004948
Robert Carr578038f2018-03-09 12:25:24 -08004949 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004950 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4951 if (!layer->isVisible()) {
4952 return;
Robert Carr578038f2018-03-09 12:25:24 -08004953 } else if (childrenOnly && layer == parent.get()) {
4954 return;
chaviwa76b2712017-09-20 12:02:26 -07004955 }
4956 visitor(layer);
4957 });
4958 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004959 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004960}
4961
4962status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4963 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004964 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004965 bool useIdentityTransform) {
4966 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004967
Iris Chang7501ed62018-04-30 14:45:42 +08004968 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004969
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4971 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4972 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4973 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004974
4975 // This mutex protects syncFd and captureResult for communication of the return values from the
4976 // main thread back to this Binder thread
4977 std::mutex captureMutex;
4978 std::condition_variable captureCondition;
4979 std::unique_lock<std::mutex> captureLock(captureMutex);
4980 int syncFd = -1;
4981 std::optional<status_t> captureResult;
4982
Robert Carr03480e22018-01-04 16:02:06 -08004983 const int uid = IPCThreadState::self()->getCallingUid();
4984 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4985
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004986 sp<LambdaMessage> message = new LambdaMessage([&]() {
4987 // If there is a refresh pending, bug out early and tell the binder thread to try again
4988 // after the refresh.
4989 if (mRefreshPending) {
4990 ATRACE_NAME("Skipping screenshot for now");
4991 std::unique_lock<std::mutex> captureLock(captureMutex);
4992 captureResult = std::make_optional<status_t>(EAGAIN);
4993 captureCondition.notify_one();
4994 return;
4995 }
4996
4997 status_t result = NO_ERROR;
4998 int fd = -1;
4999 {
5000 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005001 renderArea.render([&]() {
5002 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5003 useIdentityTransform, forSystem, &fd);
5004 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 }
5006
5007 {
5008 std::unique_lock<std::mutex> captureLock(captureMutex);
5009 syncFd = fd;
5010 captureResult = std::make_optional<status_t>(result);
5011 captureCondition.notify_one();
5012 }
5013 });
5014
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005015 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005016 if (result == NO_ERROR) {
5017 captureCondition.wait(captureLock, [&]() { return captureResult; });
5018 while (*captureResult == EAGAIN) {
5019 captureResult.reset();
5020 result = postMessageAsync(message);
5021 if (result != NO_ERROR) {
5022 return result;
5023 }
5024 captureCondition.wait(captureLock, [&]() { return captureResult; });
5025 }
5026 result = *captureResult;
5027 }
5028
5029 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005030 sync_wait(syncFd, -1);
5031 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005032 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005033
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005034 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005035}
5036
chaviwa76b2712017-09-20 12:02:26 -07005037void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5038 TraverseLayersFunction traverseLayers, bool yswap,
5039 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005040 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005041
Lloyd Pique144e1162017-12-20 16:44:52 -08005042 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005043
5044 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005045 const auto raWidth = renderArea.getWidth();
5046 const auto raHeight = renderArea.getHeight();
5047
5048 const auto reqWidth = renderArea.getReqWidth();
5049 const auto reqHeight = renderArea.getReqHeight();
5050 Rect sourceCrop = renderArea.getSourceCrop();
5051
Iris Chang7501ed62018-04-30 14:45:42 +08005052 bool filtering = false;
5053 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5054 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5055 static_cast<int32_t>(reqHeight) != raWidth;
5056 } else {
5057 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5058 static_cast<int32_t>(reqHeight) != raHeight;
5059 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005060
Dan Stozac1879002014-05-22 15:59:05 -07005061 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005062 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005063 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005064 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005065 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5066 Transform tr;
5067 uint32_t flags = 0x00;
5068 switch (mPrimaryDisplayOrientation) {
5069 case DisplayState::eOrientation90:
5070 flags = Transform::ROT_90;
5071 break;
5072 case DisplayState::eOrientation180:
5073 flags = Transform::ROT_180;
5074 break;
5075 case DisplayState::eOrientation270:
5076 flags = Transform::ROT_270;
5077 break;
5078 }
5079 tr.set(flags, raWidth, raHeight);
5080 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005081 }
5082
5083 // ensure that sourceCrop is inside screen
5084 if (sourceCrop.left < 0) {
5085 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5086 }
chaviwa76b2712017-09-20 12:02:26 -07005087 if (sourceCrop.right > raWidth) {
5088 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005089 }
5090 if (sourceCrop.top < 0) {
5091 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5092 }
chaviwa76b2712017-09-20 12:02:26 -07005093 if (sourceCrop.bottom > raHeight) {
5094 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005095 }
5096
Chia-I Wu36574d92018-05-16 10:54:36 -07005097 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5098 engine.setOutputDataSpace(Dataspace::SRGB);
5099 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005100
Mathias Agopian180f10d2013-04-10 22:55:41 -07005101 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005102 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005103
Iris Chang7501ed62018-04-30 14:45:42 +08005104 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5105 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5106 // convert hw orientation into flag presentation
5107 // here inverse transform needed
5108 uint8_t hw_rot_90 = 0x00;
5109 uint8_t hw_flip_hv = 0x00;
5110 switch (mPrimaryDisplayOrientation) {
5111 case DisplayState::eOrientation90:
5112 hw_rot_90 = Transform::ROT_90;
5113 hw_flip_hv = Transform::ROT_180;
5114 break;
5115 case DisplayState::eOrientation180:
5116 hw_flip_hv = Transform::ROT_180;
5117 break;
5118 case DisplayState::eOrientation270:
5119 hw_rot_90 = Transform::ROT_90;
5120 break;
5121 }
5122
5123 // transform flags operation
5124 // 1) flip H V if both have ROT_90 flag
5125 // 2) XOR these flags
5126 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5127 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5128 if (rotation_rot_90 & hw_rot_90) {
5129 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5130 }
5131 rotation = static_cast<Transform::orientation_flags>
5132 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5133 }
5134
Mathias Agopian180f10d2013-04-10 22:55:41 -07005135 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005136 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005137 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005138 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005139
chaviw50da5042018-04-09 13:49:37 -07005140 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005141 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005142 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005143
chaviwa76b2712017-09-20 12:02:26 -07005144 traverseLayers([&](Layer* layer) {
5145 if (filtering) layer->setFiltering(true);
5146 layer->draw(renderArea, useIdentityTransform);
5147 if (filtering) layer->setFiltering(false);
5148 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005149}
5150
chaviwa76b2712017-09-20 12:02:26 -07005151status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5152 TraverseLayersFunction traverseLayers,
5153 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005154 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005155 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005156 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005157 ATRACE_CALL();
5158
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005159 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005160
5161 traverseLayers([&](Layer* layer) {
5162 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5163 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005164
Robert Carr03480e22018-01-04 16:02:06 -08005165 // We allow the system server to take screenshots of secure layers for
5166 // use in situations like the Screen-rotation animation and place
5167 // the impetus on WindowManager to not persist them.
5168 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005169 ALOGW("FB is protected: PERMISSION_DENIED");
5170 return PERMISSION_DENIED;
5171 }
5172
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005173 // this binds the given EGLImage as a framebuffer for the
5174 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005175 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005176 if (bufferBond.getStatus() != NO_ERROR) {
5177 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005178 return INVALID_OPERATION;
5179 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005180
Dan Stozaabcda352017-06-01 14:37:39 -07005181 // this will in fact render into our dequeued buffer
5182 // via an FBO, which means we didn't have to create
5183 // an EGLSurface and therefore we're not
5184 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005185 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005186
Dan Stozaabcda352017-06-01 14:37:39 -07005187 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005188 getRenderEngine().finish();
5189 *outSyncFd = -1;
5190
chaviwa76b2712017-09-20 12:02:26 -07005191 const auto reqWidth = renderArea.getReqWidth();
5192 const auto reqHeight = renderArea.getReqHeight();
5193
Dan Stozaabcda352017-06-01 14:37:39 -07005194 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5195 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005196 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005197 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005198 } else {
5199 base::unique_fd syncFd = getRenderEngine().flush();
5200 if (syncFd < 0) {
5201 getRenderEngine().finish();
5202 }
5203 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005204 }
5205
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005206 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005207}
5208
Mathias Agopiand5556842013-09-19 17:08:37 -07005209void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005210 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005211 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005212 for (size_t y = 0; y < h; y++) {
5213 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5214 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005215 if (p[x] != 0xFF000000) return;
5216 }
5217 }
chaviwa76b2712017-09-20 12:02:26 -07005218 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005219
Robert Carr2047fae2016-11-28 14:09:09 -08005220 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005221 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005222 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005223 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5224 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5225 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5226 static_cast<float>(state.color.a));
5227 i++;
5228 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005229 }
5230}
5231
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005232// ---------------------------------------------------------------------------
5233
Dan Stoza412903f2017-04-27 13:42:17 -07005234void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5235 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005236}
5237
Dan Stoza412903f2017-04-27 13:42:17 -07005238void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5239 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005240}
5241
chaviwa76b2712017-09-20 12:02:26 -07005242void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5243 int32_t maxLayerZ,
5244 const LayerVector::Visitor& visitor) {
5245 // We loop through the first level of layers without traversing,
5246 // as we need to interpret min/max layer Z in the top level Z space.
5247 for (const auto& layer : mDrawingState.layersSortedByZ) {
5248 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5249 continue;
5250 }
5251 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005252 // relative layers are traversed in Layer::traverseInZOrder
5253 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005254 continue;
5255 }
5256 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005257 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5258 return;
5259 }
chaviwa76b2712017-09-20 12:02:26 -07005260 if (!layer->isVisible()) {
5261 return;
5262 }
5263 visitor(layer);
5264 });
5265 }
5266}
5267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005268}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005269
5270
5271#if defined(__gl_h_)
5272#error "don't include gl/gl.h in this file"
5273#endif
5274
5275#if defined(__gl2_h_)
5276#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005277#endif