blob: 25b4cb77f3977db251ebd6707c0e1ff5769c93d4 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
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"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070082#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070083#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070084#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070085#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
88
Mathias Agopian875d8e12013-06-07 15:35:48 -070089#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070091
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080093#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
94#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090095#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096
chaviw1d044282017-09-27 12:19:28 -070097#include <layerproto/LayerProtoParser.h>
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099#define DISPLAY_COUNT 1
100
Mathias Agopianfee2b462013-07-03 12:34:01 -0700101/*
102 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
103 * black pixels.
104 */
105#define DEBUG_SCREENSHOTS false
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
117class ConditionalLock {
118public:
119 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
120 if (lock) {
121 mMutex.lock();
122 }
123 }
124 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
125private:
126 Mutex& mMutex;
127 bool mLocked;
128};
129} // namespace anonymous
130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131// ---------------------------------------------------------------------------
132
Mathias Agopian99b49842011-06-27 16:05:52 -0700133const String16 sHardwareTest("android.permission.HARDWARE_TEST");
134const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
135const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
136const String16 sDump("android.permission.DUMP");
137
138// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800139int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
140int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700141int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700142bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800143uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800144bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800145bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800146int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800147// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600148bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700149
Kalle Raitaa099a242017-01-11 11:17:29 -0800150
151std::string getHwcServiceName() {
152 char value[PROPERTY_VALUE_MAX] = {};
153 property_get("debug.sf.hwc_service_name", value, "default");
154 ALOGI("Using HWComposer service: '%s'", value);
155 return std::string(value);
156}
157
158bool useTrebleTestingOverride() {
159 char value[PROPERTY_VALUE_MAX] = {};
160 property_get("debug.sf.treble_testing_override", value, "false");
161 ALOGI("Treble testing override: '%s'", value);
162 return std::string(value) == "true";
163}
164
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800165std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
166 switch(displayColorSetting) {
167 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800169 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700170 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800171 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700172 return std::string("Enhanced");
173 default:
174 return std::string("Unknown ") +
175 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800176 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800177}
178
Lloyd Pique99d3da52018-01-22 17:48:03 -0800179NativeWindowSurface::~NativeWindowSurface() = default;
180
181namespace impl {
182
183class NativeWindowSurface final : public android::NativeWindowSurface {
184public:
185 static std::unique_ptr<android::NativeWindowSurface> create(
186 const sp<IGraphicBufferProducer>& producer) {
187 return std::make_unique<NativeWindowSurface>(producer);
188 }
189
190 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
191 : surface(new Surface(producer, false)) {}
192
193 ~NativeWindowSurface() override = default;
194
195private:
196 sp<ANativeWindow> getNativeWindow() const override { return surface; }
197
198 void preallocateBuffers() override { surface->allocateBuffers(); }
199
200 sp<Surface> surface;
201};
202
203} // namespace impl
204
David Sodmanbc815282017-11-05 18:57:52 -0800205SurfaceFlingerBE::SurfaceFlingerBE()
206 : mHwcServiceName(getHwcServiceName()),
207 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800208 mFrameBuckets(),
209 mTotalTime(0),
210 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800211 mComposerSequenceId(0) {
212}
213
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800214SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800215 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700217 mTransactionPending(false),
218 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700219 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700220 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700221 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700223 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800225 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800226 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800227 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700229 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700230 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700231 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700232 mDebugInSwapBuffers(0),
233 mLastSwapBufferTime(0),
234 mDebugInTransaction(0),
235 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700236 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000237 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700238 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700239 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800240 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800241 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700242 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800244 mCreateBufferQueue(&BufferQueue::createBufferQueue),
245 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800246
247SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800248 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800249
250 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
251 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
252
253 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
254 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
255
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
257 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700259 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
260 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
261
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700262 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
263 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
264
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800265 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
266 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
267
Steven Thomas050b2c82017-03-06 11:45:16 -0800268 // Vr flinger is only enabled on Daydream ready devices.
269 useVrFlinger = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useVrFlinger>(false);
271
Fabien Sanglard1971b632017-03-10 14:50:03 -0800272 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
274
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600275 hasWideColorDisplay =
276 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
277
Iris Chang7501ed62018-04-30 14:45:42 +0800278 V1_1::DisplayOrientation primaryDisplayOrientation =
279 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
280 V1_1::DisplayOrientation::ORIENTATION_0);
281
282 switch (primaryDisplayOrientation) {
283 case V1_1::DisplayOrientation::ORIENTATION_90:
284 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
285 break;
286 case V1_1::DisplayOrientation::ORIENTATION_180:
287 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
288 break;
289 case V1_1::DisplayOrientation::ORIENTATION_270:
290 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
291 break;
292 default:
293 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
294 break;
295 }
296 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
297
David Sodman99974d22017-11-28 12:04:33 -0800298 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700299
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300 // debugging stuff...
301 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700302
Mathias Agopianb4b17302013-03-20 18:36:41 -0700303 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700304 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306 property_get("debug.sf.showupdates", value, "0");
307 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700309 property_get("debug.sf.ddms", value, "0");
310 mDebugDDMS = atoi(value);
311 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700312 if (!startDdmConnection()) {
313 // start failed, and DDMS debugging not enabled
314 mDebugDDMS = 0;
315 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700316 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700317 ALOGI_IF(mDebugRegion, "showupdates enabled");
318 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700319
320 property_get("debug.sf.disable_backpressure", value, "0");
321 mPropagateBackpressure = !atoi(value);
322 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700323
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800324 property_get("debug.sf.enable_hwc_vds", value, "0");
325 mUseHwcVirtualDisplays = atoi(value);
326 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800327
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800328 property_get("ro.sf.disable_triple_buffer", value, "1");
329 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800330 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700331
Yiwei Zhang243b3782018-05-15 17:40:04 -0700332 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700333 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
334 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
335
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200336 property_get("debug.sf.early_phase_offset_ns", value, "-1");
337 const int earlySfOffsetNs = atoi(value);
338
339 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
340 const int earlyGlSfOffsetNs = atoi(value);
341
342 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
343 const int earlyAppOffsetNs = atoi(value);
344
345 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
346 const int earlyGlAppOffsetNs = atoi(value);
347
348 const VSyncModulator::Offsets earlyOffsets =
349 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
350 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
351 const VSyncModulator::Offsets earlyGlOffsets =
352 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
353 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
354 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
355 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700356
Romain Guy11d63f42017-07-20 12:47:14 -0700357 // We should be reading 'persist.sys.sf.color_saturation' here
358 // but since /data may be encrypted, we need to wait until after vold
359 // comes online to attempt to read the property. The property is
360 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800361
362 if (useTrebleTestingOverride()) {
363 // Without the override SurfaceFlinger cannot connect to HIDL
364 // services that are not listed in the manifests. Considered
365 // deriving the setting from the set service name, but it
366 // would be brittle if the name that's not 'default' is used
367 // for production purposes later on.
368 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370}
371
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800372void SurfaceFlinger::onFirstRef()
373{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800374 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377SurfaceFlinger::~SurfaceFlinger()
378{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379}
380
Dan Stozac7014012014-02-14 15:03:43 -0800381void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382{
383 // the window manager died on us. prepare its eulogy.
384
Andy McFadden13a082e2012-08-24 10:16:42 -0700385 // restore initial conditions (default device unblank, etc)
386 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387
388 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700389 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390}
391
Robert Carr1db73f62016-12-21 12:58:51 -0800392static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700393 status_t err = client->initCheck();
394 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800395 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 }
Robert Carr1db73f62016-12-21 12:58:51 -0800397 return nullptr;
398}
399
400sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
401 return initClient(new Client(this));
402}
403
404sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
405 const sp<IGraphicBufferProducer>& gbp) {
406 if (authenticateSurfaceTexture(gbp) == false) {
407 return nullptr;
408 }
409 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
410 if (layer == nullptr) {
411 return nullptr;
412 }
413
414 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700417sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
418 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700419{
420 class DisplayToken : public BBinder {
421 sp<SurfaceFlinger> flinger;
422 virtual ~DisplayToken() {
423 // no more references, this display must be terminated
424 Mutex::Autolock _l(flinger->mStateLock);
425 flinger->mCurrentState.displays.removeItem(this);
426 flinger->setTransactionFlags(eDisplayTransactionNeeded);
427 }
428 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700429 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700430 : flinger(flinger) {
431 }
432 };
433
434 sp<BBinder> token = new DisplayToken(this);
435
436 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700437 DisplayDeviceState info;
438 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700439 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700440 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800442 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 return token;
444}
445
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700446void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 Mutex::Autolock _l(mStateLock);
448
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700449 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700450 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700451 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 return;
453 }
454
455 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700456 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 ALOGE("destroyDisplay called for non-virtual display");
458 return;
459 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700460 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 mCurrentState.displays.removeItemsAt(idx);
462 setTransactionFlags(eDisplayTransactionNeeded);
463}
464
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700466 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800468 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700470 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471}
472
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800473void SurfaceFlinger::bootFinished()
474{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700475 if (mStartPropertySetThread->join() != NO_ERROR) {
476 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478 const nsecs_t now = systemTime();
479 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000480 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700481
482 // wait patiently for the window manager death
483 const String16 name("window");
484 sp<IBinder> window(defaultServiceManager()->getService(name));
485 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700487 }
488
Steven Thomas050b2c82017-03-06 11:45:16 -0800489 if (mVrFlinger) {
490 mVrFlinger->OnBootFinished();
491 }
492
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700493 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700494 // formerly we would just kill the process, but we now ask it to exit so it
495 // can choose where to stop the animation.
496 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700497
498 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
499 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
500 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700501
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800502 postMessageAsync(new LambdaMessage([this] {
503 readPersistentProperties();
504 mBootStage = BootStage::FINISHED;
505 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506}
507
Dan Stoza436ccf32018-06-21 12:10:12 -0700508uint32_t SurfaceFlinger::getNewTexture() {
509 {
510 std::lock_guard lock(mTexturePoolMutex);
511 if (!mTexturePool.empty()) {
512 uint32_t name = mTexturePool.back();
513 mTexturePool.pop_back();
514 ATRACE_INT("TexturePoolSize", mTexturePool.size());
515 return name;
516 }
517
518 // The pool was too small, so increase it for the future
519 ++mTexturePoolSize;
520 }
521
522 // The pool was empty, so we need to get a new texture name directly using a
523 // blocking call to the main thread
524 uint32_t name = 0;
525 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
526 return name;
527}
528
Mathias Agopian3f844832013-08-07 21:24:32 -0700529void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700530 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700531}
532
Lloyd Piquee83f9312018-02-01 12:53:17 -0800533class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700535 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000536 const char* name) :
537 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700538 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700539 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
541 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 mDispSync(dispSync),
543 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 mVsyncMutex(),
545 mPhaseOffset(phaseOffset),
546 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700549
Lloyd Piquee83f9312018-02-01 12:53:17 -0800550 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000553 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 static_cast<DispSync::Callback*>(this));
555 if (err != NO_ERROR) {
556 ALOGE("error registering vsync callback: %s (%d)",
557 strerror(-err), err);
558 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700559 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 } else {
561 status_t err = mDispSync->removeEventListener(
562 static_cast<DispSync::Callback*>(this));
563 if (err != NO_ERROR) {
564 ALOGE("error unregistering vsync callback: %s (%d)",
565 strerror(-err), err);
566 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700567 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 }
571
Lloyd Piquee83f9312018-02-01 12:53:17 -0800572 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700573 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 mCallback = callback;
575 }
576
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 Mutex::Autolock lock(mVsyncMutex);
579
580 // Normalize phaseOffset to [0, period)
581 auto period = mDispSync->getPeriod();
582 phaseOffset %= period;
583 if (phaseOffset < 0) {
584 // If we're here, then phaseOffset is in (-period, 0). After this
585 // operation, it will be in (0, period)
586 phaseOffset += period;
587 }
588 mPhaseOffset = phaseOffset;
589
590 // If we're not enabled, we don't need to mess with the listeners
591 if (!mEnabled) {
592 return;
593 }
594
Dan Stoza84d619e2018-03-28 17:07:36 -0700595 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
596 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700598 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700599 strerror(-err), err);
600 }
601 }
602
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603private:
604 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700606 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 callback = mCallback;
609
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700610 if (mTraceVsync) {
611 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700612 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700613 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614 }
615
Peiyong Lin566a3b42018-01-09 18:22:43 -0800616 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 callback->onVSyncEvent(when);
618 }
619 }
620
Tim Murray4a4e4a22016-04-19 16:29:23 +0000621 const char* const mName;
622
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 int mValue;
624
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700625 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700626 const String8 mVsyncOnLabel;
627 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700628
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700630
631 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800632 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633
634 Mutex mVsyncMutex; // Protects the following
635 nsecs_t mPhaseOffset;
636 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637};
638
Lloyd Piquee83f9312018-02-01 12:53:17 -0800639class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700640public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800641 InjectVSyncSource() = default;
642 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700643
Lloyd Piquee83f9312018-02-01 12:53:17 -0800644 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700645 std::lock_guard<std::mutex> lock(mCallbackMutex);
646 mCallback = callback;
647 }
648
Lloyd Piquee83f9312018-02-01 12:53:17 -0800649 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700650 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700651 if (mCallback) {
652 mCallback->onVSyncEvent(when);
653 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654 }
655
Lloyd Piquee83f9312018-02-01 12:53:17 -0800656 void setVSyncEnabled(bool) override {}
657 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700658
659private:
660 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800661 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700662};
663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664// Do not call property_set on main thread which will be blocked by init
665// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700666void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700667 ALOGI( "SurfaceFlinger's main thread ready to run. "
668 "Initializing graphics H/W...");
669
Thierry Strudel2924d012017-08-14 15:19:37 -0700670 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900671
Steven Thomasb02664d2017-07-26 18:48:28 -0700672 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800675 mEventThreadSource =
676 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
677 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800678 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800680 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800681 "appEventThread");
682 mSfEventThreadSource =
683 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
684 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800685
Lloyd Pique24b0a482018-03-09 18:52:26 -0800686 mSFEventThread =
687 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800689 [this](nsecs_t timestamp) {
690 mInterceptor->saveVSyncEvent(timestamp);
691 },
692 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800693 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200694 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695
Steven Thomasb02664d2017-07-26 18:48:28 -0700696 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800697 getBE().mRenderEngine =
698 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
699 hasWideColorDisplay
700 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
701 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800702 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700703
704 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
705 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800706 getBE().mHwc.reset(
707 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700708 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800709 // Process any initial hotplug and resulting display changes.
710 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700711 const auto display = getDefaultDisplayDeviceLocked();
712 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
713 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
714 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800715
Lloyd Piquefcd86612017-12-14 17:15:36 -0800716 // make the default display GLContext current so that we can create textures
717 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700718 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800719
Steven Thomas050b2c82017-03-06 11:45:16 -0800720 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700721 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700722 // This callback is called from the vr flinger dispatch thread. We
723 // need to call signalTransaction(), which requires holding
724 // mStateLock when we're not on the main thread. Acquiring
725 // mStateLock from the vr flinger dispatch thread might trigger a
726 // deadlock in surface flinger (see b/66916578), so post a message
727 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700728 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700729 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
730 mVrFlingerRequestsDisplay = requestDisplay;
731 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700732 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800733 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700734 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
735 getHwComposer()
736 .getHwcDisplayId(display->getId())
737 .value_or(0),
738 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 if (!mVrFlinger) {
740 ALOGE("Failed to start vrflinger");
741 }
742 }
743
Lloyd Pique379adc12018-01-22 17:31:47 -0800744 mEventControlThread = std::make_unique<impl::EventControlThread>(
745 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700746
Mathias Agopian92a979a2012-08-02 18:32:23 -0700747 // initialize our drawing state
748 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700749
Andy McFadden13a082e2012-08-24 10:16:42 -0700750 // set initial conditions (e.g. unblank default device)
751 initializeDisplays();
752
David Sodmanbc815282017-11-05 18:57:52 -0800753 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700754
Wei Wangf9b05ee2017-07-19 20:59:39 -0700755 // Inform native graphics APIs whether the present timestamp is supported:
756 if (getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 mStartPropertySetThread = new StartPropertySetThread(false);
759 } else {
760 mStartPropertySetThread = new StartPropertySetThread(true);
761 }
762
763 if (mStartPropertySetThread->Start() != NO_ERROR) {
764 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800766
Chia-I Wud49d6692018-06-27 07:17:41 +0800767 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
768 // is used to saturate legacy sRGB content. However, to make sure the same color under
769 // Display P3 will be saturated to the same color, we intentionally break the API spec
770 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
771 // such saturation matrix on Display P3 is understood fully, the API should always return
772 // identify matrix.
773 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
774 Dataspace::SRGB_LINEAR);
775
776 // we will apply this on Display P3.
777 if (mEnhancedSaturationMatrix != mat4()) {
778 ColorSpace srgb(ColorSpace::sRGB());
779 ColorSpace displayP3(ColorSpace::DisplayP3());
780 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
781 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
782 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
783 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700786}
787
Romain Guy11d63f42017-07-20 12:47:14 -0700788void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700789 Mutex::Autolock _l(mStateLock);
790
Romain Guy11d63f42017-07-20 12:47:14 -0700791 char value[PROPERTY_VALUE_MAX];
792
793 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800794 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800796 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100797
798 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700799 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700800}
801
Mathias Agopiana67e4182012-06-19 17:26:12 -0700802void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800803 // Start boot animation service by setting a property mailbox
804 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700805 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800806 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700807 if (mStartPropertySetThread->join() != NO_ERROR) {
808 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800809 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700810}
811
Mathias Agopian875d8e12013-06-07 15:35:48 -0700812size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800813 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700814}
815
Mathias Agopian875d8e12013-06-07 15:35:48 -0700816size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800817 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700818}
819
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800821
Jamie Gennis582270d2011-08-17 18:19:00 -0700822bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800823 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800824 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800825 return authenticateSurfaceTextureLocked(bufferProducer);
826}
827
828bool SurfaceFlinger::authenticateSurfaceTextureLocked(
829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800830 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800831 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800832}
833
Brian Anderson6b376712017-04-04 10:51:39 -0700834status_t SurfaceFlinger::getSupportedFrameTimestamps(
835 std::vector<FrameEvent>* outSupported) const {
836 *outSupported = {
837 FrameEvent::REQUESTED_PRESENT,
838 FrameEvent::ACQUIRE,
839 FrameEvent::LATCH,
840 FrameEvent::FIRST_REFRESH_START,
841 FrameEvent::LAST_REFRESH_START,
842 FrameEvent::GPU_COMPOSITION_DONE,
843 FrameEvent::DEQUEUE_READY,
844 FrameEvent::RELEASE,
845 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700848 if (!getHwComposer().hasCapability(
849 HWC2::Capability::PresentFenceIsNotReliable)) {
850 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
851 }
852 return NO_ERROR;
853}
854
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
856 Vector<DisplayInfo>* configs) {
857 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 return BAD_VALUE;
859 }
860
Jesse Hall692c7232012-11-08 15:41:56 -0800861 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700862 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
863 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700864 type = i;
865 break;
866 }
867 }
868
869 if (type < 0) {
870 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700871 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700872
Mathias Agopian8b736f12012-08-13 17:54:26 -0700873 // TODO: Not sure if display density should handled by SF any longer
874 class Density {
875 static int getDensityFromProperty(char const* propName) {
876 char property[PROPERTY_VALUE_MAX];
877 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800878 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700879 density = atoi(property);
880 }
881 return density;
882 }
883 public:
884 static int getEmuDensity() {
885 return getDensityFromProperty("qemu.sf.lcd_density"); }
886 static int getBuildDensity() {
887 return getDensityFromProperty("ro.sf.lcd_density"); }
888 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700891
Steven Thomas6d8110b2017-08-31 18:24:21 -0700892 ConditionalLock _l(mStateLock,
893 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 DisplayInfo info = DisplayInfo();
896
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 float xdpi = hwConfig->getDpiX();
898 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
900 if (type == DisplayDevice::DISPLAY_PRIMARY) {
901 // The density of the device is provided by a build property
902 float density = Density::getBuildDensity() / 160.0f;
903 if (density == 0) {
904 // the build doesn't provide a density -- this is wrong!
905 // use xdpi instead
906 ALOGE("ro.sf.lcd_density must be defined as a build property");
907 density = xdpi / 160.0f;
908 }
909 if (Density::getEmuDensity()) {
910 // if "qemu.sf.lcd_density" is specified, it overrides everything
911 xdpi = ydpi = density = Density::getEmuDensity();
912 density /= 160.0f;
913 }
914 info.density = density;
915
916 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917 const auto display = getDefaultDisplayDeviceLocked();
918 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 } else {
920 // TODO: where should this value come from?
921 static const int TV_DENSITY = 213;
922 info.density = TV_DENSITY / 160.0f;
923 info.orientation = 0;
924 }
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.w = hwConfig->getWidth();
927 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 info.xdpi = xdpi;
929 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800930 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900931 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932
Andy McFadden91b2ca82014-06-13 14:04:23 -0700933 // This is how far in advance a buffer must be queued for
934 // presentation at a given time. If you want a buffer to appear
935 // on the screen at time N, you must submit the buffer before
936 // (N - presentationDeadline).
937 //
938 // Normally it's one full refresh period (to give SF a chance to
939 // latch the buffer), but this can be reduced by configuring a
940 // DispSync offset. Any additional delays introduced by the hardware
941 // composer or panel must be accounted for here.
942 //
943 // We add an additional 1ms to allow for processing time and
944 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800945 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800946 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947
948 // All non-virtual displays are currently considered secure.
949 info.secure = true;
950
Iris Chang7501ed62018-04-30 14:45:42 +0800951 if (type == DisplayDevice::DISPLAY_PRIMARY &&
952 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
953 std::swap(info.w, info.h);
954 }
955
Michael Wright28f24d02016-07-12 13:30:53 -0700956 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700957 }
958
Dan Stoza7f7da322014-05-02 15:26:25 -0700959 return NO_ERROR;
960}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
963 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700964 return BAD_VALUE;
965 }
966
967 // FIXME for now we always return stats for the primary display
968 memset(stats, 0, sizeof(*stats));
969 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
970 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
971 return NO_ERROR;
972}
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800978 return BAD_VALUE;
979 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700980
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700982}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700983
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700984void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
985 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987 return;
988 }
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700991 ALOGW("Trying to set config for virtual display");
992 return;
993 }
994
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700995 display->setActiveConfig(mode);
996 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997}
998
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001000 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 Vector<DisplayInfo> configs;
1002 getDisplayConfigs(displayToken, &configs);
1003 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1004 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1005 configs.size());
1006 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001007 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008 const auto display = getDisplayDevice(displayToken);
1009 if (!display) {
1010 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1011 displayToken.get());
1012 } else if (display->isVirtual()) {
1013 ALOGW("Attempt to set active config %d for virtual display", mode);
1014 } else {
1015 setActiveConfigInternal(display, mode);
1016 }
1017 }));
1018
Mathias Agopian888c8222012-08-04 21:10:38 -07001019 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001020}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1022 Vector<ColorMode>* outColorModes) {
1023 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001024 return BAD_VALUE;
1025 }
1026
Michael Wright28f24d02016-07-12 13:30:53 -07001027 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1029 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001030 type = i;
1031 break;
1032 }
1033 }
1034
1035 if (type < 0) {
1036 return type;
1037 }
1038
Peiyong Lina52f0292018-03-14 17:26:31 -07001039 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001040 {
1041 ConditionalLock _l(mStateLock,
1042 std::this_thread::get_id() != mMainThreadId);
1043 modes = getHwComposer().getColorModes(type);
1044 }
Michael Wright28f24d02016-07-12 13:30:53 -07001045 outColorModes->clear();
1046 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1047
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
1053 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1059 Dataspace dataSpace, RenderIntent renderIntent) {
1060 ColorMode currentMode = display->getActiveColorMode();
1061 Dataspace currentDataSpace = display->getCompositionDataSpace();
1062 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001063
Peiyong Lin38e9a562018-04-10 16:24:20 -07001064 if (mode == currentMode && dataSpace == currentDataSpace &&
1065 renderIntent == currentRenderIntent) {
1066 return;
1067 }
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001070 ALOGW("Trying to set config for virtual display");
1071 return;
1072 }
1073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001074 display->setActiveColorMode(mode);
1075 display->setCompositionDataSpace(dataSpace);
1076 display->setActiveRenderIntent(renderIntent);
1077 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001078
1079 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1081 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001085 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 Vector<ColorMode> modes;
1087 getDisplayColorModes(displayToken, &modes);
1088 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1089 if (mode < ColorMode::NATIVE || !exists) {
1090 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1091 decodeColorMode(mode).c_str(), mode, displayToken.get());
1092 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDevice(displayToken);
1095 if (!display) {
1096 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1097 decodeColorMode(mode).c_str(), mode, displayToken.get());
1098 } else if (display->isVirtual()) {
1099 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1100 decodeColorMode(mode).c_str(), mode);
1101 } else {
1102 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1103 RenderIntent::COLORIMETRIC);
1104 }
1105 }));
1106
Michael Wright28f24d02016-07-12 13:30:53 -07001107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1123 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001124 Mutex::Autolock _l(mStateLock);
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDeviceLocked(displayToken);
1127 if (!display) {
1128 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
1152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001156 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001157 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001158 impl::EventThread::InterceptVSyncsCallback(),
1159 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 } else {
1163 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001164 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 }
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001168 }));
1169
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001170 return NO_ERROR;
1171}
1172
1173status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
1175
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 if (!mInjectVSyncs) {
1177 ALOGE("VSync Injections not enabled");
1178 return BAD_VALUE;
1179 }
1180 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1181 ALOGV("Injecting VSync inside SurfaceFlinger");
1182 mVSyncInjector->onInjectSyncEvent(when);
1183 }
1184 return NO_ERROR;
1185}
1186
Lloyd Pique755e3192018-01-31 16:46:15 -08001187status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1188 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001189 IPCThreadState* ipc = IPCThreadState::self();
1190 const int pid = ipc->getCallingPid();
1191 const int uid = ipc->getCallingUid();
1192 if ((uid != AID_SHELL) &&
1193 !PermissionCache::checkPermission(sDump, pid, uid)) {
1194 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1195 return PERMISSION_DENIED;
1196 }
1197
1198 // Try to acquire a lock for 1s, fail gracefully
1199 const status_t err = mStateLock.timedLock(s2ns(1));
1200 const bool locked = (err == NO_ERROR);
1201 if (!locked) {
1202 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1203 return TIMED_OUT;
1204 }
1205
1206 outLayers->clear();
1207 mCurrentState.traverseInZOrder([&](Layer* layer) {
1208 outLayers->push_back(layer->getLayerDebugInfo());
1209 });
1210
1211 mStateLock.unlock();
1212 return NO_ERROR;
1213}
1214
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001215// ----------------------------------------------------------------------------
1216
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001217sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1218 ISurfaceComposer::VsyncSource vsyncSource) {
1219 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1220 return mSFEventThread->createEventConnection();
1221 } else {
1222 return mEventThread->createEventConnection();
1223 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001224}
1225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001226// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227
1228void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001229 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001237 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001238}
1239
1240void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001241 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001242 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001243}
1244
1245status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001246 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001247 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001248}
1249
1250status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001251 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001252 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253 if (res == NO_ERROR) {
1254 msg->wait();
1255 }
1256 return res;
1257}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001260 do {
1261 waitForEvent();
1262 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263}
1264
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265void SurfaceFlinger::enableHardwareVsync() {
1266 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001269 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001271 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272}
1273
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 Mutex::Autolock _l(mHWVsyncLock);
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277 if (makeAvailable) {
1278 mHWVsyncAvailable = true;
1279 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001280 // Hardware vsync is not currently available, so abort the resync
1281 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 return;
1283 }
1284
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001285 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1286 if (!getHwComposer().isConnected(displayId)) {
1287 return;
1288 }
1289
1290 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001291 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292
1293 mPrimaryDispSync.reset();
1294 mPrimaryDispSync.setPeriod(period);
1295
1296 if (!mPrimaryHWVsyncEnabled) {
1297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryHWVsyncEnabled = true;
1300 }
1301}
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 Mutex::Autolock _l(mHWVsyncLock);
1305 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001306 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 mPrimaryDispSync.endResync();
1308 mPrimaryHWVsyncEnabled = false;
1309 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 if (makeUnavailable) {
1311 mHWVsyncAvailable = false;
1312 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313}
1314
Tim Murray4a4e4a22016-04-19 16:29:23 +00001315void SurfaceFlinger::resyncWithRateLimit() {
1316 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001317
1318 // No explicit locking is needed here since EventThread holds a lock while calling this method
1319 static nsecs_t sLastResyncAttempted = 0;
1320 const nsecs_t now = systemTime();
1321 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001322 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001323 }
Dan Stoza57164302017-05-08 14:03:54 -07001324 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001325}
1326
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001327void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1328 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001329 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001331 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 return;
1333 }
1334
1335 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001336 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 return;
1338 }
1339
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 { // Scope for the lock
1343 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001345 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001347 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001348
1349 if (needsHwVsync) {
1350 enableHardwareVsync();
1351 } else {
1352 disableHardwareVsync(false);
1353 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001354}
1355
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001356void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001357 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1358 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001359}
1360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001362 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001363 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001364 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
Lloyd Piqueba04e622017-12-14 17:11:26 -08001366 // Ignore events that do not have the right sequenceId.
1367 if (sequenceId != getBE().mComposerSequenceId) {
1368 return;
1369 }
1370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 // Only lock if we're not on the main thread. This function is normally
1372 // called on a hwbinder thread, but for the primary display it's called on
1373 // the main thread with the state lock already held, so don't attempt to
1374 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001375 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001377 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001378
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001379 if (std::this_thread::get_id() == mMainThreadId) {
1380 // Process all pending hot plug events immediately if we are on the main thread.
1381 processDisplayHotplugEventsLocked();
1382 }
1383
Lloyd Piqueba04e622017-12-14 17:11:26 -08001384 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001385}
1386
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001387void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001391 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001392 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001393}
1394
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 getHwComposer().setVsyncEnabled(disp,
1399 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001400}
1401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001403void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405 // Clear the drawing state so that the logic inside of
1406 // handleTransactionLocked will fire. It will determine the delta between
1407 // mCurrentState and mDrawingState and re-apply all changes when we make the
1408 // transition.
1409 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001410 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411 mDisplays.clear();
1412}
1413
Steven Thomas050b2c82017-03-06 11:45:16 -08001414void SurfaceFlinger::updateVrFlinger() {
1415 if (!mVrFlinger)
1416 return;
1417 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 return;
1420 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 ALOGE("Vr flinger is only supported for remote hardware composer"
1424 " service connections. Ignoring request to transition to vr"
1425 " flinger.");
1426 mVrFlingerRequestsDisplay = false;
1427 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001428 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomas0123ac62018-07-12 11:32:34 -07001432 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001433 LOG_ALWAYS_FATAL_IF(!display);
1434 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001435 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1436 // called below. Clear the reference now so we don't accidentally use it
1437 // later.
1438 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001445 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001446 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1447 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001448 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449
David Sodman105b7dc2017-11-04 20:28:14 -07001450 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1451 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001452
1453 if (vrFlingerRequestsDisplay) {
1454 mVrFlinger->GrantDisplayOwnership();
1455 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
1459 mVisibleRegionsDirty = true;
1460 invalidateHwcGeometry();
1461
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001463 display = getDefaultDisplayDeviceLocked();
1464 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001465 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001468 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 const nsecs_t period = activeConfig->getVsyncPeriod();
1470 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 // Use phase of 0 since phase is not known.
1473 // Use latency of 0, which will snap to the ideal latency.
1474 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001475
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001476 android_atomic_or(1, &mRepaintEverything);
1477 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478}
1479
Mathias Agopian4fec8732012-06-29 14:12:52 -07001480void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001481 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001482 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001484 bool frameMissed = !mHadClientComposition &&
1485 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486 (mPreviousPresentFence->getSignalTime() ==
1487 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001488 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001489 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001490 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001491 mTimeStats.incrementMissedFrames();
1492 if (mPropagateBackpressure) {
1493 signalLayerUpdate();
1494 break;
1495 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001496 }
Dan Stoza50182882016-07-08 12:02:20 -07001497
Steven Thomas050b2c82017-03-06 11:45:16 -08001498 // Now that we're going to make it to the handleMessageTransaction()
1499 // call below it's safe to call updateVrFlinger(), which will
1500 // potentially trigger a display handoff.
1501 updateVrFlinger();
1502
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 bool refreshNeeded = handleMessageTransaction();
1504 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001505 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001506 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001507 // Signal a refresh if a transaction modified the window state,
1508 // a new buffer was latched, or if HWC has requested a full
1509 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 signalRefresh();
1511 }
1512 break;
1513 }
1514 case MessageQueue::REFRESH: {
1515 handleMessageRefresh();
1516 break;
1517 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001518 }
1519}
1520
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001522 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001524 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001528}
1529
Dan Stoza6b9454d2014-11-07 16:00:59 -08001530bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001532 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001533}
1534
1535void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001537
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001538 mRefreshPending = false;
1539
Chia-I Wu30505fb2018-03-26 16:20:31 -07001540 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001541
Chia-I Wu30505fb2018-03-26 16:20:31 -07001542 preComposition(refreshStartTime);
1543 rebuildLayerStacks();
1544 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001545 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001546 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001547 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001548 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001549 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001550
Dan Stozabfbffeb2016-07-21 14:49:33 -07001551 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001552 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001554 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001555 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001556 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001557
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001560
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561void SurfaceFlinger::doDebugFlashRegions()
1562{
1563 // is debugging enabled
1564 if (CC_LIKELY(!mDebugRegion))
1565 return;
1566
1567 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001568 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001569 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001571 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 if (!dirtyRegion.isEmpty()) {
1573 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001574 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575
1576 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001577 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001578 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001579 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001581 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 }
1583 }
1584 }
1585
1586 postFramebuffer();
1587
1588 if (mDebugRegion > 1) {
1589 usleep(mDebugRegion * 1000);
1590 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001591
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001592 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001593 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001594 continue;
1595 }
1596
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001597 status_t result = display->prepareFrame(*getBE().mHwc);
1598 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001599 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001600 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601}
1602
Adrian Roos1e1a1282017-11-01 19:05:31 +01001603void SurfaceFlinger::doTracing(const char* where) {
1604 ATRACE_CALL();
1605 ATRACE_NAME(where);
1606 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001607 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001608 }
1609}
1610
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001611void SurfaceFlinger::logLayerStats() {
1612 ATRACE_CALL();
1613 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 if (display->isPrimary()) {
1616 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001617 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001618 }
1619 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001620
1621 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001622 }
1623}
1624
Chia-I Wu30505fb2018-03-26 16:20:31 -07001625void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 ATRACE_CALL();
1628 ALOGV("preComposition");
1629
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001631 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001632 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633 needExtraInvalidate = true;
1634 }
Robert Carr2047fae2016-11-28 14:09:09 -08001635 });
1636
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637 if (needExtraInvalidate) {
1638 signalLayerUpdate();
1639 }
1640}
1641
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642void SurfaceFlinger::updateCompositorTiming(
1643 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1644 std::shared_ptr<FenceTime>& presentFenceTime) {
1645 // Update queue of past composite+present times and determine the
1646 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001647 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001649 while (!getBE().mCompositePresentTimes.empty()) {
1650 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 // Cached values should have been updated before calling this method,
1652 // which helps avoid duplicate syscalls.
1653 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1654 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1655 break;
1656 }
1657 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001658 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 }
1660
1661 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001662 while (getBE().mCompositePresentTimes.size() > 16) {
1663 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 }
1665
Brian Andersond0010582017-03-07 13:20:31 -08001666 setCompositorTimingSnapped(
1667 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1668}
1669
1670void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1671 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 // Integer division and modulo round toward 0 not -inf, so we need to
1673 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001674 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1676 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1677
Brian Andersond0010582017-03-07 13:20:31 -08001678 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1679 if (idealLatency <= 0) {
1680 idealLatency = vsyncInterval;
1681 }
1682
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 // Snap the latency to a value that removes scheduling jitter from the
1684 // composition and present times, which often have >1ms of jitter.
1685 // Reducing jitter is important if an app attempts to extrapolate
1686 // something (such as user input) to an accurate diasplay time.
1687 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1688 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001689 nsecs_t bias = vsyncInterval / 2;
1690 int64_t extraVsyncs =
1691 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1692 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1693 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694
David Sodman99974d22017-11-28 12:04:33 -08001695 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1696 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1697 getBE().mCompositorTiming.interval = vsyncInterval;
1698 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001699}
1700
Chia-I Wu30505fb2018-03-26 16:20:31 -07001701void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001703 ATRACE_CALL();
1704 ALOGV("postComposition");
1705
Brian Anderson3546a3f2016-07-14 11:51:14 -07001706 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001707 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001708 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001709 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001710 }
1711
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001712 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001713 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714
David Sodman73beded2017-11-15 11:56:06 -08001715 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001717 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001719 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 } else {
1722 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1723 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001726 mPreviousPresentFence =
1727 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1728 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001729 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001730
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1732 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1733
Chia-I Wu30505fb2018-03-26 16:20:31 -07001734 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735 // when we started doing work for this frame, but that should be okay
1736 // since updateCompositorTiming has snapping logic.
1737 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001738 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001739 CompositorTiming compositorTiming;
1740 {
David Sodman99974d22017-11-28 12:04:33 -08001741 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1742 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001743 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744
Robert Carr2047fae2016-11-28 14:09:09 -08001745 mDrawingState.traverseInZOrder([&](Layer* layer) {
1746 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001747 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001748 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001749 recordBufferingStats(layer->getName().string(),
1750 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001751 }
Robert Carr2047fae2016-11-28 14:09:09 -08001752 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001753
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001754 if (presentFenceTime->isValid()) {
1755 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001756 enableHardwareVsync();
1757 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001758 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001759 }
1760 }
1761
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001762 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001764 enableHardwareVsync();
1765 }
1766 }
1767
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001768 if (mAnimCompositionPending) {
1769 mAnimCompositionPending = false;
1770
Brian Anderson4e606e32017-03-16 15:34:57 -07001771 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001773 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001774 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 // The HWC doesn't support present fences, so use the refresh
1776 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001777 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001778 mAnimFrameTracker.setActualPresentTime(presentTime);
1779 }
1780 mAnimFrameTracker.advanceFrame();
1781 }
Dan Stozab90cf072015-03-05 11:05:59 -08001782
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001783 mTimeStats.incrementTotalFrames();
1784 if (mHadClientComposition) {
1785 mTimeStats.incrementClientCompositionFrames();
1786 }
1787
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001788 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001789 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001790 return;
1791 }
1792
1793 nsecs_t currentTime = systemTime();
1794 if (mHasPoweredOff) {
1795 mHasPoweredOff = false;
1796 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001797 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001798 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001799 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1800 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001801 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001802 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001803 }
David Sodman4a36e932017-11-07 14:29:47 -08001804 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001805 }
David Sodman4a36e932017-11-07 14:29:47 -08001806 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001807
1808 {
1809 std::lock_guard lock(mTexturePoolMutex);
1810 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1811 if (refillCount > 0) {
1812 const size_t offset = mTexturePool.size();
1813 mTexturePool.resize(mTexturePoolSize);
1814 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1815 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1816 }
1817 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818}
1819
1820void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821 ATRACE_CALL();
1822 ALOGV("rebuildLayerStacks");
1823
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001826 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 mVisibleRegionsDirty = false;
1828 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001829
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001830 for (const auto& pair : mDisplays) {
1831 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 Region opaqueRegion;
1833 Region dirtyRegion;
1834 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001835 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001836 const Transform& tr = display->getTransform();
1837 const Rect bounds = display->getBounds();
1838 if (display->isPoweredOn()) {
1839 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001840
Jeff Sharkey76488112017-02-27 14:15:18 -07001841 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001842 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001843 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001844 Region drawRegion(tr.transform(
1845 layer->visibleNonTransparentRegion));
1846 drawRegion.andSelf(bounds);
1847 if (!drawRegion.isEmpty()) {
1848 layersSortedByZ.add(layer);
1849 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001850 // Clear out the HWC layer if this layer was
1851 // previously visible, but no longer is
Dominik Laskowski7e045462018-05-30 13:02:02 -07001852 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001853 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001854 } else {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001855 // WM changes display->layerStack upon sleep/awake.
Chia-I Wu30505fb2018-03-26 16:20:31 -07001856 // Here we make sure we delete the HWC layers even if
1857 // WM changed their layer stack.
Dominik Laskowski7e045462018-05-30 13:02:02 -07001858 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001859 }
1860
1861 // If a layer is not going to get a release fence because
1862 // it is invisible, but it is also going to release its
1863 // old buffer, add it to the list of layers needing
1864 // fences.
1865 if (hwcLayerDestroyed) {
1866 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1867 mLayersWithQueuedFrames.cend(), layer);
1868 if (found != mLayersWithQueuedFrames.cend()) {
1869 layersNeedingFences.add(layer);
1870 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001871 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001872 });
1873 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 display->setVisibleLayersSortedByZ(layersSortedByZ);
1875 display->setLayersNeedingFences(layersNeedingFences);
1876 display->undefinedRegion.set(bounds);
1877 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1878 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001879 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001880 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001882
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001883// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001885// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001887// The returned HDR data space is one of
1888// - Dataspace::UNKNOWN
1889// - Dataspace::BT2020_HLG
1890// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001891Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1892 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001893 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001894 *outHdrDataSpace = Dataspace::UNKNOWN;
1895
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001897 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 case Dataspace::V0_SCRGB:
1899 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001900 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001901 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001902 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 case Dataspace::BT2020_PQ:
1904 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001905 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001907 case Dataspace::BT2020_HLG:
1908 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001909 // When there's mixed PQ content and HLG content, we set the HDR
1910 // data space to be BT2020_PQ and convert HLG to PQ.
1911 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1912 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001913 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914 break;
1915 default:
1916 break;
1917 }
Romain Guy54f154a2017-10-24 21:40:32 +01001918 }
1919
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001920 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001921}
1922
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001923// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1925 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1927 *outMode = ColorMode::NATIVE;
1928 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001931 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001932
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001935
Peiyong Lindfde5112018-06-05 10:58:41 -07001936 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001937 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001938 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001939 if (isHdr) {
1940 bestDataSpace = hdrDataSpace;
1941 }
1942
Chia-I Wu0d711262018-05-21 15:19:35 -07001943 RenderIntent intent;
1944 switch (mDisplayColorSetting) {
1945 case DisplayColorSetting::MANAGED:
1946 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001947 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001948 break;
1949 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001950 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001951 break;
1952 default: // vendor display color setting
1953 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1954 break;
1955 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001956
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001957 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958}
1959
Chia-I Wu30505fb2018-03-26 16:20:31 -07001960void SurfaceFlinger::setUpHWComposer() {
1961 ATRACE_CALL();
1962 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001964 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1966 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1967 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07001968
1969 // If nothing has changed (!dirty), don't recompose.
1970 // If something changed, but we don't currently have any visible layers,
1971 // and didn't when we last did a composition, then skip it this time.
1972 // The second rule does two things:
1973 // - When all layers are removed from a display, we'll emit one black
1974 // frame, then nothing more until we get new layers.
1975 // - When a display is created with a private layer stack, we won't
1976 // emit any black frames until a layer is added to the layer stack.
1977 bool mustRecompose = dirty && !(empty && wasEmpty);
1978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001979 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001980 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1981 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07001982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001983 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001984
1985 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001986 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07001987 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001988 }
1989
Chia-I Wu30505fb2018-03-26 16:20:31 -07001990 // build the h/w work list
1991 if (CC_UNLIKELY(mGeometryInvalid)) {
1992 mGeometryInvalid = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07001994 const auto displayId = display->getId();
1995 if (displayId >= 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001996 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001997 for (size_t i = 0; i < currentLayers.size(); i++) {
1998 const auto& layer = currentLayers[i];
Dominik Laskowski7e045462018-05-30 13:02:02 -07001999 if (!layer->hasHwcLayer(displayId)) {
2000 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2001 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002002 continue;
2003 }
2004 }
2005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 layer->setGeometry(display, i);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002007 if (mDebugDisableHWC || mDebugRegion) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002008 layer->forceClientComposition(displayId);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002009 }
2010 }
2011 }
2012 }
2013 }
2014
Chia-I Wu30505fb2018-03-26 16:20:31 -07002015 // Set the per-frame data
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002016 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002017 const auto displayId = display->getId();
2018 if (displayId < 0) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002019 continue;
2020 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002021
Chia-I Wu28f320b2018-05-03 11:02:56 -07002022 if (mDrawingState.colorMatrixChanged) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002024 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002026 displayId, result);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002027 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu692e0832018-06-05 15:46:58 -07002029 if (layer->isHdrY410()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002030 layer->forceClientComposition(displayId);
Chia-I Wu692e0832018-06-05 15:46:58 -07002031 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2032 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2033 !display->hasHDR10Support()) {
2034 layer->forceClientComposition(displayId);
2035 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2036 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2037 !display->hasHLGSupport()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002038 layer->forceClientComposition(displayId);
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002040
Dominik Laskowski7e045462018-05-30 13:02:02 -07002041 if (layer->getForceClientComposition(displayId)) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002042 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002043 layer->setCompositionType(displayId, HWC2::Composition::Client);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002044 continue;
2045 }
2046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 layer->setPerFrameData(display);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002048 }
2049
2050 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002051 ColorMode colorMode;
2052 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002053 RenderIntent renderIntent;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2055 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002056 }
2057 }
2058
Chia-I Wu28f320b2018-05-03 11:02:56 -07002059 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002060
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002061 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002062 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002063 continue;
2064 }
2065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002066 status_t result = display->prepareFrame(*getBE().mHwc);
2067 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002068 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002070}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002071
Mathias Agopiancd60f992012-08-16 16:28:27 -07002072void SurfaceFlinger::doComposition() {
2073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ALOGV("doComposition");
2075
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002077 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002078 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002079 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002081
2082 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002085 display->dirtyRegion.clear();
2086 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002087 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002088 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002089 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002090}
2091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002092void SurfaceFlinger::postFramebuffer()
2093{
Mathias Agopian841cde52012-03-01 15:44:37 -08002094 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002096
Mathias Agopiana44b0412011-10-16 18:46:35 -07002097 const nsecs_t now = systemTime();
2098 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002099
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002100 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002102 continue;
2103 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002104 const auto displayId = display->getId();
2105 if (displayId >= 0) {
2106 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002107 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 display->onSwapBuffersCompleted();
2109 display->makeCurrent();
2110 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002111 // The layer buffer from the previous frame (if any) is released
2112 // by HWC only when the release fence from this frame (if any) is
2113 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002114 auto hwcLayer = layer->getHwcLayer(displayId);
2115 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002116
2117 // If the layer was client composited in the previous frame, we
2118 // need to merge with the previous client target acquire fence.
2119 // Since we do not track that, always merge with the current
2120 // client target acquire fence when it is available, even though
2121 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002122 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002123 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002124 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002125 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002126
David Sodmanb8af7922017-12-21 15:17:55 -08002127 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 }
Chia-I Wu83806892017-11-16 10:50:20 -08002129
2130 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002131 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002132 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002133 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002134 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002135 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002136 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002137 }
2138 }
2139
Dominik Laskowski7e045462018-05-30 13:02:02 -07002140 if (displayId >= 0) {
2141 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002142 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002143 }
2144
Mathias Agopiana44b0412011-10-16 18:46:35 -07002145 mLastSwapBufferTime = systemTime() - now;
2146 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002147
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002148 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002149 const auto display = getDefaultDisplayDeviceLocked();
2150 if (display && getHwComposer().isConnected(display->getId())) {
2151 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002152 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2153 logFrameStats();
2154 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002155 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156}
2157
Mathias Agopian87baae12012-07-31 12:38:26 -07002158void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159{
Mathias Agopian841cde52012-03-01 15:44:37 -08002160 ATRACE_CALL();
2161
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002162 // here we keep a copy of the drawing state (that is the state that's
2163 // going to be overwritten by handleTransactionLocked()) outside of
2164 // mStateLock so that the side-effects of the State assignment
2165 // don't happen with mStateLock held (which can cause deadlocks).
2166 State drawingState(mDrawingState);
2167
Mathias Agopianca4d3602011-05-19 15:38:14 -07002168 Mutex::Autolock _l(mStateLock);
2169 const nsecs_t now = systemTime();
2170 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002171
Mathias Agopianca4d3602011-05-19 15:38:14 -07002172 // Here we're guaranteed that some transaction flags are set
2173 // so we can call handleTransactionLocked() unconditionally.
2174 // We call getTransactionFlags(), which will also clear the flags,
2175 // with mStateLock held to guarantee that mCurrentState won't change
2176 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002177
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002178 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002179 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002180 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002181
Mathias Agopianca4d3602011-05-19 15:38:14 -07002182 mLastTransactionTime = systemTime() - now;
2183 mDebugInTransaction = 0;
2184 invalidateHwcGeometry();
2185 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002186}
2187
Dominik Laskowski7e045462018-05-30 13:02:02 -07002188DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002189 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002190 // Figure out whether the event is for the primary display or an
2191 // external display by matching the Hwc display id against one for a
2192 // connected display. If we did not find a match, we then check what
2193 // displays are not already connected to determine the type. If we don't
2194 // have a connected primary display, we assume the new display is meant to
2195 // be the primary display, and then if we don't have an external display,
2196 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002197 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2198 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002199 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002200 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002201 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002202 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002203 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002204 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002205 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002206 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002207 return DisplayDevice::DISPLAY_EXTERNAL;
2208 }
2209
2210 return DisplayDevice::DISPLAY_ID_INVALID;
2211}
2212
Lloyd Piqueba04e622017-12-14 17:11:26 -08002213void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2214 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002215 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002216 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002217 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002218 continue;
2219 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002220
2221 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2222 ALOGE("External displays are not supported by the vr hardware composer.");
2223 continue;
2224 }
2225
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002226 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002227 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002228 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002229 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002230 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002231
2232 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002233 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002234 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002236 DisplayDeviceState info;
2237 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002238 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2239 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002240 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002242 mInterceptor->saveDisplayCreation(info);
2243 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002244 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002245 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002246
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002248 if (idx >= 0) {
2249 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002250 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002251 mCurrentState.displays.removeItemsAt(idx);
2252 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002253 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002254 }
2255
2256 processDisplayChangesLocked();
2257 }
2258
2259 mPendingHotplugEvents.clear();
2260}
2261
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002263 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002265 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002266 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002267
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002269 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 for (ColorMode colorMode : modes) {
2271 switch (colorMode) {
2272 case ColorMode::DISPLAY_P3:
2273 case ColorMode::ADOBE_RGB:
2274 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 break;
2277 default:
2278 break;
2279 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280
Dominik Laskowski7e045462018-05-30 13:02:02 -07002281 std::vector<RenderIntent> renderIntents =
2282 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002283 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284 }
2285 }
2286
Peiyong Lin62665892018-04-16 11:07:44 -07002287 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002288 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289
2290 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2291 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2292
2293 /*
2294 * Create our display's surface
2295 */
2296 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2297 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002298 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002299 renderSurface->setNativeWindow(nativeWindow.get());
2300 const int displayWidth = renderSurface->queryWidth();
2301 const int displayHeight = renderSurface->queryHeight();
2302
2303 // Make sure that composition can never be stalled by a virtual display
2304 // consumer that isn't processing buffers fast enough. We have to do this
2305 // in two places:
2306 // * Here, in case the display is composed entirely by HWC.
2307 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2308 // window's swap interval in eglMakeCurrent, so they'll override the
2309 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002310 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002311 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2312 }
2313
2314 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002315 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2319 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2320 displayHeight, hasWideColorGamut, hdrCapabilities,
2321 getHwComposer().getSupportedPerFrameMetadata(displayId),
2322 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323
2324 if (maxFrameBufferAcquiredBuffers >= 3) {
2325 nativeWindowSurface->preallocateBuffers();
2326 }
2327
2328 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2330 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002332 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002336 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002338 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 display->setLayerStack(state.layerStack);
2340 display->setProjection(state.orientation, state.viewport, state.frame);
2341 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344}
2345
Lloyd Pique347200f2017-12-14 17:00:15 -08002346void SurfaceFlinger::processDisplayChangesLocked() {
2347 // here we take advantage of Vector's copy-on-write semantics to
2348 // improve performance by skipping the transaction entirely when
2349 // know that the lists are identical
2350 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2351 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2352 if (!curr.isIdenticalTo(draw)) {
2353 mVisibleRegionsDirty = true;
2354 const size_t cc = curr.size();
2355 size_t dc = draw.size();
2356
2357 // find the displays that were removed
2358 // (ie: in drawing state but not in current state)
2359 // also handle displays that changed
2360 // (ie: displays that are in both lists)
2361 for (size_t i = 0; i < dc;) {
2362 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2363 if (j < 0) {
2364 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002365 // Call makeCurrent() on the primary display so we can
2366 // be sure that nothing associated with this display
2367 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002368 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2369 defaultDisplay->makeCurrent();
2370 }
2371 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2372 display->disconnect(getHwComposer());
2373 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002374 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2375 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2376 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2377 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2378 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002379 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 } else {
2381 // this display is in both lists. see if something changed.
2382 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002384 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2385 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2386 if (state_binder != draw_binder) {
2387 // changing the surface is like destroying and
2388 // recreating the DisplayDevice, so we just remove it
2389 // from the drawing state, so that it get re-added
2390 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2392 display->disconnect(getHwComposer());
2393 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002394 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002395 mDrawingState.displays.removeItemsAt(i);
2396 dc--;
2397 // at this point we must loop to the next item
2398 continue;
2399 }
2400
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002401 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002403 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002404 }
2405 if ((state.orientation != draw[i].orientation) ||
2406 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 }
2409 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002410 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002411 }
2412 }
2413 }
2414 ++i;
2415 }
2416
2417 // find displays that were added
2418 // (ie: in current state but not in drawing state)
2419 for (size_t i = 0; i < cc; i++) {
2420 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2421 const DisplayDeviceState& state(curr[i]);
2422
2423 sp<DisplaySurface> dispSurface;
2424 sp<IGraphicBufferProducer> producer;
2425 sp<IGraphicBufferProducer> bqProducer;
2426 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002427 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002428
Dominik Laskowski7e045462018-05-30 13:02:02 -07002429 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002430 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 // Virtual displays without a surface are dormant:
2432 // they have external state (layer stack, projection,
2433 // etc.) but no internal state (i.e. a DisplayDevice).
2434 if (state.surface != nullptr) {
2435 // Allow VR composer to use virtual displays.
2436 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2437 int width = 0;
2438 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2439 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2440 int height = 0;
2441 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2442 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2443 int intFormat = 0;
2444 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2445 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002446 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002447
Dominik Laskowski7e045462018-05-30 13:02:02 -07002448 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2449 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 }
2451
2452 // TODO: Plumb requested format back up to consumer
2453
2454 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002455 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 bqProducer, bqConsumer,
2457 state.displayName);
2458
2459 dispSurface = vds;
2460 producer = vds;
2461 }
2462 } else {
2463 ALOGE_IF(state.surface != nullptr,
2464 "adding a supported display, but rendering "
2465 "surface is provided (%p), ignoring it",
2466 state.surface.get());
2467
Dominik Laskowski7e045462018-05-30 13:02:02 -07002468 displayId = state.type;
2469 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 producer = bqProducer;
2471 }
2472
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002473 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002475 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002476 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002477 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002478 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002479 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2480 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2481 true);
2482 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2483 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2484 true);
2485 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 }
2487 }
2488 }
2489 }
2490 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002491
2492 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002493}
2494
Mathias Agopian87baae12012-07-31 12:38:26 -07002495void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002496{
Dan Stoza7dde5992015-05-22 09:51:44 -07002497 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002498 mCurrentState.traverseInZOrder([](Layer* layer) {
2499 layer->notifyAvailableFrames();
2500 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 /*
2503 * Traversal of the children
2504 * (perform the transaction for each of them if needed)
2505 */
2506
Mathias Agopian3559b072012-08-15 13:46:03 -07002507 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002508 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002510 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
2512 const uint32_t flags = layer->doTransaction(0);
2513 if (flags & Layer::eVisibleRegion)
2514 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002515 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 }
2517
2518 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 */
2521
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002527 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002528 // The transform hint might have changed for some layers
2529 // (either because a display has changed, or because a layer
2530 // as changed).
2531 //
2532 // Walk through all the layers in currentLayers,
2533 // and update their transform hint.
2534 //
2535 // If a layer is visible only on a single display, then that
2536 // display is used to calculate the hint, otherwise we use the
2537 // default display.
2538 //
2539 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2540 // the hint is set before we acquire a buffer from the surface texture.
2541 //
2542 // NOTE: layer transactions have taken place already, so we use their
2543 // drawing state. However, SurfaceFlinger's own transaction has not
2544 // happened yet, so we must use the current state layer list
2545 // (soon to become the drawing state list).
2546 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002548 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002549 bool first = true;
2550 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002551 // NOTE: we rely on the fact that layers are sorted by
2552 // layerStack first (so we don't have to traverse the list
2553 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002555 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002556 currentlayerStack = layerStack;
2557 // figure out if this layerstack is mirrored
2558 // (more than one display) if so, pick the default display,
2559 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 hintDisplay = nullptr;
2561 for (const auto& [token, display] : mDisplays) {
2562 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2563 if (hintDisplay) {
2564 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002565 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002567 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002568 }
2569 }
2570 }
2571 }
Chet Haase91d25932013-04-11 15:24:55 -07002572
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002573 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002574 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2575 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002576
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002577 // could be null when this layer is using a layerStack
2578 // that is not visible on any display. Also can occur at
2579 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002580 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002581 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002582
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002584 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 if (hintDisplay) {
2586 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002587 }
Robert Carr2047fae2016-11-28 14:09:09 -08002588
2589 first = false;
2590 });
Mathias Agopian84300952012-11-21 16:02:13 -08002591 }
2592
2593
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 /*
2595 * Perform our own transaction if needed
2596 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002597
2598 if (mLayersAdded) {
2599 mLayersAdded = false;
2600 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002601 mVisibleRegionsDirty = true;
2602 }
2603
2604 // some layers might have been removed, so
2605 // we need to update the regions they're exposing.
2606 if (mLayersRemoved) {
2607 mLayersRemoved = false;
2608 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002609 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002610 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002611 // this layer is not visible anymore
2612 // TODO: we could traverse the tree from front to back and
2613 // compute the actual visible region
2614 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002615 Region visibleReg;
2616 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002617 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002618 }
Robert Carr2047fae2016-11-28 14:09:09 -08002619 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 }
2621
2622 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002623
2624 updateCursorAsync();
2625}
2626
2627void SurfaceFlinger::updateCursorAsync()
2628{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002630 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002631 continue;
2632 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002634 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2635 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002636 }
2637 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638}
2639
2640void SurfaceFlinger::commitTransaction()
2641{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002642 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002643 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 for (const auto& l : mLayersPendingRemoval) {
2645 recordBufferingStats(l->getName().string(),
2646 l->getOccupancyHistory(true));
2647 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648 }
2649 mLayersPendingRemoval.clear();
2650 }
2651
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002652 // If this transaction is part of a window animation then the next frame
2653 // we composite should be considered an animation as well.
2654 mAnimCompositionPending = mAnimTransactionPending;
2655
Mathias Agopian4fec8732012-06-29 14:12:52 -07002656 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002657 // clear the "changed" flags in current state
2658 mCurrentState.colorMatrixChanged = false;
2659
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 mDrawingState.traverseInZOrder([](Layer* layer) {
2661 layer->commitChildList();
2662 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002663 mTransactionPending = false;
2664 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002665 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666}
2667
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002668void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2669 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002670 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002672
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 Region aboveOpaqueLayers;
2674 Region aboveCoveredLayers;
2675 Region dirty;
2676
Mathias Agopian87baae12012-07-31 12:38:26 -07002677 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002681 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
Jesse Hall01e29052013-02-19 16:13:35 -08002683 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002685 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002687
Mathias Agopianab028732010-03-16 16:41:46 -07002688 /*
2689 * opaqueRegion: area of a surface that is fully opaque.
2690 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002692
2693 /*
2694 * visibleRegion: area of a surface that is visible on screen
2695 * and not fully transparent. This is essentially the layer's
2696 * footprint minus the opaque regions above it.
2697 * Areas covered by a translucent surface are considered visible.
2698 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002700
2701 /*
2702 * coveredRegion: area of a surface that is covered by all
2703 * visible regions above it (which includes the translucent areas).
2704 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002706
Jesse Halla8026d22012-09-25 13:25:04 -07002707 /*
2708 * transparentRegion: area of a surface that is hinted to be completely
2709 * transparent. This is only used to tell when the layer has no visible
2710 * non-transparent regions and can be removed from the layer list. It
2711 * does not affect the visibleRegion of this layer or any layers
2712 * beneath it. The hint may not be correct if apps don't respect the
2713 * SurfaceView restrictions (which, sadly, some don't).
2714 */
2715 Region transparentRegion;
2716
Mathias Agopianab028732010-03-16 16:41:46 -07002717
2718 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002719 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002720 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002721 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002724 if (!visibleRegion.isEmpty()) {
2725 // Remove the transparent area from the visible region
2726 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002727 if (tr.preserveRects()) {
2728 // transform the transparent region
2729 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002731 // transformation too complex, can't do the
2732 // transparent region optimization.
2733 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 }
Mathias Agopianab028732010-03-16 16:41:46 -07002735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736
Mathias Agopianab028732010-03-16 16:41:46 -07002737 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002739 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002740 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2741 // the opaque region is the layer's footprint
2742 opaqueRegion = visibleRegion;
2743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 }
2745 }
2746
Robert Carre5f4f692018-01-12 13:12:28 -08002747 if (visibleRegion.isEmpty()) {
2748 layer->clearVisibilityRegions();
2749 return;
2750 }
2751
Mathias Agopianab028732010-03-16 16:41:46 -07002752 // Clip the covered region to the visible region
2753 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2754
2755 // Update aboveCoveredLayers for next (lower) layer
2756 aboveCoveredLayers.orSelf(visibleRegion);
2757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 // subtract the opaque region covered by the layers above us
2759 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
2761 // compute this layer's dirty region
2762 if (layer->contentDirty) {
2763 // we need to invalidate the whole region
2764 dirty = visibleRegion;
2765 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 layer->contentDirty = false;
2768 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002769 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002770 * the exposed region consists of two components:
2771 * 1) what's VISIBLE now and was COVERED before
2772 * 2) what's EXPOSED now less what was EXPOSED before
2773 *
2774 * note that (1) is conservative, we start with the whole
2775 * visible region but only keep what used to be covered by
2776 * something -- which mean it may have been exposed.
2777 *
2778 * (2) handles areas that were not covered by anything but got
2779 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002780 */
Mathias Agopianab028732010-03-16 16:41:46 -07002781 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002782 const Region oldVisibleRegion = layer->visibleRegion;
2783 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002784 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2785 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 }
2787 dirty.subtractSelf(aboveOpaqueLayers);
2788
2789 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002790 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791
Mathias Agopianab028732010-03-16 16:41:46 -07002792 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002794
Jesse Halla8026d22012-09-25 13:25:04 -07002795 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 layer->setVisibleRegion(visibleRegion);
2797 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002798 layer->setVisibleNonTransparentRegion(
2799 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002800 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801
Mathias Agopian87baae12012-07-31 12:38:26 -07002802 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803}
2804
Chia-I Wuab0c3192017-08-01 11:29:00 -07002805void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2808 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002809 }
2810 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002811}
2812
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("handlePageFlip");
2816
Brian Andersond6927fb2016-07-23 23:37:30 -07002817 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002821 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002822
2823 // Store the set of layers that need updates. This set must not change as
2824 // buffers are being latched, as this could result in a deadlock.
2825 // Example: Two producers share the same command stream and:
2826 // 1.) Layer 0 is latched
2827 // 2.) Layer 0 gets a new frame
2828 // 2.) Layer 1 gets a new frame
2829 // 3.) Layer 1 is latched.
2830 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2831 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 if (layer->hasQueuedFrame()) {
2834 frameQueued = true;
2835 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002836 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002837 } else {
2838 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002840 } else {
2841 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843 });
2844
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002846 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002847 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002848 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002849 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002850 newDataLatched = true;
2851 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002852 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002853
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002854 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855
2856 // If we will need to wake up at some time in the future to deal with a
2857 // queued frame that shouldn't be displayed during this vsync period, wake
2858 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002859 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 signalLayerUpdate();
2861 }
2862
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002863 // enter boot animation on first buffer latch
2864 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2865 ALOGI("Enter boot animation");
2866 mBootStage = BootStage::BOOTANIMATION;
2867 }
2868
Dan Stoza6b9454d2014-11-07 16:00:59 -08002869 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002870 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871}
2872
Mathias Agopianad456f92011-01-13 17:53:01 -08002873void SurfaceFlinger::invalidateHwcGeometry()
2874{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002876}
2877
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002878void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2879 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002880 // We only need to actually compose the display if:
2881 // 1) It is being handled by hardware composer, which may need this to
2882 // keep its virtual display state machine in sync, or
2883 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002884 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002885 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002887 return;
2888 }
2889
Dan Stoza9e56aa02015-11-02 13:00:03 -08002890 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002891 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002892
2893 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895}
2896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002898 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 const Region bounds(display->bounds());
2901 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002902 const auto displayId = display->getId();
2903 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002904 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002905
Chia-I Wu8e50e692018-05-04 10:12:37 -07002906 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002907 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002908
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 if (hasClientComposition) {
2910 ALOGV("hasClientComposition");
2911
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002912 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002913 if (display->hasWideColorGamut()) {
2914 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002915 }
2916 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002917 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002918 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002919
Dominik Laskowski7e045462018-05-30 13:02:02 -07002920 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002921 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2922 HWC2::Capability::SkipClientColorTransform);
2923
Chia-I Wud49d6692018-06-27 07:17:41 +08002924 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002925 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2926 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002927 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002928 }
2929
Chia-I Wud49d6692018-06-27 07:17:41 +08002930 // The current enhanced saturation matrix is designed to enhance Display P3,
2931 // thus we only apply this matrix when the render intent is not colorimetric
2932 // and the output color space is Display P3.
2933 needsEnhancedColorMatrix =
2934 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2935 outputDataspace == Dataspace::DISPLAY_P3);
2936 if (needsEnhancedColorMatrix) {
2937 colorMatrix *= mEnhancedSaturationMatrix;
2938 }
2939
2940 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002942 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002943 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002944 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002945 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002946
2947 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002948 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2949 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2950 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002951 }
2952 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002953 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002954
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002955 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002957 // when using overlays, we assume a fully transparent framebuffer
2958 // NOTE: we could reduce how much we need to clear, for instance
2959 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002960 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002961 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002962 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002963 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002964 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002965 // we're left with the letterbox region
2966 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002967 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002968
2969 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002970 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002971
Mathias Agopianb9494d52012-04-18 02:28:45 -07002972 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002973 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002974 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002976 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002977 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002980 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002981 // scissor on the main display. It should never be needed
2982 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 const Rect& bounds = display->getBounds();
2984 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 if (scissor != bounds) {
2986 // scissor doesn't match the screen's dimensions, so we
2987 // need to clear everything outside of it and enable
2988 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002989
Mathias Agopianf45c5102012-10-24 16:29:17 -07002990 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002991 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002992 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002993 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002994 }
2995 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002996 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002997
Mathias Agopian85d751c2012-08-29 16:59:24 -07002998 /*
2999 * and then, render the layers targeted at the framebuffer
3000 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003001
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003003 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003004 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003005 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003006 const Region clip(bounds.intersect(
3007 displayTransform.transform(layer->visibleRegion)));
3008 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003009 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003010 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003011 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003012 case HWC2::Composition::Cursor:
3013 case HWC2::Composition::Device:
3014 case HWC2::Composition::Sideband:
3015 case HWC2::Composition::SolidColor: {
3016 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003017 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3018 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003019 // never clear the very first layer since we're
3020 // guaranteed the FB is already cleared
3021 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003022 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003023 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003024 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003025 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003026 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003027 break;
3028 }
3029 default:
3030 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003031 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003032 } else {
3033 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003034 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003035 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003036 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003037
Chia-I Wud49d6692018-06-27 07:17:41 +08003038 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003039 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003040 }
3041
Mathias Agopianf45c5102012-10-24 16:29:17 -07003042 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003043 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003044 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045}
3046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003047void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3048 const Region& region) const {
3049 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003050 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003051 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052}
3053
Dan Stoza7d89d062015-04-30 13:29:25 -07003054status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003055 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003056 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 const sp<Layer>& lbc,
3058 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003059{
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 // add this layer to the current state list
3061 {
3062 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003064 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3065 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003066 return NO_MEMORY;
3067 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068 if (parent == nullptr) {
3069 mCurrentState.layersSortedByZ.add(lbc);
3070 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003071 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003072 ALOGE("addClientLayer called with a removed parent");
3073 return NAME_NOT_FOUND;
3074 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003075 parent->addChild(lbc);
3076 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003077
Yiwei Zhang243b3782018-05-15 17:40:04 -07003078 if (gbc != nullptr) {
3079 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3080 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3081 mMaxGraphicBufferProducerListSize,
3082 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3083 mGraphicBufferProducerList.size(),
3084 mMaxGraphicBufferProducerListSize, mNumLayers);
3085 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersAdded = true;
3087 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003088 }
3089
Mathias Agopian96f08192010-06-02 23:28:45 -07003090 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003091 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003092
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003094}
3095
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003097 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003098 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3099}
Robert Carr7f9b8992017-03-10 11:08:39 -08003100
chaviwca27f252018-02-06 16:46:39 -08003101status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3102 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003103 if (layer->isPendingRemoval()) {
3104 return NO_ERROR;
3105 }
3106
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003108 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003109 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003110 if (topLevelOnly) {
3111 return NO_ERROR;
3112 }
3113
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114 sp<Layer> ancestor = p;
3115 while (ancestor->getParent() != nullptr) {
3116 ancestor = ancestor->getParent();
3117 }
3118 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3119 ALOGE("removeLayer called with a layer whose parent has been removed");
3120 return NAME_NOT_FOUND;
3121 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003122
3123 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003124 } else {
3125 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003126 }
3127
Robert Carr136e2f62017-02-08 17:54:29 -08003128 // As a matter of normal operation, the LayerCleaner will produce a second
3129 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3130 // so we will succeed in promoting it, but it's already been removed
3131 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3132 // otherwise something has gone wrong and we are leaking the layer.
3133 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3135 layer->getName().string(),
3136 (p != nullptr) ? p->getName().string() : "no-parent");
3137 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003138 } else if (index < 0) {
3139 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003140 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141
Chia-I Wuc6657022017-08-15 11:18:17 -07003142 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 mLayersPendingRemoval.add(layer);
3144 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003145 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003146 setTransactionFlags(eTransactionNeeded);
3147 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148}
3149
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003150uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003151 return android_atomic_release_load(&mTransactionFlags);
3152}
3153
Mathias Agopian3f844832013-08-07 21:24:32 -07003154uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3156}
3157
Mathias Agopian3f844832013-08-07 21:24:32 -07003158uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003159 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3160}
3161
3162uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3163 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003165 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003167 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 return old;
3170}
3171
chaviwca27f252018-02-06 16:46:39 -08003172bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3173 for (const ComposerState& state : states) {
3174 // Here we need to check that the interface we're given is indeed
3175 // one of our own. A malicious client could give us a nullptr
3176 // IInterface, or one of its own or even one of our own but a
3177 // different type. All these situations would cause us to crash.
3178 if (state.client == nullptr) {
3179 return true;
3180 }
3181
3182 sp<IBinder> binder = IInterface::asBinder(state.client);
3183 if (binder == nullptr) {
3184 return true;
3185 }
3186
3187 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3188 return true;
3189 }
3190 }
3191 return false;
3192}
3193
Mathias Agopian8b33f032012-07-24 20:43:54 -07003194void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003195 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003196 const Vector<DisplayState>& displays,
3197 uint32_t flags)
3198{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003199 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003200 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003201 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003202
chaviwca27f252018-02-06 16:46:39 -08003203 if (containsAnyInvalidClientState(states)) {
3204 return;
3205 }
3206
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 // For window updates that are part of an animation we must wait for
3209 // previous animation "frames" to be handled.
3210 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003214 // caller after a few seconds.
3215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3216 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003217 mAnimTransactionPending = false;
3218 break;
3219 }
3220 }
3221 }
3222
chaviwca27f252018-02-06 16:46:39 -08003223 for (const DisplayState& display : displays) {
3224 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003225 }
3226
chaviwca27f252018-02-06 16:46:39 -08003227 for (const ComposerState& state : states) {
3228 transactionFlags |= setClientStateLocked(state);
3229 }
3230
3231 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3232 // as destroyed should only occur after setting all other states. This is to allow for a
3233 // child re-parent to happen before marking its original parent as destroyed (which would
3234 // then mark the child as destroyed).
3235 for (const ComposerState& state : states) {
3236 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003237 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003238
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003239 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3240 // anyway. This can be used as a flush mechanism for previous async transactions.
3241 // Empty animation transaction can be used to simulate back-pressure, so also force a
3242 // transaction for empty animation transactions.
3243 if (transactionFlags == 0 &&
3244 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003245 transactionFlags = eTransactionNeeded;
3246 }
3247
Mathias Agopian386aa982011-11-07 21:58:03 -08003248 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003249 if (mInterceptor->isEnabled()) {
3250 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003251 }
Irvel468051e2016-06-13 16:44:44 -07003252
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003254 const auto start = (flags & eEarlyWakeup)
3255 ? VSyncModulator::TransactionStart::EARLY
3256 : VSyncModulator::TransactionStart::NORMAL;
3257 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003258
3259 // if this is a synchronous transaction, wait for it to take effect
3260 // before returning.
3261 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003263 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003264 if (flags & eAnimation) {
3265 mAnimTransactionPending = true;
3266 }
3267 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3269 if (CC_UNLIKELY(err != NO_ERROR)) {
3270 // just in case something goes wrong in SF, return to the
3271 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3273 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003274 break;
3275 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
3278}
3279
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003280uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3281 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3282 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003283
Mathias Agopiane57f2922012-08-09 16:29:12 -07003284 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003285 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3286
3287 const uint32_t what = s.what;
3288 if (what & DisplayState::eSurfaceChanged) {
3289 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3290 state.surface = s.surface;
3291 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003292 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003293 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003294 if (what & DisplayState::eLayerStackChanged) {
3295 if (state.layerStack != s.layerStack) {
3296 state.layerStack = s.layerStack;
3297 flags |= eDisplayTransactionNeeded;
3298 }
3299 }
3300 if (what & DisplayState::eDisplayProjectionChanged) {
3301 if (state.orientation != s.orientation) {
3302 state.orientation = s.orientation;
3303 flags |= eDisplayTransactionNeeded;
3304 }
3305 if (state.frame != s.frame) {
3306 state.frame = s.frame;
3307 flags |= eDisplayTransactionNeeded;
3308 }
3309 if (state.viewport != s.viewport) {
3310 state.viewport = s.viewport;
3311 flags |= eDisplayTransactionNeeded;
3312 }
3313 }
3314 if (what & DisplayState::eDisplaySizeChanged) {
3315 if (state.width != s.width) {
3316 state.width = s.width;
3317 flags |= eDisplayTransactionNeeded;
3318 }
3319 if (state.height != s.height) {
3320 state.height = s.height;
3321 flags |= eDisplayTransactionNeeded;
3322 }
3323 }
3324
Mathias Agopiane57f2922012-08-09 16:29:12 -07003325 return flags;
3326}
3327
Robert Carrd4ae7f32018-06-07 16:10:57 -07003328bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3329 IPCThreadState* ipc = IPCThreadState::self();
3330 const int pid = ipc->getCallingPid();
3331 const int uid = ipc->getCallingUid();
3332
3333 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3334 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3335 return false;
3336 }
3337 return true;
3338}
3339
chaviwca27f252018-02-06 16:46:39 -08003340uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3341 const layer_state_t& s = composerState.state;
3342 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3343
Mathias Agopian13127d82013-03-05 17:47:11 -08003344 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003345 if (layer == nullptr) {
3346 return 0;
3347 }
3348
3349 if (layer->isPendingRemoval()) {
3350 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3351 return 0;
3352 }
3353
3354 uint32_t flags = 0;
3355
3356 const uint32_t what = s.what;
3357 bool geometryAppliesWithResize =
3358 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003359
3360 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3361 // pending state will also be deferred.
3362 if (what & layer_state_t::eDeferTransaction) {
3363 layer->pushPendingState();
3364 }
3365
chaviw8b3871a2017-11-01 17:41:01 -07003366 if (what & layer_state_t::ePositionChanged) {
3367 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3368 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003369 }
chaviw8b3871a2017-11-01 17:41:01 -07003370 }
3371 if (what & layer_state_t::eLayerChanged) {
3372 // NOTE: index needs to be calculated before we update the state
3373 const auto& p = layer->getParent();
3374 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003375 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003376 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003377 mCurrentState.layersSortedByZ.removeAt(idx);
3378 mCurrentState.layersSortedByZ.add(layer);
3379 // we need traversal (state changed)
3380 // AND transaction (list changed)
3381 flags |= eTransactionNeeded|eTraversalNeeded;
3382 }
chaviw8b3871a2017-11-01 17:41:01 -07003383 } else {
3384 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003385 flags |= eTransactionNeeded|eTraversalNeeded;
3386 }
3387 }
chaviw8b3871a2017-11-01 17:41:01 -07003388 }
3389 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003390 // NOTE: index needs to be calculated before we update the state
3391 const auto& p = layer->getParent();
3392 if (p == nullptr) {
3393 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3394 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3395 mCurrentState.layersSortedByZ.removeAt(idx);
3396 mCurrentState.layersSortedByZ.add(layer);
3397 // we need traversal (state changed)
3398 // AND transaction (list changed)
3399 flags |= eTransactionNeeded|eTraversalNeeded;
3400 }
3401 } else {
3402 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3403 flags |= eTransactionNeeded|eTraversalNeeded;
3404 }
chaviw8b3871a2017-11-01 17:41:01 -07003405 }
3406 }
3407 if (what & layer_state_t::eSizeChanged) {
3408 if (layer->setSize(s.w, s.h)) {
3409 flags |= eTraversalNeeded;
3410 }
3411 }
3412 if (what & layer_state_t::eAlphaChanged) {
3413 if (layer->setAlpha(s.alpha))
3414 flags |= eTraversalNeeded;
3415 }
3416 if (what & layer_state_t::eColorChanged) {
3417 if (layer->setColor(s.color))
3418 flags |= eTraversalNeeded;
3419 }
3420 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003421 // TODO: b/109894387
3422 //
3423 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3424 // rotation. To see the problem observe that if we have a square parent, and a child
3425 // of the same size, then we rotate the child 45 degrees around it's center, the child
3426 // must now be cropped to a non rectangular 8 sided region.
3427 //
3428 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3429 // private API, and the WindowManager only uses rotation in one case, which is on a top
3430 // level layer in which cropping is not an issue.
3431 //
3432 // However given that abuse of rotation matrices could lead to surfaces extending outside
3433 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3434 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3435 // transformations.
3436 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003437 flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eTransparentRegionChanged) {
3440 if (layer->setTransparentRegionHint(s.transparentRegion))
3441 flags |= eTraversalNeeded;
3442 }
3443 if (what & layer_state_t::eFlagsChanged) {
3444 if (layer->setFlags(s.flags, s.mask))
3445 flags |= eTraversalNeeded;
3446 }
3447 if (what & layer_state_t::eCropChanged) {
3448 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3449 flags |= eTraversalNeeded;
3450 }
3451 if (what & layer_state_t::eFinalCropChanged) {
3452 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3453 flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eLayerStackChanged) {
3456 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3457 // We only allow setting layer stacks for top level layers,
3458 // everything else inherits layer stack from its parent.
3459 if (layer->hasParent()) {
3460 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3461 layer->getName().string());
3462 } else if (idx < 0) {
3463 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3464 "that also does not appear in the top level layer list. Something"
3465 " has gone wrong.", layer->getName().string());
3466 } else if (layer->setLayerStack(s.layerStack)) {
3467 mCurrentState.layersSortedByZ.removeAt(idx);
3468 mCurrentState.layersSortedByZ.add(layer);
3469 // we need traversal (state changed)
3470 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003471 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003472 }
3473 }
3474 if (what & layer_state_t::eDeferTransaction) {
3475 if (s.barrierHandle != nullptr) {
3476 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3477 } else if (s.barrierGbp != nullptr) {
3478 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3479 if (authenticateSurfaceTextureLocked(gbp)) {
3480 const auto& otherLayer =
3481 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3482 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3483 } else {
3484 ALOGE("Attempt to defer transaction to to an"
3485 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003486 }
3487 }
chaviw8b3871a2017-11-01 17:41:01 -07003488 // We don't trigger a traversal here because if no other state is
3489 // changed, we don't want this to cause any more work
3490 }
3491 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003492 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003493 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003494 if (!hadParent) {
3495 mCurrentState.layersSortedByZ.remove(layer);
3496 }
chaviw8b3871a2017-11-01 17:41:01 -07003497 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003498 }
chaviw8b3871a2017-11-01 17:41:01 -07003499 }
3500 if (what & layer_state_t::eReparentChildren) {
3501 if (layer->reparentChildren(s.reparentHandle)) {
3502 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003503 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003504 }
chaviw8b3871a2017-11-01 17:41:01 -07003505 if (what & layer_state_t::eDetachChildren) {
3506 layer->detachChildren();
3507 }
3508 if (what & layer_state_t::eOverrideScalingModeChanged) {
3509 layer->setOverrideScalingMode(s.overrideScalingMode);
3510 // We don't trigger a traversal here because if no other state is
3511 // changed, we don't want this to cause any more work
3512 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003513 return flags;
3514}
3515
chaviwca27f252018-02-06 16:46:39 -08003516void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3517 const layer_state_t& state = composerState.state;
3518 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3519
3520 sp<Layer> layer(client->getLayerUser(state.surface));
3521 if (layer == nullptr) {
3522 return;
3523 }
3524
3525 if (layer->isPendingRemoval()) {
3526 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3527 return;
3528 }
3529
3530 if (state.what & layer_state_t::eDestroySurface) {
3531 removeLayerLocked(mStateLock, layer);
3532 }
3533}
3534
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003535status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003536 const String8& name,
3537 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003538 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003539 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003540 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003542 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003543 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003544 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003546 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003547
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 status_t result = NO_ERROR;
3549
3550 sp<Layer> layer;
3551
Cody Northropbc755282017-03-31 12:00:08 -06003552 String8 uniqueName = getUniqueLayerName(name);
3553
Mathias Agopian3165cc22012-08-08 19:42:09 -07003554 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3555 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003556 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003557 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003558 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 break;
chaviw13fdc492017-06-27 12:40:18 -07003561 case ISurfaceComposerClient::eFXSurfaceColor:
3562 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003563 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003564 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 break;
3566 default:
3567 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 break;
3569 }
3570
Dan Stoza7d89d062015-04-30 13:29:25 -07003571 if (result != NO_ERROR) {
3572 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003574
Chia-I Wuab0c3192017-08-01 11:29:00 -07003575 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3576 // TODO b/64227542
3577 if (windowType == 441731) {
3578 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3579 layer->setPrimaryDisplayOnly();
3580 }
3581
Albert Chaulk479c60c2017-01-27 14:21:34 -05003582 layer->setInfo(windowType, ownerUid);
3583
Robert Carr1f0a16a2016-10-24 16:27:39 -07003584 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003585 if (result != NO_ERROR) {
3586 return result;
3587 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003588 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003589
3590 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592}
3593
Cody Northropbc755282017-03-31 12:00:08 -06003594String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3595{
3596 bool matchFound = true;
3597 uint32_t dupeCounter = 0;
3598
3599 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3600 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3601
Dan Stoza436ccf32018-06-21 12:10:12 -07003602 // Grab the state lock since we're accessing mCurrentState
3603 Mutex::Autolock lock(mStateLock);
3604
Cody Northropbc755282017-03-31 12:00:08 -06003605 // Loop over layers until we're sure there is no matching name
3606 while (matchFound) {
3607 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003608 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003609 if (layer->getName() == uniqueName) {
3610 matchFound = true;
3611 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3612 }
3613 });
3614 }
3615
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003616 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3617 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003618
3619 return uniqueName;
3620}
3621
David Sodman0c69cad2017-08-21 12:12:51 -07003622status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3624 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625{
3626 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003627 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 case PIXEL_FORMAT_TRANSPARENT:
3629 case PIXEL_FORMAT_TRANSLUCENT:
3630 format = PIXEL_FORMAT_RGBA_8888;
3631 break;
3632 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003633 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634 break;
3635 }
3636
David Sodman0c69cad2017-08-21 12:12:51 -07003637 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3638 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003640 *handle = layer->getHandle();
3641 *gbp = layer->getProducer();
3642 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644
David Sodman0c69cad2017-08-21 12:12:51 -07003645 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647}
3648
chaviw13fdc492017-06-27 12:40:18 -07003649status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003650 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003651 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652{
chaviw13fdc492017-06-27 12:40:18 -07003653 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003654 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003656}
3657
Mathias Agopianac9fa422013-02-11 16:40:36 -08003658status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659{
Robert Carr9524cb32017-02-13 11:32:32 -08003660 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003661 status_t err = NO_ERROR;
3662 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003663 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003664 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003665 err = removeLayer(l);
3666 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3667 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003668 }
3669 return err;
3670}
3671
Mathias Agopian13127d82013-03-05 17:47:11 -08003672status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003673{
Mathias Agopian67106042013-03-14 19:18:13 -07003674 // called by ~LayerCleaner() when all references to the IBinder (handle)
3675 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003676 sp<Layer> l = layer.promote();
3677 if (l == nullptr) {
3678 // The layer has already been removed, carry on
3679 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003680 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003681 // If we have a parent, then we can continue to live as long as it does.
3682 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683}
3684
Mathias Agopianb60314a2012-04-10 22:09:54 -07003685// ---------------------------------------------------------------------------
3686
Andy McFadden13a082e2012-08-24 10:16:42 -07003687void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003688 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3689 if (!displayToken) return;
3690
Jesse Hall01e29052013-02-19 16:13:35 -08003691 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003692 Vector<ComposerState> state;
3693 Vector<DisplayState> displays;
3694 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003695 d.what = DisplayState::eDisplayProjectionChanged |
3696 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003697 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003698 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003699 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003700 d.frame.makeInvalid();
3701 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003702 d.width = 0;
3703 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003704 displays.add(d);
3705 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003706
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003707 const auto display = getDisplayDevice(displayToken);
3708 if (!display) return;
3709
3710 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3711
3712 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003713 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003714 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003715
Brian Andersond0010582017-03-07 13:20:31 -08003716 // Use phase of 0 since phase is not known.
3717 // Use latency of 0, which will snap to the ideal latency.
3718 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003719}
3720
3721void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003722 // Async since we may be called from the main thread.
3723 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003724}
3725
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3727 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003728 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003729 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003730
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003731 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733 return;
3734 }
3735
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003737 ALOGW("Trying to set power mode for virtual display");
3738 return;
3739 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741 display->setPowerMode(mode);
3742
Lloyd Pique4dccc412018-01-22 17:21:36 -08003743 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003744 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003745 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003746 if (idx < 0) {
3747 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3748 return;
3749 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003750 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003751 }
3752
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003753 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003755 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003757 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003758 // FIXME: eventthread only knows about the main display right now
3759 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003760 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003762
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003764 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003765 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003766
3767 struct sched_param param = {0};
3768 param.sched_priority = 1;
3769 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3770 ALOGW("Couldn't set SCHED_FIFO on display on");
3771 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003773 // Turn off the display
3774 struct sched_param param = {0};
3775 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3776 ALOGW("Couldn't set SCHED_OTHER on display off");
3777 }
3778
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003780 disableHardwareVsync(true); // also cancels any in-progress resync
3781
Mathias Agopiancde87a32012-09-13 14:09:01 -07003782 // FIXME: eventthread only knows about the main display right now
3783 mEventThread->onScreenReleased();
3784 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003786 getHwComposer().setPowerMode(type, mode);
3787 mVisibleRegionsDirty = true;
3788 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003789 } else if (mode == HWC_POWER_MODE_DOZE ||
3790 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003791 // Update display while dozing
3792 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003793 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003794 // FIXME: eventthread only knows about the main display right now
3795 mEventThread->onScreenAcquired();
3796 resyncToHardwareVsync(true);
3797 }
3798 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3799 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003801 disableHardwareVsync(true); // also cancels any in-progress resync
3802 // FIXME: eventthread only knows about the main display right now
3803 mEventThread->onScreenReleased();
3804 }
3805 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003807 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003810
3811 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003812}
3813
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003814void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003815 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816 const auto display = getDisplayDevice(displayToken);
3817 if (!display) {
3818 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3819 displayToken.get());
3820 } else if (display->isVirtual()) {
3821 ALOGW("Attempt to set power mode %d for virtual display", mode);
3822 } else {
3823 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003824 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003825 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003826}
3827
3828// ---------------------------------------------------------------------------
3829
Lloyd Pique755e3192018-01-31 16:46:15 -08003830status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3831 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003833
Mathias Agopianbd115332013-04-18 16:41:04 -07003834 IPCThreadState* ipc = IPCThreadState::self();
3835 const int pid = ipc->getCallingPid();
3836 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003837
Mathias Agopianbd115332013-04-18 16:41:04 -07003838 if ((uid != AID_SHELL) &&
3839 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003841 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003843 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003844 // (this would indicate SF is stuck, but we want to be able to
3845 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003846 status_t err = mStateLock.timedLock(s2ns(1));
3847 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003848 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003849 result.appendFormat(
3850 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3851 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003852 }
3853
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854 bool dumpAll = true;
3855 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003857
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003859 if ((index < numArgs) &&
3860 (args[index] == String16("--list"))) {
3861 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003862 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003863 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003864 }
3865
3866 if ((index < numArgs) &&
3867 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003868 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003869 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003870 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003871 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872
3873 if ((index < numArgs) &&
3874 (args[index] == String16("--latency-clear"))) {
3875 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003876 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003877 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003878 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003879
3880 if ((index < numArgs) &&
3881 (args[index] == String16("--dispsync"))) {
3882 index++;
3883 mPrimaryDispSync.dump(result);
3884 dumpAll = false;
3885 }
Dan Stozab90cf072015-03-05 11:05:59 -08003886
3887 if ((index < numArgs) &&
3888 (args[index] == String16("--static-screen"))) {
3889 index++;
3890 dumpStaticScreenStats(result);
3891 dumpAll = false;
3892 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003893
3894 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003895 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003896 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003897 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003898 dumpAll = false;
3899 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003900
3901 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3902 index++;
3903 dumpWideColorInfo(result);
3904 dumpAll = false;
3905 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003906
3907 if ((index < numArgs) &&
3908 (args[index] == String16("--enable-layer-stats"))) {
3909 index++;
3910 mLayerStats.enable();
3911 dumpAll = false;
3912 }
3913
3914 if ((index < numArgs) &&
3915 (args[index] == String16("--disable-layer-stats"))) {
3916 index++;
3917 mLayerStats.disable();
3918 dumpAll = false;
3919 }
3920
3921 if ((index < numArgs) &&
3922 (args[index] == String16("--clear-layer-stats"))) {
3923 index++;
3924 mLayerStats.clear();
3925 dumpAll = false;
3926 }
3927
3928 if ((index < numArgs) &&
3929 (args[index] == String16("--dump-layer-stats"))) {
3930 index++;
3931 mLayerStats.dump(result);
3932 dumpAll = false;
3933 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003934
3935 if ((index < numArgs) &&
3936 (args[index] == String16("--display-identification"))) {
3937 index++;
3938 dumpDisplayIdentificationData(result);
3939 dumpAll = false;
3940 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003941
3942 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3943 index++;
3944 mTimeStats.parseArgs(asProto, args, index, result);
3945 dumpAll = false;
3946 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003948
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003950 if (asProto) {
3951 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3952 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3953 } else {
3954 dumpAllLocked(args, index, result);
3955 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003956 }
3957
Mathias Agopian9795c422009-08-26 16:36:26 -07003958 if (locked) {
3959 mStateLock.unlock();
3960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961 }
3962 write(fd, result.string(), result.size());
3963 return NO_ERROR;
3964}
3965
Dan Stozac7014012014-02-14 15:03:43 -08003966void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3967 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968{
Robert Carr2047fae2016-11-28 14:09:09 -08003969 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003970 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003971 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003972}
3973
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003975 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976{
3977 String8 name;
3978 if (index < args.size()) {
3979 name = String8(args[index]);
3980 index++;
3981 }
3982
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003983 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3984 getHwComposer().isConnected(displayId)) {
3985 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3986 const nsecs_t period = activeConfig->getVsyncPeriod();
3987 result.appendFormat("%" PRId64 "\n", period);
3988 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003989
3990 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003991 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003992 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003993 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003994 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003995 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003996 }
Robert Carr2047fae2016-11-28 14:09:09 -08003997 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003998 }
3999}
4000
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004002 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003{
4004 String8 name;
4005 if (index < args.size()) {
4006 name = String8(args[index]);
4007 index++;
4008 }
4009
Robert Carr2047fae2016-11-28 14:09:09 -08004010 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004012 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013 }
Robert Carr2047fae2016-11-28 14:09:09 -08004014 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004015
Svetoslavd85084b2014-03-20 10:28:31 -07004016 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017}
4018
Jamie Gennis6547ff42013-07-16 20:12:42 -07004019// This should only be called from the main thread. Otherwise it would need
4020// the lock and should use mCurrentState rather than mDrawingState.
4021void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004022 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004023 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004024 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004025
4026 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4027}
4028
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004029void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004030{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004031 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004032
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004033 if (isLayerTripleBufferingDisabled())
4034 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004035
4036 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004037 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004038 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004039 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004040 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4041 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004042 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004043}
4044
Dan Stozab90cf072015-03-05 11:05:59 -08004045void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4046{
4047 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004048 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4049 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004050 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004051 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004052 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4053 b + 1, bucketTimeSec, percent);
4054 }
David Sodman4a36e932017-11-07 14:29:47 -08004055 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004056 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004057 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004058 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004059 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004060}
4061
Dan Stozae77c7662016-05-13 11:37:28 -07004062void SurfaceFlinger::recordBufferingStats(const char* layerName,
4063 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004064 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4065 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004066 for (const auto& segment : history) {
4067 if (!segment.usedThirdBuffer) {
4068 stats.twoBufferTime += segment.totalTime;
4069 }
4070 if (segment.occupancyAverage < 1.0f) {
4071 stats.doubleBufferedTime += segment.totalTime;
4072 } else if (segment.occupancyAverage < 2.0f) {
4073 stats.tripleBufferedTime += segment.totalTime;
4074 }
4075 ++stats.numSegments;
4076 stats.totalTime += segment.totalTime;
4077 }
4078}
4079
Brian Andersond6927fb2016-07-23 23:37:30 -07004080void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4081 result.appendFormat("Layer frame timestamps:\n");
4082
4083 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4084 const size_t count = currentLayers.size();
4085 for (size_t i=0 ; i<count ; i++) {
4086 currentLayers[i]->dumpFrameEvents(result);
4087 }
4088}
4089
Dan Stozae77c7662016-05-13 11:37:28 -07004090void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4091 result.append("Buffering stats:\n");
4092 result.append(" [Layer name] <Active time> <Two buffer> "
4093 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004094 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004095 typedef std::tuple<std::string, float, float, float> BufferTuple;
4096 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004097 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004098 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004099 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004100 if (stats.numSegments == 0) {
4101 continue;
4102 }
4103 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4104 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4105 stats.totalTime;
4106 float doubleBufferRatio = static_cast<float>(
4107 stats.doubleBufferedTime) / stats.totalTime;
4108 float tripleBufferRatio = static_cast<float>(
4109 stats.tripleBufferedTime) / stats.totalTime;
4110 sorted.insert({activeTime, {name, twoBufferRatio,
4111 doubleBufferRatio, tripleBufferRatio}});
4112 }
4113 for (const auto& sortedPair : sorted) {
4114 float activeTime = sortedPair.first;
4115 const BufferTuple& values = sortedPair.second;
4116 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4117 std::get<0>(values).c_str(), activeTime,
4118 std::get<1>(values), std::get<2>(values),
4119 std::get<3>(values));
4120 }
4121 result.append("\n");
4122}
4123
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004124void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004125 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004126 const int32_t displayId = display->getId();
4127 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4128 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004129 continue;
4130 }
4131
Dominik Laskowski7e045462018-05-30 13:02:02 -07004132 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004133 uint8_t port;
4134 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004135 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004136 result.append("no identification data\n");
4137 continue;
4138 }
4139
4140 if (!isEdid(data)) {
4141 result.append("unknown identification data: ");
4142 for (uint8_t byte : data) {
4143 result.appendFormat("%x ", byte);
4144 }
4145 result.append("\n");
4146 continue;
4147 }
4148
4149 const auto edid = parseEdid(data);
4150 if (!edid) {
4151 result.append("invalid EDID: ");
4152 for (uint8_t byte : data) {
4153 result.appendFormat("%x ", byte);
4154 }
4155 result.append("\n");
4156 continue;
4157 }
4158
4159 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4160 result.append(edid->displayName.data(), edid->displayName.length());
4161 result.append("\"\n");
4162 }
4163 result.append("\n");
4164}
4165
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4167 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004168 result.appendFormat("DisplayColorSetting: %s\n",
4169 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170
4171 // TODO: print out if wide-color mode is active or not
4172
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004173 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004174 const int32_t displayId = display->getId();
4175 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004176 continue;
4177 }
4178
Dominik Laskowski7e045462018-05-30 13:02:02 -07004179 result.appendFormat("Display %d color modes:\n", displayId);
4180 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004181 for (auto&& mode : modes) {
4182 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4183 }
4184
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004185 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004186 result.appendFormat(" Current color mode: %s (%d)\n",
4187 decodeColorMode(currentMode).c_str(), currentMode);
4188 }
4189 result.append("\n");
4190}
4191
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004192LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004193 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004194 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4195 const State& state = useDrawing ? mDrawingState : mCurrentState;
4196 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004197 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004198 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004199 });
4200
4201 return layersProto;
4202}
4203
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004204LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004205 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004206
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004207 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 resolution->set_w(display.getWidth());
4209 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004211 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4212 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4213 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004214
Dominik Laskowski7e045462018-05-30 13:02:02 -07004215 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004216 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004217 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004218 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004219 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004220 }
4221 });
4222
4223 return layersProto;
4224}
4225
Mathias Agopian74d211a2013-04-22 16:55:35 +02004226void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4227 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 bool colorize = false;
4230 if (index < args.size()
4231 && (args[index] == String16("--color"))) {
4232 colorize = true;
4233 index++;
4234 }
4235
4236 Colorizer colorizer(colorize);
4237
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004238 // figure out if we're stuck somewhere
4239 const nsecs_t now = systemTime();
4240 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4241 const nsecs_t inTransaction(mDebugInTransaction);
4242 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4243 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4244
4245 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004246 * Dump library configuration.
4247 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248
4249 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004250 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004251 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004252 appendSfConfigString(result);
4253 appendUiConfigString(result);
4254 appendGuiConfigString(result);
4255 result.append("\n");
4256
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004257 result.append("\nDisplay identification data:\n");
4258 dumpDisplayIdentificationData(result);
4259
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004260 result.append("\nWide-Color information:\n");
4261 dumpWideColorInfo(result);
4262
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004263 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004264 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004265 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004266 result.append(SyncFeatures::getInstance().toString());
4267 result.append("\n");
4268
Andy McFadden41d67d72014-04-25 16:58:34 -07004269 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004270 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004271 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004272
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004273 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4274 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004275 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4276 getHwComposer().isConnected(displayId)) {
4277 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004278 result.appendFormat("Display %d: "
4279 "app phase %" PRId64 " ns, "
4280 "sf phase %" PRId64 " ns, "
4281 "early app phase %" PRId64 " ns, "
4282 "early sf phase %" PRId64 " ns, "
4283 "early app gl phase %" PRId64 " ns, "
4284 "early sf gl phase %" PRId64 " ns, "
4285 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4286 displayId,
4287 vsyncPhaseOffsetNs,
4288 sfVsyncPhaseOffsetNs,
4289 appEarlyOffset,
4290 sfEarlyOffset,
4291 appEarlyGlOffset,
4292 sfEarlyOffset,
4293 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004294 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004295 result.append("\n");
4296
Dan Stozab90cf072015-03-05 11:05:59 -08004297 // Dump static screen stats
4298 result.append("\n");
4299 dumpStaticScreenStats(result);
4300 result.append("\n");
4301
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004302 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4303
Dan Stozae77c7662016-05-13 11:37:28 -07004304 dumpBufferingStats(result);
4305
Andy McFadden4803b742012-09-24 19:07:20 -07004306 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307 * Dump the visible layer list
4308 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004310 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004311 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4312 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004313 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004314
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004315 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004316 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004317 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004318 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319
4320 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004321 * Dump Display state
4322 */
4323
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004324 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004325 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004327 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004329 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004330 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004331
4332 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 * Dump SurfaceFlinger global state
4334 */
4335
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004336 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004337 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004339
Mathias Agopian888c8222012-08-04 21:10:38 -07004340 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004341 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004342
David Sodmanbc815282017-11-05 18:57:52 -08004343 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004344
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345 if (display) {
4346 display->undefinedRegion.dump(result, "undefinedRegion");
4347 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4348 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004349 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004350 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4351 " last transaction time : %f us\n"
4352 " transaction-flags : %08x\n"
4353 " gpu_to_cpu_unsupported : %d\n",
4354 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4355 mTransactionFlags, !mGpuToCpuSupported);
4356
4357 if (display) {
4358 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4359 result.appendFormat(" refresh-rate : %f fps\n"
4360 " x-dpi : %f\n"
4361 " y-dpi : %f\n",
4362 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4363 activeConfig->getDpiY());
4364 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365
Mathias Agopian74d211a2013-04-22 16:55:35 +02004366 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
Mathias Agopian74d211a2013-04-22 16:55:35 +02004369 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004371
4372 /*
4373 * VSYNC state
4374 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004375 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004376 result.append("\n");
4377
4378 /*
4379 * HWC layer minidump
4380 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004381 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004382 const int32_t displayId = display->getId();
4383 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004384 continue;
4385 }
4386
Dominik Laskowski7e045462018-05-30 13:02:02 -07004387 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004388 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004389 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004390 result.append("\n");
4391 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392
4393 /*
4394 * Dump HWComposer state
4395 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004396 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004397 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004398 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004399 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004400 result.appendFormat(" h/w composer %s\n",
4401 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004402 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403
4404 /*
4405 * Dump gralloc state
4406 */
4407 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4408 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004409
4410 /*
4411 * Dump VrFlinger state if in use.
4412 */
4413 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4414 result.append("VrFlinger state:\n");
4415 result.append(mVrFlinger->Dump().c_str());
4416 result.append("\n");
4417 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418}
4419
Dominik Laskowski7e045462018-05-30 13:02:02 -07004420const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004421 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004422 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004423 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004424 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004425 }
4426 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004427
4428 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4429 static const Vector<sp<Layer>> empty;
4430 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004431}
4432
Keun young Park63f165f2012-08-31 10:53:36 -07004433bool SurfaceFlinger::startDdmConnection()
4434{
4435 void* libddmconnection_dso =
4436 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4437 if (!libddmconnection_dso) {
4438 return false;
4439 }
4440 void (*DdmConnection_start)(const char* name);
4441 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004442 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004443 if (!DdmConnection_start) {
4444 dlclose(libddmconnection_dso);
4445 return false;
4446 }
4447 (*DdmConnection_start)(getServiceName());
4448 return true;
4449}
4450
Chia-I Wu28f320b2018-05-03 11:02:56 -07004451void SurfaceFlinger::updateColorMatrixLocked() {
4452 mat4 colorMatrix;
4453 if (mGlobalSaturationFactor != 1.0f) {
4454 // Rec.709 luma coefficients
4455 float3 luminance{0.213f, 0.715f, 0.072f};
4456 luminance *= 1.0f - mGlobalSaturationFactor;
4457 mat4 saturationMatrix = mat4(
4458 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4459 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4460 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4461 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4462 );
4463 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4464 } else {
4465 colorMatrix = mClientColorMatrix * mDaltonizer();
4466 }
4467
4468 if (mCurrentState.colorMatrix != colorMatrix) {
4469 mCurrentState.colorMatrix = colorMatrix;
4470 mCurrentState.colorMatrixChanged = true;
4471 setTransactionFlags(eTransactionNeeded);
4472 }
4473}
4474
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004475status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 switch (code) {
4477 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004478 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004480 case CLEAR_ANIMATION_FRAME_STATS:
4481 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004482 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004483 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004484 case ENABLE_VSYNC_INJECTIONS:
4485 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004486 {
4487 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004488 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4489 IPCThreadState* ipc = IPCThreadState::self();
4490 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4491 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004492 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004494 break;
4495 }
Robert Carr1db73f62016-12-21 12:58:51 -08004496 /*
4497 * Calling setTransactionState is safe, because you need to have been
4498 * granted a reference to Client* and Handle* to do anything with it.
4499 *
4500 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4501 */
4502 case SET_TRANSACTION_STATE:
4503 case CREATE_SCOPED_CONNECTION:
4504 {
4505 return OK;
4506 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004507 case CAPTURE_SCREEN:
4508 {
4509 // codes that require permission check
4510 IPCThreadState* ipc = IPCThreadState::self();
4511 const int pid = ipc->getCallingPid();
4512 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004513 if ((uid != AID_GRAPHICS) &&
4514 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004515 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004516 return PERMISSION_DENIED;
4517 }
4518 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 }
chaviwa76b2712017-09-20 12:02:26 -07004520 case CAPTURE_LAYERS: {
4521 IPCThreadState* ipc = IPCThreadState::self();
4522 const int pid = ipc->getCallingPid();
4523 const int uid = ipc->getCallingUid();
4524 if ((uid != AID_GRAPHICS) &&
4525 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4526 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4527 return PERMISSION_DENIED;
4528 }
4529 break;
4530 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004532 return OK;
4533}
4534
4535status_t SurfaceFlinger::onTransact(
4536 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4537{
4538 status_t credentialCheck = CheckTransactCodeCredentials(code);
4539 if (credentialCheck != OK) {
4540 return credentialCheck;
4541 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4544 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004545 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004546 IPCThreadState* ipc = IPCThreadState::self();
4547 const int uid = ipc->getCallingUid();
4548 if (CC_UNLIKELY(uid != AID_SYSTEM
4549 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004550 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004551 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004552 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 return PERMISSION_DENIED;
4554 }
4555 int n;
4556 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004557 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004558 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 return NO_ERROR;
4560 case 1002: // SHOW_UPDATES
4561 n = data.readInt32();
4562 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004563 invalidateHwcGeometry();
4564 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004567 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004570 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004571 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004572 setTransactionFlags(
4573 eTransactionNeeded|
4574 eDisplayTransactionNeeded|
4575 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004576 return NO_ERROR;
4577 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004578 case 1006:{ // send empty update
4579 signalRefresh();
4580 return NO_ERROR;
4581 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004582 case 1008: // toggle use of hw composer
4583 n = data.readInt32();
4584 mDebugDisableHWC = n ? 1 : 0;
4585 invalidateHwcGeometry();
4586 repaintEverything();
4587 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004588 case 1009: // toggle use of transform hint
4589 n = data.readInt32();
4590 mDebugDisableTransformHint = n ? 1 : 0;
4591 invalidateHwcGeometry();
4592 repaintEverything();
4593 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004595 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 reply->writeInt32(0);
4597 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004598 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004599 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004600 return NO_ERROR;
4601 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004602 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004603 if (!display) {
4604 return NAME_NOT_FOUND;
4605 }
4606
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004607 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004608 return NO_ERROR;
4609 }
4610 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004611 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004612 // daltonize
4613 n = data.readInt32();
4614 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 case 1:
4616 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4617 break;
4618 case 2:
4619 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4620 break;
4621 case 3:
4622 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4623 break;
4624 default:
4625 mDaltonizer.setType(ColorBlindnessType::None);
4626 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004627 }
4628 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004629 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004630 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004631 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004632 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004633
4634 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004637 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004639 // apply a color matrix
4640 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004642 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004643 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004644 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004645 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004646 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004648 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004650 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004651
4652 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4653 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004655 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4656 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4657 }
4658
Chia-I Wu28f320b2018-05-03 11:02:56 -07004659 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004660 return NO_ERROR;
4661 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004662 // This is an experimental interface
4663 // Needs to be shifted to proper binder interface when we productize
4664 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004665 n = data.readInt32();
4666 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004667 return NO_ERROR;
4668 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004669 case 1017: {
4670 n = data.readInt32();
4671 mForceFullDamage = static_cast<bool>(n);
4672 return NO_ERROR;
4673 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004674 case 1018: { // Modify Choreographer's phase offset
4675 n = data.readInt32();
4676 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4677 return NO_ERROR;
4678 }
4679 case 1019: { // Modify SurfaceFlinger's phase offset
4680 n = data.readInt32();
4681 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4682 return NO_ERROR;
4683 }
Irvel468051e2016-06-13 16:44:44 -07004684 case 1020: { // Layer updates interceptor
4685 n = data.readInt32();
4686 if (n) {
4687 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004688 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004689 }
4690 else{
4691 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004692 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004693 }
4694 return NO_ERROR;
4695 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004696 case 1021: { // Disable HWC virtual displays
4697 n = data.readInt32();
4698 mUseHwcVirtualDisplays = !n;
4699 return NO_ERROR;
4700 }
Romain Guy0147a172017-06-01 13:53:56 -07004701 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004702 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004703 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004704
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004706 return NO_ERROR;
4707 }
Romain Guy54f154a2017-10-24 21:40:32 +01004708 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004709 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004710 invalidateHwcGeometry();
4711 repaintEverything();
4712 return NO_ERROR;
4713 }
4714 case 1024: { // Is wide color gamut rendering/color management supported?
4715 reply->writeBool(hasWideColorDisplay);
4716 return NO_ERROR;
4717 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004718 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004719 n = data.readInt32();
4720 if (n) {
4721 ALOGV("LayerTracing enabled");
4722 mTracing.enable();
4723 doTracing("tracing.enable");
4724 reply->writeInt32(NO_ERROR);
4725 } else {
4726 ALOGV("LayerTracing disabled");
4727 status_t err = mTracing.disable();
4728 reply->writeInt32(err);
4729 }
4730 return NO_ERROR;
4731 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004732 case 1026: { // Get layer tracing status
4733 reply->writeBool(mTracing.isEnabled());
4734 return NO_ERROR;
4735 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004736 // Is a DisplayColorSetting supported?
4737 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004738 const auto display = getDefaultDisplayDevice();
4739 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004740 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004741 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004742
4743 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4744 switch (setting) {
4745 case DisplayColorSetting::MANAGED:
4746 reply->writeBool(hasWideColorDisplay);
4747 break;
4748 case DisplayColorSetting::UNMANAGED:
4749 reply->writeBool(true);
4750 break;
4751 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004753 break;
4754 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004755 reply->writeBool(
4756 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004757 break;
4758 }
4759 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004760 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004761 // Is VrFlinger active?
4762 case 1028: {
4763 Mutex::Autolock _l(mStateLock);
4764 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4765 return NO_ERROR;
4766 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 }
4768 }
4769 return err;
4770}
4771
Steven Thomas6d8110b2017-08-31 18:24:21 -07004772void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004773 android_atomic_or(1, &mRepaintEverything);
4774 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004775}
4776
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004777// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4778class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004779public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004780 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4781 ~WindowDisconnector() {
4782 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004783 }
4784
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004785private:
4786 ANativeWindow* mWindow;
4787 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004788};
4789
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004790status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4791 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4792 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4793 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004794 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004795 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004796
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004797 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004798
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004799 const auto display = getDisplayDeviceLocked(displayToken);
4800 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004801
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004802 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004803
4804 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004805 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004806 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004807}
4808
4809status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004810 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004811 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004812 ATRACE_CALL();
4813
4814 class LayerRenderArea : public RenderArea {
4815 public:
Robert Carr578038f2018-03-09 12:25:24 -08004816 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4817 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004818 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004819 mLayer(layer),
4820 mCrop(crop),
4821 mFlinger(flinger),
4822 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004823 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004824 Rect getBounds() const override {
4825 const Layer::State& layerState(mLayer->getDrawingState());
4826 return Rect(layerState.active.w, layerState.active.h);
4827 }
4828 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4829 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4830 bool isSecure() const override { return false; }
4831 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004832 Rect getSourceCrop() const override {
4833 if (mCrop.isEmpty()) {
4834 return getBounds();
4835 } else {
4836 return mCrop;
4837 }
4838 }
Robert Carr578038f2018-03-09 12:25:24 -08004839 class ReparentForDrawing {
4840 public:
4841 const sp<Layer>& oldParent;
4842 const sp<Layer>& newParent;
4843
4844 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4845 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004846 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004847 }
Robert Carr15eae092018-03-23 13:43:53 -07004848 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004849 };
4850
4851 void render(std::function<void()> drawLayers) override {
4852 if (!mChildrenOnly) {
4853 mTransform = mLayer->getTransform().inverse();
4854 drawLayers();
4855 } else {
4856 Rect bounds = getBounds();
4857 screenshotParentLayer =
4858 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4859 bounds.getWidth(), bounds.getHeight(), 0);
4860
4861 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4862 drawLayers();
4863 }
4864 }
chaviwa76b2712017-09-20 12:02:26 -07004865
chaviwa76b2712017-09-20 12:02:26 -07004866 private:
chaviw7206d492017-11-10 16:16:12 -08004867 const sp<Layer> mLayer;
4868 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004869
4870 // In the "childrenOnly" case we reparent the children to a screenshot
4871 // layer which has no properties set and which does not draw.
4872 sp<ContainerLayer> screenshotParentLayer;
4873 Transform mTransform;
4874
4875 SurfaceFlinger* mFlinger;
4876 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004877 };
4878
4879 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4880 auto parent = layerHandle->owner.promote();
4881
chaviw7206d492017-11-10 16:16:12 -08004882 if (parent == nullptr || parent->isPendingRemoval()) {
4883 ALOGE("captureLayers called with a removed parent");
4884 return NAME_NOT_FOUND;
4885 }
4886
Robert Carr578038f2018-03-09 12:25:24 -08004887 const int uid = IPCThreadState::self()->getCallingUid();
4888 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4889 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4890 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4891 return PERMISSION_DENIED;
4892 }
4893
chaviw7206d492017-11-10 16:16:12 -08004894 Rect crop(sourceCrop);
4895 if (sourceCrop.width() <= 0) {
4896 crop.left = 0;
4897 crop.right = parent->getCurrentState().active.w;
4898 }
4899
4900 if (sourceCrop.height() <= 0) {
4901 crop.top = 0;
4902 crop.bottom = parent->getCurrentState().active.h;
4903 }
4904
4905 int32_t reqWidth = crop.width() * frameScale;
4906 int32_t reqHeight = crop.height() * frameScale;
4907
Robert Carr578038f2018-03-09 12:25:24 -08004908 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004909
Robert Carr578038f2018-03-09 12:25:24 -08004910 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004911 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4912 if (!layer->isVisible()) {
4913 return;
Robert Carr578038f2018-03-09 12:25:24 -08004914 } else if (childrenOnly && layer == parent.get()) {
4915 return;
chaviwa76b2712017-09-20 12:02:26 -07004916 }
4917 visitor(layer);
4918 });
4919 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004920 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004921}
4922
4923status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4924 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004925 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004926 bool useIdentityTransform) {
4927 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004928
Iris Chang7501ed62018-04-30 14:45:42 +08004929 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004930
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004931 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4932 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4933 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4934 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004935
4936 // This mutex protects syncFd and captureResult for communication of the return values from the
4937 // main thread back to this Binder thread
4938 std::mutex captureMutex;
4939 std::condition_variable captureCondition;
4940 std::unique_lock<std::mutex> captureLock(captureMutex);
4941 int syncFd = -1;
4942 std::optional<status_t> captureResult;
4943
Robert Carr03480e22018-01-04 16:02:06 -08004944 const int uid = IPCThreadState::self()->getCallingUid();
4945 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4946
Dominik Laskowski8c001672018-05-30 16:52:06 -07004947 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004948 // If there is a refresh pending, bug out early and tell the binder thread to try again
4949 // after the refresh.
4950 if (mRefreshPending) {
4951 ATRACE_NAME("Skipping screenshot for now");
4952 std::unique_lock<std::mutex> captureLock(captureMutex);
4953 captureResult = std::make_optional<status_t>(EAGAIN);
4954 captureCondition.notify_one();
4955 return;
4956 }
4957
4958 status_t result = NO_ERROR;
4959 int fd = -1;
4960 {
4961 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004962 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004963 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4964 useIdentityTransform, forSystem, &fd);
4965 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004966 }
4967
4968 {
4969 std::unique_lock<std::mutex> captureLock(captureMutex);
4970 syncFd = fd;
4971 captureResult = std::make_optional<status_t>(result);
4972 captureCondition.notify_one();
4973 }
4974 });
4975
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004976 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004977 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004978 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004979 while (*captureResult == EAGAIN) {
4980 captureResult.reset();
4981 result = postMessageAsync(message);
4982 if (result != NO_ERROR) {
4983 return result;
4984 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004985 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004986 }
4987 result = *captureResult;
4988 }
4989
4990 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004991 sync_wait(syncFd, -1);
4992 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004993 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004994
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004995 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004996}
4997
chaviwa76b2712017-09-20 12:02:26 -07004998void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4999 TraverseLayersFunction traverseLayers, bool yswap,
5000 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005001 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005002
Lloyd Pique144e1162017-12-20 16:44:52 -08005003 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005004
5005 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005006 const auto raWidth = renderArea.getWidth();
5007 const auto raHeight = renderArea.getHeight();
5008
5009 const auto reqWidth = renderArea.getReqWidth();
5010 const auto reqHeight = renderArea.getReqHeight();
5011 Rect sourceCrop = renderArea.getSourceCrop();
5012
Iris Chang7501ed62018-04-30 14:45:42 +08005013 bool filtering = false;
5014 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5015 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5016 static_cast<int32_t>(reqHeight) != raWidth;
5017 } else {
5018 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5019 static_cast<int32_t>(reqHeight) != raHeight;
5020 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005021
Dan Stozac1879002014-05-22 15:59:05 -07005022 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005023 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005024 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005025 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005026 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5027 Transform tr;
5028 uint32_t flags = 0x00;
5029 switch (mPrimaryDisplayOrientation) {
5030 case DisplayState::eOrientation90:
5031 flags = Transform::ROT_90;
5032 break;
5033 case DisplayState::eOrientation180:
5034 flags = Transform::ROT_180;
5035 break;
5036 case DisplayState::eOrientation270:
5037 flags = Transform::ROT_270;
5038 break;
5039 }
5040 tr.set(flags, raWidth, raHeight);
5041 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005042 }
5043
5044 // ensure that sourceCrop is inside screen
5045 if (sourceCrop.left < 0) {
5046 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5047 }
chaviwa76b2712017-09-20 12:02:26 -07005048 if (sourceCrop.right > raWidth) {
5049 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005050 }
5051 if (sourceCrop.top < 0) {
5052 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5053 }
chaviwa76b2712017-09-20 12:02:26 -07005054 if (sourceCrop.bottom > raHeight) {
5055 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005056 }
5057
Chia-I Wu36574d92018-05-16 10:54:36 -07005058 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5059 engine.setOutputDataSpace(Dataspace::SRGB);
5060 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005061
Mathias Agopian180f10d2013-04-10 22:55:41 -07005062 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005063 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005064
Iris Chang7501ed62018-04-30 14:45:42 +08005065 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5066 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5067 // convert hw orientation into flag presentation
5068 // here inverse transform needed
5069 uint8_t hw_rot_90 = 0x00;
5070 uint8_t hw_flip_hv = 0x00;
5071 switch (mPrimaryDisplayOrientation) {
5072 case DisplayState::eOrientation90:
5073 hw_rot_90 = Transform::ROT_90;
5074 hw_flip_hv = Transform::ROT_180;
5075 break;
5076 case DisplayState::eOrientation180:
5077 hw_flip_hv = Transform::ROT_180;
5078 break;
5079 case DisplayState::eOrientation270:
5080 hw_rot_90 = Transform::ROT_90;
5081 break;
5082 }
5083
5084 // transform flags operation
5085 // 1) flip H V if both have ROT_90 flag
5086 // 2) XOR these flags
5087 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5088 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5089 if (rotation_rot_90 & hw_rot_90) {
5090 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5091 }
5092 rotation = static_cast<Transform::orientation_flags>
5093 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5094 }
5095
Mathias Agopian180f10d2013-04-10 22:55:41 -07005096 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005097 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005098 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005099 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005100
chaviw50da5042018-04-09 13:49:37 -07005101 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005102 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005103 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005104
chaviwa76b2712017-09-20 12:02:26 -07005105 traverseLayers([&](Layer* layer) {
5106 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005107 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005108 if (filtering) layer->setFiltering(false);
5109 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005110}
5111
chaviwa76b2712017-09-20 12:02:26 -07005112status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5113 TraverseLayersFunction traverseLayers,
5114 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005115 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005116 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005117 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005118 ATRACE_CALL();
5119
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005120 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005121
5122 traverseLayers([&](Layer* layer) {
5123 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5124 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005125
Robert Carr03480e22018-01-04 16:02:06 -08005126 // We allow the system server to take screenshots of secure layers for
5127 // use in situations like the Screen-rotation animation and place
5128 // the impetus on WindowManager to not persist them.
5129 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005130 ALOGW("FB is protected: PERMISSION_DENIED");
5131 return PERMISSION_DENIED;
5132 }
5133
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005134 // this binds the given EGLImage as a framebuffer for the
5135 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005136 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005137 if (bufferBond.getStatus() != NO_ERROR) {
5138 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005139 return INVALID_OPERATION;
5140 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005141
Dan Stozaabcda352017-06-01 14:37:39 -07005142 // this will in fact render into our dequeued buffer
5143 // via an FBO, which means we didn't have to create
5144 // an EGLSurface and therefore we're not
5145 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005146 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005147
Dan Stozaabcda352017-06-01 14:37:39 -07005148 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005149 getRenderEngine().finish();
5150 *outSyncFd = -1;
5151
chaviwa76b2712017-09-20 12:02:26 -07005152 const auto reqWidth = renderArea.getReqWidth();
5153 const auto reqHeight = renderArea.getReqHeight();
5154
Dan Stozaabcda352017-06-01 14:37:39 -07005155 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5156 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005157 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005158 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005159 } else {
5160 base::unique_fd syncFd = getRenderEngine().flush();
5161 if (syncFd < 0) {
5162 getRenderEngine().finish();
5163 }
5164 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005165 }
5166
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005167 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005168}
5169
Mathias Agopiand5556842013-09-19 17:08:37 -07005170void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005171 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005172 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005173 for (size_t y = 0; y < h; y++) {
5174 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5175 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005176 if (p[x] != 0xFF000000) return;
5177 }
5178 }
chaviwa76b2712017-09-20 12:02:26 -07005179 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005180
Robert Carr2047fae2016-11-28 14:09:09 -08005181 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005182 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005183 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005184 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5185 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5186 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5187 static_cast<float>(state.color.a));
5188 i++;
5189 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005190 }
5191}
5192
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005193// ---------------------------------------------------------------------------
5194
Dan Stoza412903f2017-04-27 13:42:17 -07005195void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5196 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005197}
5198
Dan Stoza412903f2017-04-27 13:42:17 -07005199void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5200 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005201}
5202
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005203void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5204 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005205 const LayerVector::Visitor& visitor) {
5206 // We loop through the first level of layers without traversing,
5207 // as we need to interpret min/max layer Z in the top level Z space.
5208 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005209 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005210 continue;
5211 }
5212 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005213 // relative layers are traversed in Layer::traverseInZOrder
5214 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005215 continue;
5216 }
5217 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005218 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005219 return;
5220 }
chaviwa76b2712017-09-20 12:02:26 -07005221 if (!layer->isVisible()) {
5222 return;
5223 }
5224 visitor(layer);
5225 });
5226 }
5227}
5228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005230
Chia-I Wu30505fb2018-03-26 16:20:31 -07005231
Mathias Agopian3f844832013-08-07 21:24:32 -07005232#if defined(__gl_h_)
5233#error "don't include gl/gl.h in this file"
5234#endif
5235
5236#if defined(__gl2_h_)
5237#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005238#endif