blob: 730bdcd91780743c35d8d1e2eead91d0f6725b09 [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
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080091#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
92#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090093#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094
chaviw1d044282017-09-27 12:19:28 -070095#include <layerproto/LayerProtoParser.h>
96
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097#define DISPLAY_COUNT 1
98
Mathias Agopianfee2b462013-07-03 12:34:01 -070099/*
100 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
101 * black pixels.
102 */
103#define DEBUG_SCREENSHOTS false
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700109using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700110using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700111using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700112using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
Steven Thomasb02664d2017-07-26 18:48:28 -0700114namespace {
115class ConditionalLock {
116public:
117 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
118 if (lock) {
119 mMutex.lock();
120 }
121 }
122 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
123private:
124 Mutex& mMutex;
125 bool mLocked;
126};
127} // namespace anonymous
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129// ---------------------------------------------------------------------------
130
Mathias Agopian99b49842011-06-27 16:05:52 -0700131const String16 sHardwareTest("android.permission.HARDWARE_TEST");
132const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
133const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
134const String16 sDump("android.permission.DUMP");
135
136// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800137int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
138int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700139int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700140bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800141uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800142bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800143bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800144int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800145// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600146bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700147
Kalle Raitaa099a242017-01-11 11:17:29 -0800148
149std::string getHwcServiceName() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.hwc_service_name", value, "default");
152 ALOGI("Using HWComposer service: '%s'", value);
153 return std::string(value);
154}
155
156bool useTrebleTestingOverride() {
157 char value[PROPERTY_VALUE_MAX] = {};
158 property_get("debug.sf.treble_testing_override", value, "false");
159 ALOGI("Treble testing override: '%s'", value);
160 return std::string(value) == "true";
161}
162
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800163std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
164 switch(displayColorSetting) {
165 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700166 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800167 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800169 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700170 return std::string("Enhanced");
171 default:
172 return std::string("Unknown ") +
173 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800174 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175}
176
Lloyd Pique09594832018-01-22 17:48:03 -0800177NativeWindowSurface::~NativeWindowSurface() = default;
178
179namespace impl {
180
181class NativeWindowSurface final : public android::NativeWindowSurface {
182public:
183 static std::unique_ptr<android::NativeWindowSurface> create(
184 const sp<IGraphicBufferProducer>& producer) {
185 return std::make_unique<NativeWindowSurface>(producer);
186 }
187
188 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
189 : surface(new Surface(producer, false)) {}
190
191 ~NativeWindowSurface() override = default;
192
193private:
194 sp<ANativeWindow> getNativeWindow() const override { return surface; }
195
196 void preallocateBuffers() override { surface->allocateBuffers(); }
197
198 sp<Surface> surface;
199};
200
201} // namespace impl
202
David Sodmanbc815282017-11-05 18:57:52 -0800203SurfaceFlingerBE::SurfaceFlingerBE()
204 : mHwcServiceName(getHwcServiceName()),
205 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800206 mFrameBuckets(),
207 mTotalTime(0),
208 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800209 mComposerSequenceId(0) {
210}
211
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800212SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800213 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700215 mTransactionPending(false),
216 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700217 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700218 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700219 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800221 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800223 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800224 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700226 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700227 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700228 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700229 mDebugInSwapBuffers(0),
230 mLastSwapBufferTime(0),
231 mDebugInTransaction(0),
232 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700233 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700234 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000235 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700236 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700237 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800238 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800239 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700240 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800241 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800242 mCreateBufferQueue(&BufferQueue::createBufferQueue),
243 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800244
245SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800246 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800247
248 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
249 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
250
251 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
252 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
253
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800254 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
255 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700257 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
259
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700260 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
262
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800263 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
265
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 // Vr flinger is only enabled on Daydream ready devices.
267 useVrFlinger = getBool< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::useVrFlinger>(false);
269
Fabien Sanglard1971b632017-03-10 14:50:03 -0800270 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
272
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273 hasWideColorDisplay =
274 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
275
Iris Chang7501ed62018-04-30 14:45:42 +0800276 V1_1::DisplayOrientation primaryDisplayOrientation =
277 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
278 V1_1::DisplayOrientation::ORIENTATION_0);
279
280 switch (primaryDisplayOrientation) {
281 case V1_1::DisplayOrientation::ORIENTATION_90:
282 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
283 break;
284 case V1_1::DisplayOrientation::ORIENTATION_180:
285 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
286 break;
287 case V1_1::DisplayOrientation::ORIENTATION_270:
288 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
289 break;
290 default:
291 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
292 break;
293 }
294 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
295
David Sodman99974d22017-11-28 12:04:33 -0800296 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700297
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298 // debugging stuff...
299 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700300
Mathias Agopianb4b17302013-03-20 18:36:41 -0700301 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700302 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700303
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 property_get("debug.sf.showupdates", value, "0");
305 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700306
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307 property_get("debug.sf.ddms", value, "0");
308 mDebugDDMS = atoi(value);
309 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700310 if (!startDdmConnection()) {
311 // start failed, and DDMS debugging not enabled
312 mDebugDDMS = 0;
313 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700314 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700315 ALOGI_IF(mDebugRegion, "showupdates enabled");
316 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700317
318 property_get("debug.sf.disable_backpressure", value, "0");
319 mPropagateBackpressure = !atoi(value);
320 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700321
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800322 property_get("debug.sf.enable_hwc_vds", value, "0");
323 mUseHwcVirtualDisplays = atoi(value);
324 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800325
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800326 property_get("ro.sf.disable_triple_buffer", value, "1");
327 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800328 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700329
Yiwei Zhang243b3782018-05-15 17:40:04 -0700330 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700331 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
332 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
333
Dan Stoza2713c302018-03-28 17:07:36 -0700334 property_get("debug.sf.early_phase_offset_ns", value, "0");
335 const int earlyWakeupOffsetOffsetNs = atoi(value);
336 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
337 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
338 sfVsyncPhaseOffsetNs);
339
Romain Guy11d63f42017-07-20 12:47:14 -0700340 // We should be reading 'persist.sys.sf.color_saturation' here
341 // but since /data may be encrypted, we need to wait until after vold
342 // comes online to attempt to read the property. The property is
343 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800344
345 if (useTrebleTestingOverride()) {
346 // Without the override SurfaceFlinger cannot connect to HIDL
347 // services that are not listed in the manifests. Considered
348 // deriving the setting from the set service name, but it
349 // would be brittle if the name that's not 'default' is used
350 // for production purposes later on.
351 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355void SurfaceFlinger::onFirstRef()
356{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800357 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800358}
359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360SurfaceFlinger::~SurfaceFlinger()
361{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362}
363
Dan Stozac7014012014-02-14 15:03:43 -0800364void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800365{
366 // the window manager died on us. prepare its eulogy.
367
Andy McFadden13a082e2012-08-24 10:16:42 -0700368 // restore initial conditions (default device unblank, etc)
369 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800370
371 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800373}
374
Robert Carr1db73f62016-12-21 12:58:51 -0800375static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700376 status_t err = client->initCheck();
377 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800378 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379 }
Robert Carr1db73f62016-12-21 12:58:51 -0800380 return nullptr;
381}
382
383sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
384 return initClient(new Client(this));
385}
386
387sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
388 const sp<IGraphicBufferProducer>& gbp) {
389 if (authenticateSurfaceTexture(gbp) == false) {
390 return nullptr;
391 }
392 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
393 if (layer == nullptr) {
394 return nullptr;
395 }
396
397 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700400sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
401 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402{
403 class DisplayToken : public BBinder {
404 sp<SurfaceFlinger> flinger;
405 virtual ~DisplayToken() {
406 // no more references, this display must be terminated
407 Mutex::Autolock _l(flinger->mStateLock);
408 flinger->mCurrentState.displays.removeItem(this);
409 flinger->setTransactionFlags(eDisplayTransactionNeeded);
410 }
411 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700412 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 : flinger(flinger) {
414 }
415 };
416
417 sp<BBinder> token = new DisplayToken(this);
418
419 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700420 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700421 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700422 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800423 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700424 return token;
425}
426
Jesse Hall6c913be2013-08-08 12:15:49 -0700427void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
428 Mutex::Autolock _l(mStateLock);
429
430 ssize_t idx = mCurrentState.displays.indexOfKey(display);
431 if (idx < 0) {
432 ALOGW("destroyDisplay: invalid display token");
433 return;
434 }
435
436 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
437 if (!info.isVirtualDisplay()) {
438 ALOGE("destroyDisplay called for non-virtual display");
439 return;
440 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800441 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 mCurrentState.displays.removeItemsAt(idx);
443 setTransactionFlags(eDisplayTransactionNeeded);
444}
445
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700447 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800449 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450 }
Jesse Hall692c7232012-11-08 15:41:56 -0800451 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452}
453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454void SurfaceFlinger::bootFinished()
455{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700456 if (mStartPropertySetThread->join() != NO_ERROR) {
457 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800458 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800459 const nsecs_t now = systemTime();
460 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000461 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700462
463 // wait patiently for the window manager death
464 const String16 name("window");
465 sp<IBinder> window(defaultServiceManager()->getService(name));
466 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700467 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700468 }
469
Steven Thomas050b2c82017-03-06 11:45:16 -0800470 if (mVrFlinger) {
471 mVrFlinger->OnBootFinished();
472 }
473
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700474 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700475 // formerly we would just kill the process, but we now ask it to exit so it
476 // can choose where to stop the animation.
477 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700478
479 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
480 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
481 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700482
Thierry Strudel2924d012017-08-14 15:19:37 -0700483 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700484 readPersistentProperties();
485 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700486 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487}
488
Mathias Agopian3f844832013-08-07 21:24:32 -0700489void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700490 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800491 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700492 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800494 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
495 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700496 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700497 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700498 return true;
499 }
500 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700501 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700502}
503
Lloyd Piquee83f9312018-02-01 12:53:17 -0800504class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700506 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000507 const char* name) :
508 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700509 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700510 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000511 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
512 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700513 mDispSync(dispSync),
514 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 mVsyncMutex(),
516 mPhaseOffset(phaseOffset),
517 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700518
Lloyd Piquee83f9312018-02-01 12:53:17 -0800519 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520
Lloyd Piquee83f9312018-02-01 12:53:17 -0800521 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error registering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 } else {
532 status_t err = mDispSync->removeEventListener(
533 static_cast<DispSync::Callback*>(this));
534 if (err != NO_ERROR) {
535 ALOGE("error unregistering vsync callback: %s (%d)",
536 strerror(-err), err);
537 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700538 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 }
542
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 mCallback = callback;
546 }
547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549 Mutex::Autolock lock(mVsyncMutex);
550
551 // Normalize phaseOffset to [0, period)
552 auto period = mDispSync->getPeriod();
553 phaseOffset %= period;
554 if (phaseOffset < 0) {
555 // If we're here, then phaseOffset is in (-period, 0). After this
556 // operation, it will be in (0, period)
557 phaseOffset += period;
558 }
559 mPhaseOffset = phaseOffset;
560
561 // If we're not enabled, we don't need to mess with the listeners
562 if (!mEnabled) {
563 return;
564 }
565
Dan Stoza2713c302018-03-28 17:07:36 -0700566 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
567 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700569 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 strerror(-err), err);
571 }
572 }
573
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574private:
575 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 callback = mCallback;
580
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700581 if (mTraceVsync) {
582 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700583 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700584 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585 }
586
Peiyong Lin566a3b42018-01-09 18:22:43 -0800587 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 callback->onVSyncEvent(when);
589 }
590 }
591
Tim Murray4a4e4a22016-04-19 16:29:23 +0000592 const char* const mName;
593
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 int mValue;
595
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700596 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700597 const String8 mVsyncOnLabel;
598 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700599
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700601
602 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604
605 Mutex mVsyncMutex; // Protects the following
606 nsecs_t mPhaseOffset;
607 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608};
609
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800612 InjectVSyncSource() = default;
613 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614
Lloyd Piquee83f9312018-02-01 12:53:17 -0800615 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700616 std::lock_guard<std::mutex> lock(mCallbackMutex);
617 mCallback = callback;
618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700621 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700622 if (mCallback) {
623 mCallback->onVSyncEvent(when);
624 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625 }
626
Lloyd Piquee83f9312018-02-01 12:53:17 -0800627 void setVSyncEnabled(bool) override {}
628 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700629
630private:
631 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800632 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700633};
634
Wei Wangf9b05ee2017-07-19 20:59:39 -0700635// Do not call property_set on main thread which will be blocked by init
636// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700638 ALOGI( "SurfaceFlinger's main thread ready to run. "
639 "Initializing graphics H/W...");
640
Thierry Strudel2924d012017-08-14 15:19:37 -0700641 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900642
Steven Thomasb02664d2017-07-26 18:48:28 -0700643 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800644
Steven Thomasb02664d2017-07-26 18:48:28 -0700645 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800646 mEventThreadSource =
647 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
648 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800649 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
650 [this]() { resyncWithRateLimit(); },
651 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800652 "appEventThread");
653 mSfEventThreadSource =
654 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
655 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800656
Lloyd Pique24b0a482018-03-09 18:52:26 -0800657 mSFEventThread =
658 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
659 [this]() { resyncWithRateLimit(); },
660 [this](nsecs_t timestamp) {
661 mInterceptor->saveVSyncEvent(timestamp);
662 },
663 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800664 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700665 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800668 getBE().mRenderEngine =
669 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
670 hasWideColorDisplay
671 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
672 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800673 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700674
675 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
676 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800677 getBE().mHwc.reset(
678 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700679 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
682 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
683 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Lloyd Piquefcd86612017-12-14 17:15:36 -0800685 // make the default display GLContext current so that we can create textures
686 // when creating Layers (which may happens before we render something)
687 getDefaultDisplayDeviceLocked()->makeCurrent();
688
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 if (useVrFlinger) {
690 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700691 // This callback is called from the vr flinger dispatch thread. We
692 // need to call signalTransaction(), which requires holding
693 // mStateLock when we're not on the main thread. Acquiring
694 // mStateLock from the vr flinger dispatch thread might trigger a
695 // deadlock in surface flinger (see b/66916578), so post a message
696 // to be handled on the main thread instead.
697 sp<LambdaMessage> message = new LambdaMessage([=]() {
698 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
699 mVrFlingerRequestsDisplay = requestDisplay;
700 signalTransaction();
701 });
702 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 };
David Sodman105b7dc2017-11-04 20:28:14 -0700704 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
705 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800712 mEventControlThread = std::make_unique<impl::EventControlThread>(
713 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
David Sodmanbc815282017-11-05 18:57:52 -0800721 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
724 if (getHwComposer().hasCapability(
725 HWC2::Capability::PresentFenceIsNotReliable)) {
726 mStartPropertySetThread = new StartPropertySetThread(false);
727 } else {
728 mStartPropertySetThread = new StartPropertySetThread(true);
729 }
730
731 if (mStartPropertySetThread->Start() != NO_ERROR) {
732 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800733 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800734
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
736 Dataspace::SRGB_LINEAR);
737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800766 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800770 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dan Stoza7f7da322014-05-02 15:26:25 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
809 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500814 if (!display.get())
815 return NAME_NOT_FOUND;
816
Jesse Hall692c7232012-11-08 15:41:56 -0800817 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700818 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800819 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700820 type = i;
821 break;
822 }
823 }
824
825 if (type < 0) {
826 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700827 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 // TODO: Not sure if display density should handled by SF any longer
830 class Density {
831 static int getDensityFromProperty(char const* propName) {
832 char property[PROPERTY_VALUE_MAX];
833 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800834 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 density = atoi(property);
836 }
837 return density;
838 }
839 public:
840 static int getEmuDensity() {
841 return getDensityFromProperty("qemu.sf.lcd_density"); }
842 static int getBuildDensity() {
843 return getDensityFromProperty("ro.sf.lcd_density"); }
844 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700847
Steven Thomas6d8110b2017-08-31 18:24:21 -0700848 ConditionalLock _l(mStateLock,
849 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 DisplayInfo info = DisplayInfo();
852
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 float xdpi = hwConfig->getDpiX();
854 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
856 if (type == DisplayDevice::DISPLAY_PRIMARY) {
857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700873 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800874 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 info.w = hwConfig->getWidth();
883 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Iris Chang7501ed62018-04-30 14:45:42 +0800907 if (type == DisplayDevice::DISPLAY_PRIMARY &&
908 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800920 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
924 // FIXME for now we always return stats for the primary display
925 memset(stats, 0, sizeof(*stats));
926 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
928 return NO_ERROR;
929}
930
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800932 if (display == nullptr) {
933 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800934 return BAD_VALUE;
935 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700936
937 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800938 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700939 return device->getActiveConfig();
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dan Stoza24a42e92015-03-09 10:04:11 -0700942 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
946 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
947 this);
948 int32_t type = hw->getDisplayType();
949 int currentMode = hw->getActiveConfig();
950
951 if (mode == currentMode) {
952 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
953 return;
954 }
955
956 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
957 ALOGW("Trying to set config for virtual display");
958 return;
959 }
960
961 hw->setActiveConfig(mode);
962 getHwComposer().setActiveConfig(type, mode);
963}
964
965status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
966 class MessageSetActiveConfig: public MessageBase {
967 SurfaceFlinger& mFlinger;
968 sp<IBinder> mDisplay;
969 int mMode;
970 public:
971 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
972 int mode) :
973 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
974 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700975 Vector<DisplayInfo> configs;
976 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700977 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700978 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700979 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700981 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800983 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700985 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
987 ALOGW("Attempt to set active config = %d for virtual display",
988 mMode);
989 } else {
990 mFlinger.setActiveConfigInternal(hw, mMode);
991 }
992 return true;
993 }
994 };
995 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
996 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700997 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700998}
Michael Wright28f24d02016-07-12 13:30:53 -0700999status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001001 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1002 return BAD_VALUE;
1003 }
1004
1005 if (!display.get()) {
1006 return NAME_NOT_FOUND;
1007 }
1008
1009 int32_t type = NAME_NOT_FOUND;
1010 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1011 if (display == mBuiltinDisplays[i]) {
1012 type = i;
1013 break;
1014 }
1015 }
1016
1017 if (type < 0) {
1018 return type;
1019 }
1020
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001022 {
1023 ConditionalLock _l(mStateLock,
1024 std::this_thread::get_id() != mMainThreadId);
1025 modes = getHwComposer().getColorModes(type);
1026 }
Michael Wright28f24d02016-07-12 13:30:53 -07001027 outColorModes->clear();
1028 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1029
1030 return NO_ERROR;
1031}
1032
Peiyong Lina52f0292018-03-14 17:26:31 -07001033ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001034 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001035 if (device != nullptr) {
1036 return device->getActiveColorMode();
1037 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001038 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001039}
1040
1041void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001042 ColorMode mode, Dataspace dataSpace,
1043 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001044 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001046 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001047 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001048
Peiyong Lin38e9a562018-04-10 16:24:20 -07001049 if (mode == currentMode && dataSpace == currentDataSpace &&
1050 renderIntent == currentRenderIntent) {
1051 return;
1052 }
1053
1054 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1055 ALOGW("Trying to set config for virtual display");
1056 return;
1057 }
1058
1059 hw->setActiveColorMode(mode);
1060 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001061 hw->setActiveRenderIntent(renderIntent);
1062 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1063
1064 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1065 decodeColorMode(mode).c_str(), mode,
1066 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1067 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001068}
1069
1070
1071status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001073 class MessageSetActiveColorMode: public MessageBase {
1074 SurfaceFlinger& mFlinger;
1075 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 public:
1078 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001080 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1081 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001083 mFlinger.getDisplayColorModes(mDisplay, &modes);
1084 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return true;
1089 }
1090 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1091 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001092 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1093 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001094 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001095 ALOGW("Attempt to set active color mode %s %d for virtual display",
1096 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001097 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001098 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1099 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
1101 return true;
1102 }
1103 };
1104 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1105 postMessageSync(msg);
1106 return NO_ERROR;
1107}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001108
Svetoslavd85084b2014-03-20 10:28:31 -07001109status_t SurfaceFlinger::clearAnimationFrameStats() {
1110 Mutex::Autolock _l(mStateLock);
1111 mAnimFrameTracker.clearStats();
1112 return NO_ERROR;
1113}
1114
1115status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1116 Mutex::Autolock _l(mStateLock);
1117 mAnimFrameTracker.getStats(outStats);
1118 return NO_ERROR;
1119}
1120
Dan Stozac4f471e2016-03-24 09:31:08 -07001121status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1122 HdrCapabilities* outCapabilities) const {
1123 Mutex::Autolock _l(mStateLock);
1124
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001125 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001126 if (displayDevice == nullptr) {
1127 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1128 return BAD_VALUE;
1129 }
1130
Peiyong Linfb069302018-04-25 14:34:31 -07001131 // At this point the DisplayDeivce should already be set up,
1132 // meaning the luminance information is already queried from
1133 // hardware composer and stored properly.
1134 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1135 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1136 capabilities.getDesiredMaxLuminance(),
1137 capabilities.getDesiredMaxAverageLuminance(),
1138 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001139
1140 return NO_ERROR;
1141}
1142
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1145 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 if (mInjectVSyncs == enable) {
1148 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150
1151 if (enable) {
1152 ALOGV("VSync Injections enabled");
1153 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001154 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001155 mInjectorEventThread = std::make_unique<
1156 impl::EventThread>(mVSyncInjector.get(),
1157 [this]() { resyncWithRateLimit(); },
1158 impl::EventThread::InterceptVSyncsCallback(),
1159 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 }
Lloyd Pique9123ae52018-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 Pique9123ae52018-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;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 });
1169 postMessageSync(enableVSyncInjections);
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 Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-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 Pique9123ae52018-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 Pique9123ae52018-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 Pique9123ae52018-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 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1270 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273}
1274
Jesse Hall948fe0c2013-10-14 12:56:09 -07001275void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276 Mutex::Autolock _l(mHWVsyncLock);
1277
Jesse Hall948fe0c2013-10-14 12:56:09 -07001278 if (makeAvailable) {
1279 mHWVsyncAvailable = true;
1280 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001281 // Hardware vsync is not currently available, so abort the resync
1282 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001283 return;
1284 }
1285
David Sodman105b7dc2017-11-04 20:28:14 -07001286 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001287 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288
1289 mPrimaryDispSync.reset();
1290 mPrimaryDispSync.setPeriod(period);
1291
1292 if (!mPrimaryHWVsyncEnabled) {
1293 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1295 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryHWVsyncEnabled = true;
1297 }
1298}
1299
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 Mutex::Autolock _l(mHWVsyncLock);
1302 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1304 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 mPrimaryDispSync.endResync();
1306 mPrimaryHWVsyncEnabled = false;
1307 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308 if (makeUnavailable) {
1309 mHWVsyncAvailable = false;
1310 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311}
1312
Tim Murray4a4e4a22016-04-19 16:29:23 +00001313void SurfaceFlinger::resyncWithRateLimit() {
1314 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001315
1316 // No explicit locking is needed here since EventThread holds a lock while calling this method
1317 static nsecs_t sLastResyncAttempted = 0;
1318 const nsecs_t now = systemTime();
1319 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001320 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001321 }
Dan Stoza57164302017-05-08 14:03:54 -07001322 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001323}
1324
Steven Thomasb02664d2017-07-26 18:48:28 -07001325void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1326 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001329 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 return;
1331 }
1332
1333 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001334 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001335 return;
1336 }
1337
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 { // Scope for the lock
1341 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001343 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001345 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001346
1347 if (needsHwVsync) {
1348 enableHardwareVsync();
1349 } else {
1350 disableHardwareVsync(false);
1351 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001352}
1353
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001354void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001355 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1356 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001357}
1358
Lloyd Pique715a2c12017-12-14 17:18:08 -08001359void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1360 HWC2::Connection connection) {
1361 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1362 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001363
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 // Ignore events that do not have the right sequenceId.
1365 if (sequenceId != getBE().mComposerSequenceId) {
1366 return;
1367 }
1368
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 // Only lock if we're not on the main thread. This function is normally
1370 // called on a hwbinder thread, but for the primary display it's called on
1371 // the main thread with the state lock already held, so don't attempt to
1372 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374
Lloyd Pique715a2c12017-12-14 17:18:08 -08001375 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001376
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001377 if (std::this_thread::get_id() == mMainThreadId) {
1378 // Process all pending hot plug events immediately if we are on the main thread.
1379 processDisplayHotplugEventsLocked();
1380 }
1381
Lloyd Piqueba04e622017-12-14 17:11:26 -08001382 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001383}
1384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385void SurfaceFlinger::onRefreshReceived(int sequenceId,
1386 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001388 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001391 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001392}
1393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001395 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001397 getHwComposer().setVsyncEnabled(disp,
1398 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001399}
1400
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001402void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 // Clear the drawing state so that the logic inside of
1405 // handleTransactionLocked will fire. It will determine the delta between
1406 // mCurrentState and mDrawingState and re-apply all changes when we make the
1407 // transition.
1408 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001409 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410 mDisplays.clear();
1411}
1412
Steven Thomas050b2c82017-03-06 11:45:16 -08001413void SurfaceFlinger::updateVrFlinger() {
1414 if (!mVrFlinger)
1415 return;
1416 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 return;
1419 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420
David Sodman105b7dc2017-11-04 20:28:14 -07001421 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 ALOGE("Vr flinger is only supported for remote hardware composer"
1423 " service connections. Ignoring request to transition to vr"
1424 " flinger.");
1425 mVrFlingerRequestsDisplay = false;
1426 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 int currentDisplayPowerMode = getDisplayDeviceLocked(
1432 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001440 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1441 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001442 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
David Sodman105b7dc2017-11-04 20:28:14 -07001444 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1445 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001446
1447 if (vrFlingerRequestsDisplay) {
1448 mVrFlinger->GrantDisplayOwnership();
1449 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
1453 mVisibleRegionsDirty = true;
1454 invalidateHwcGeometry();
1455
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1458 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1459 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001462 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 const nsecs_t period = activeConfig->getVsyncPeriod();
1464 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Use phase of 0 since phase is not known.
1467 // Use latency of 0, which will snap to the ideal latency.
1468 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001469
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 android_atomic_or(1, &mRepaintEverything);
1471 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472}
1473
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001475 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001476 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001478 bool frameMissed = !mHadClientComposition &&
1479 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480 (mPreviousPresentFence->getSignalTime() ==
1481 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001482 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001483 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001484 mTimeStats.incrementMissedFrames();
1485 if (mPropagateBackpressure) {
1486 signalLayerUpdate();
1487 break;
1488 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001489 }
Dan Stoza50182882016-07-08 12:02:20 -07001490
Steven Thomas050b2c82017-03-06 11:45:16 -08001491 // Now that we're going to make it to the handleMessageTransaction()
1492 // call below it's safe to call updateVrFlinger(), which will
1493 // potentially trigger a display handoff.
1494 updateVrFlinger();
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 bool refreshNeeded = handleMessageTransaction();
1497 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001498 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001500 // Signal a refresh if a transaction modified the window state,
1501 // a new buffer was latched, or if HWC has requested a full
1502 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 signalRefresh();
1504 }
1505 break;
1506 }
1507 case MessageQueue::REFRESH: {
1508 handleMessageRefresh();
1509 break;
1510 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 }
1512}
1513
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001515 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001517 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526}
1527
1528void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001530
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = false;
1532
Pablo Ceballos40845df2016-01-25 17:41:15 -08001533 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001534
Brian Andersond6927fb2016-07-23 23:37:30 -07001535 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536 rebuildLayerStacks();
1537 setUpHWComposer();
1538 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001539 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001540 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001541 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001543
David Sodman105b7dc2017-11-04 20:28:14 -07001544 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001545
1546 mHadClientComposition = false;
1547 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1548 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1549 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001550 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001551 }
Dan Stoza2713c302018-03-28 17:07:36 -07001552 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001553
Dan Stoza9e56aa02015-11-02 13:00:03 -08001554 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001556
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557void SurfaceFlinger::doDebugFlashRegions()
1558{
1559 // is debugging enabled
1560 if (CC_LIKELY(!mDebugRegion))
1561 return;
1562
1563 const bool repaintEverything = mRepaintEverything;
1564 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1565 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001566 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 // transform the dirty region into this screen's coordinate space
1568 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1569 if (!dirtyRegion.isEmpty()) {
1570 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001571 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572
1573 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001575 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001576 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1577
Mathias Agopianda27af92012-09-13 18:17:13 -07001578 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579 }
1580 }
1581 }
1582
1583 postFramebuffer();
1584
1585 if (mDebugRegion > 1) {
1586 usleep(mDebugRegion * 1000);
1587 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001588
Dan Stoza9e56aa02015-11-02 13:00:03 -08001589 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001590 auto& displayDevice = mDisplays[displayId];
1591 if (!displayDevice->isDisplayOn()) {
1592 continue;
1593 }
1594
David Sodman105b7dc2017-11-04 20:28:14 -07001595 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1596 ALOGE_IF(result != NO_ERROR,
1597 "prepareFrame for display %zd failed:"
1598 " %d (%s)",
1599 displayId, 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 Zhang068e31b2018-02-21 13:02:45 -08001611void SurfaceFlinger::logLayerStats() {
1612 ATRACE_CALL();
1613 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1614 int32_t hwcId = -1;
1615 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1616 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1617 if (displayDevice->isPrimary()) {
1618 hwcId = displayDevice->getHwcDisplayId();
1619 break;
1620 }
1621 }
1622 if (hwcId < 0) {
1623 ALOGE("LayerStats: Hmmm, no primary display?");
1624 return;
1625 }
1626 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1627 }
1628}
1629
Brian Andersond6927fb2016-07-23 23:37:30 -07001630void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001632 ATRACE_CALL();
1633 ALOGV("preComposition");
1634
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001636 mDrawingState.traverseInZOrder([&](Layer* layer) {
1637 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 needExtraInvalidate = true;
1639 }
Robert Carr2047fae2016-11-28 14:09:09 -08001640 });
1641
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642 if (needExtraInvalidate) {
1643 signalLayerUpdate();
1644 }
1645}
1646
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647void SurfaceFlinger::updateCompositorTiming(
1648 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1649 std::shared_ptr<FenceTime>& presentFenceTime) {
1650 // Update queue of past composite+present times and determine the
1651 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001652 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001654 while (!getBE().mCompositePresentTimes.empty()) {
1655 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 // Cached values should have been updated before calling this method,
1657 // which helps avoid duplicate syscalls.
1658 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1659 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1660 break;
1661 }
1662 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001663 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 }
1665
1666 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001667 while (getBE().mCompositePresentTimes.size() > 16) {
1668 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 }
1670
Brian Andersond0010582017-03-07 13:20:31 -08001671 setCompositorTimingSnapped(
1672 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1673}
1674
1675void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1676 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 // Integer division and modulo round toward 0 not -inf, so we need to
1678 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001679 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1681 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1682
Brian Andersond0010582017-03-07 13:20:31 -08001683 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1684 if (idealLatency <= 0) {
1685 idealLatency = vsyncInterval;
1686 }
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 // Snap the latency to a value that removes scheduling jitter from the
1689 // composition and present times, which often have >1ms of jitter.
1690 // Reducing jitter is important if an app attempts to extrapolate
1691 // something (such as user input) to an accurate diasplay time.
1692 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1693 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001694 nsecs_t bias = vsyncInterval / 2;
1695 int64_t extraVsyncs =
1696 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1697 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1698 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001699
David Sodman99974d22017-11-28 12:04:33 -08001700 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1701 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1702 getBE().mCompositorTiming.interval = vsyncInterval;
1703 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704}
1705
1706void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 ATRACE_CALL();
1709 ALOGV("postComposition");
1710
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001712 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001714 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001715 }
1716
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 // |mStateLock| not needed as we are on the main thread
1718 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001722 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 glCompositionDoneFenceTime =
1724 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 } else {
1727 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1728 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729
David Sodman73beded2017-11-15 11:56:06 -08001730 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001731 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001732 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001734
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1736 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1737
1738 // We use the refreshStartTime which might be sampled a little later than
1739 // when we started doing work for this frame, but that should be okay
1740 // since updateCompositorTiming has snapping logic.
1741 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001742 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001743 CompositorTiming compositorTiming;
1744 {
David Sodman99974d22017-11-28 12:04:33 -08001745 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1746 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001747 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748
Robert Carr2047fae2016-11-28 14:09:09 -08001749 mDrawingState.traverseInZOrder([&](Layer* layer) {
1750 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001751 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001752 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001753 recordBufferingStats(layer->getName().string(),
1754 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001755 }
Robert Carr2047fae2016-11-28 14:09:09 -08001756 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001757
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001758 if (presentFenceTime->isValid()) {
1759 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001760 enableHardwareVsync();
1761 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001762 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001763 }
1764 }
1765
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001766 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001767 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001768 enableHardwareVsync();
1769 }
1770 }
1771
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001772 if (mAnimCompositionPending) {
1773 mAnimCompositionPending = false;
1774
Brian Anderson4e606e32017-03-16 15:34:57 -07001775 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001777 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001778 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001779 // The HWC doesn't support present fences, so use the refresh
1780 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001781 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001782 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001783 mAnimFrameTracker.setActualPresentTime(presentTime);
1784 }
1785 mAnimFrameTracker.advanceFrame();
1786 }
Dan Stozab90cf072015-03-05 11:05:59 -08001787
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001788 mTimeStats.incrementTotalFrames();
1789 if (mHadClientComposition) {
1790 mTimeStats.incrementClientCompositionFrames();
1791 }
1792
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001793 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1794 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001795 return;
1796 }
1797
1798 nsecs_t currentTime = systemTime();
1799 if (mHasPoweredOff) {
1800 mHasPoweredOff = false;
1801 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001802 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001804 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1805 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001810 }
David Sodman4a36e932017-11-07 14:29:47 -08001811 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812}
1813
1814void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("rebuildLayerStacks");
1817
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001820 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 mVisibleRegionsDirty = false;
1822 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823
Jeff Sharkey76488112017-02-27 14:15:18 -07001824 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1825 Region opaqueRegion;
1826 Region dirtyRegion;
1827 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001828 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1830 const Transform& tr(displayDevice->getTransform());
1831 const Rect bounds(displayDevice->getBounds());
1832 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001833 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001836 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001837 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1838 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 Region drawRegion(tr.transform(
1840 layer->visibleNonTransparentRegion));
1841 drawRegion.andSelf(bounds);
1842 if (!drawRegion.isEmpty()) {
1843 layersSortedByZ.add(layer);
1844 } else {
1845 // Clear out the HWC layer if this layer was
1846 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001847 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001848 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001850 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001851 // WM changes displayDevice->layerStack upon sleep/awake.
1852 // Here we make sure we delete the HWC layers even if
1853 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001854 hwcLayerDestroyed = layer->destroyHwcLayer(
1855 displayDevice->getHwcDisplayId());
1856 }
1857
1858 // If a layer is not going to get a release fence because
1859 // it is invisible, but it is also going to release its
1860 // old buffer, add it to the list of layers needing
1861 // fences.
1862 if (hwcLayerDestroyed) {
1863 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1864 mLayersWithQueuedFrames.cend(), layer);
1865 if (found != mLayersWithQueuedFrames.cend()) {
1866 layersNeedingFences.add(layer);
1867 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 });
1870 }
1871 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001872 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 displayDevice->undefinedRegion.set(bounds);
1874 displayDevice->undefinedRegion.subtractSelf(
1875 tr.transform(opaqueRegion));
1876 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001877 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001880
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001881// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001883// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001885// The returned HDR data space is one of
1886// - Dataspace::UNKNOWN
1887// - Dataspace::BT2020_HLG
1888// - Dataspace::BT2020_PQ
1889Dataspace SurfaceFlinger::getBestDataspace(
1890 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1891 Dataspace bestDataSpace = Dataspace::SRGB;
1892 *outHdrDataSpace = Dataspace::UNKNOWN;
1893
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001895 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 case Dataspace::V0_SCRGB:
1897 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001898 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001899 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001900 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901 case Dataspace::BT2020_PQ:
1902 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001903 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001905 case Dataspace::BT2020_HLG:
1906 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001907 // When there's mixed PQ content and HLG content, we set the HDR
1908 // data space to be BT2020_PQ and convert HLG to PQ.
1909 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1910 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001911 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 break;
1913 default:
1914 break;
1915 }
Romain Guy54f154a2017-10-24 21:40:32 +01001916 }
1917
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001918 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001919}
1920
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001923 ColorMode* outMode, Dataspace* outDataSpace,
1924 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1926 *outMode = ColorMode::NATIVE;
1927 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001928 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001930 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001931
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001932 Dataspace hdrDataSpace;
1933 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1934
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001935 // respect hdrDataSpace only when there is modern HDR support
1936 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
1937 displayDevice->hasModernHdrSupport(hdrDataSpace);
1938 if (isHdr) {
1939 bestDataSpace = hdrDataSpace;
1940 }
1941
Chia-I Wu0d711262018-05-21 15:19:35 -07001942 RenderIntent intent;
1943 switch (mDisplayColorSetting) {
1944 case DisplayColorSetting::MANAGED:
1945 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001946 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001947 break;
1948 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001949 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001950 break;
1951 default: // vendor display color setting
1952 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1953 break;
1954 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001955
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001956 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001957}
1958
Mathias Agopiancd60f992012-08-16 16:28:27 -07001959void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 ATRACE_CALL();
1961 ALOGV("setUpHWComposer");
1962
Jesse Hall028dc8f2013-08-20 16:35:32 -07001963 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001964 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001965 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1966 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1967
1968 // If nothing has changed (!dirty), don't recompose.
1969 // If something changed, but we don't currently have any visible layers,
1970 // and didn't when we last did a composition, then skip it this time.
1971 // The second rule does two things:
1972 // - When all layers are removed from a display, we'll emit one black
1973 // frame, then nothing more until we get new layers.
1974 // - When a display is created with a private layer stack, we won't
1975 // emit any black frames until a layer is added to the layer stack.
1976 bool mustRecompose = dirty && !(empty && wasEmpty);
1977
1978 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1979 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1980 mustRecompose ? "doing" : "skipping",
1981 dirty ? "+" : "-",
1982 empty ? "+" : "-",
1983 wasEmpty ? "+" : "-");
1984
Dan Stoza71433162014-02-04 16:22:36 -08001985 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001986
1987 if (mustRecompose) {
1988 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1989 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001990 }
1991
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 // build the h/w work list
1993 if (CC_UNLIKELY(mGeometryInvalid)) {
1994 mGeometryInvalid = false;
1995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1996 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1997 const auto hwcId = displayDevice->getHwcDisplayId();
1998 if (hwcId >= 0) {
1999 const Vector<sp<Layer>>& currentLayers(
2000 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002001 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002002 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002004 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002007 }
2008 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002009
Robert Carrae060832016-11-28 10:51:00 -08002010 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002011 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002013 }
2014 }
2015 }
2016 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 }
Riley Andrews03414a12014-07-01 14:22:59 -07002018
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 // Set the per-frame data
2020 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2021 auto& displayDevice = mDisplays[displayId];
2022 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002023
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 if (hwcId < 0) {
2025 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002026 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002027 if (mDrawingState.colorMatrixChanged) {
2028 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2029 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002030 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2031 "display %zd: %d", displayId, result);
2032 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002034 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2035 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002036 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002037 layer->forceClientComposition(hwcId);
2038 }
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002039 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2040 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002041 !displayDevice->hasHLGSupport()) {
2042 layer->forceClientComposition(hwcId);
2043 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002044
chaviwc9232ed2017-11-14 15:31:15 -08002045 if (layer->getForceClientComposition(hwcId)) {
2046 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2047 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2048 continue;
2049 }
2050
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 layer->setPerFrameData(displayDevice);
2052 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002053
2054 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002055 ColorMode colorMode;
2056 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002057 RenderIntent renderIntent;
2058 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2059 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002060 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 }
2062
Chia-I Wu28f320b2018-05-03 11:02:56 -07002063 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002064
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002066 auto& displayDevice = mDisplays[displayId];
2067 if (!displayDevice->isDisplayOn()) {
2068 continue;
2069 }
2070
David Sodman105b7dc2017-11-04 20:28:14 -07002071 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2073 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002074 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002075}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076
Mathias Agopiancd60f992012-08-16 16:28:27 -07002077void SurfaceFlinger::doComposition() {
2078 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 ALOGV("doComposition");
2080
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002081 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002082 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002083 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002084 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002085 // transform the dirty region into this screen's coordinate space
2086 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002087
2088 // repaint the framebuffer (if needed)
2089 doDisplayComposition(hw, dirtyRegion);
2090
Mathias Agopiancd60f992012-08-16 16:28:27 -07002091 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002092 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002093 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002095 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096}
2097
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098void SurfaceFlinger::postFramebuffer()
2099{
Mathias Agopian841cde52012-03-01 15:44:37 -08002100 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002102
Mathias Agopiana44b0412011-10-16 18:46:35 -07002103 const nsecs_t now = systemTime();
2104 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002105
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2107 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002108 if (!displayDevice->isDisplayOn()) {
2109 continue;
2110 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 const auto hwcId = displayDevice->getHwcDisplayId();
2112 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002113 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002114 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002115 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002116 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002118 // The layer buffer from the previous frame (if any) is released
2119 // by HWC only when the release fence from this frame (if any) is
2120 // signaled. Always get the release fence from HWC first.
2121 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002122 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002123
2124 // If the layer was client composited in the previous frame, we
2125 // need to merge with the previous client target acquire fence.
2126 // Since we do not track that, always merge with the current
2127 // client target acquire fence when it is available, even though
2128 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002130 releaseFence = Fence::merge("LayerRelease", releaseFence,
2131 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002132 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002133
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 layer->onLayerDisplayed(releaseFence);
2135 }
Chia-I Wu83806892017-11-16 10:50:20 -08002136
2137 // We've got a list of layers needing fences, that are disjoint with
2138 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2139 // supply them with the present fence.
2140 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002141 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002142 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2143 layer->onLayerDisplayed(presentFence);
2144 }
2145 }
2146
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002148 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002149 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002150 }
2151
Mathias Agopiana44b0412011-10-16 18:46:35 -07002152 mLastSwapBufferTime = systemTime() - now;
2153 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002154
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002155 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002156 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2157 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2158 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2159 logFrameStats();
2160 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162}
2163
Mathias Agopian87baae12012-07-31 12:38:26 -07002164void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165{
Mathias Agopian841cde52012-03-01 15:44:37 -08002166 ATRACE_CALL();
2167
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002168 // here we keep a copy of the drawing state (that is the state that's
2169 // going to be overwritten by handleTransactionLocked()) outside of
2170 // mStateLock so that the side-effects of the State assignment
2171 // don't happen with mStateLock held (which can cause deadlocks).
2172 State drawingState(mDrawingState);
2173
Mathias Agopianca4d3602011-05-19 15:38:14 -07002174 Mutex::Autolock _l(mStateLock);
2175 const nsecs_t now = systemTime();
2176 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177
Mathias Agopianca4d3602011-05-19 15:38:14 -07002178 // Here we're guaranteed that some transaction flags are set
2179 // so we can call handleTransactionLocked() unconditionally.
2180 // We call getTransactionFlags(), which will also clear the flags,
2181 // with mStateLock held to guarantee that mCurrentState won't change
2182 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002183
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002184 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002185 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002186 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002187
Mathias Agopianca4d3602011-05-19 15:38:14 -07002188 mLastTransactionTime = systemTime() - now;
2189 mDebugInTransaction = 0;
2190 invalidateHwcGeometry();
2191 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002192}
2193
Lloyd Pique715a2c12017-12-14 17:18:08 -08002194DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002195 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002196 // Figure out whether the event is for the primary display or an
2197 // external display by matching the Hwc display id against one for a
2198 // connected display. If we did not find a match, we then check what
2199 // displays are not already connected to determine the type. If we don't
2200 // have a connected primary display, we assume the new display is meant to
2201 // be the primary display, and then if we don't have an external display,
2202 // we assume it is that.
2203 const auto primaryDisplayId =
2204 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2205 const auto externalDisplayId =
2206 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2207 if (primaryDisplayId && primaryDisplayId == display) {
2208 return DisplayDevice::DISPLAY_PRIMARY;
2209 } else if (externalDisplayId && externalDisplayId == display) {
2210 return DisplayDevice::DISPLAY_EXTERNAL;
2211 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2212 return DisplayDevice::DISPLAY_PRIMARY;
2213 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2214 return DisplayDevice::DISPLAY_EXTERNAL;
2215 }
2216
2217 return DisplayDevice::DISPLAY_ID_INVALID;
2218}
2219
Lloyd Piqueba04e622017-12-14 17:11:26 -08002220void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2221 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002222 auto displayType = determineDisplayType(event.display, event.connection);
2223 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2224 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2225 continue;
2226 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002227
2228 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2229 ALOGE("External displays are not supported by the vr hardware composer.");
2230 continue;
2231 }
2232
Lloyd Pique715a2c12017-12-14 17:18:08 -08002233 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234
2235 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002236 if (!mBuiltinDisplays[displayType].get()) {
2237 ALOGV("Creating built in display %d", displayType);
2238 mBuiltinDisplays[displayType] = new BBinder();
2239 // All non-virtual displays are currently considered secure.
2240 DisplayDeviceState info(displayType, true);
2241 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2242 "Built-in Screen" : "External Screen";
2243 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002244 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002245 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002246 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002247 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002248
Lloyd Piquefcd86612017-12-14 17:15:36 -08002249 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2250 if (idx >= 0) {
2251 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002252 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002253 mCurrentState.displays.removeItemsAt(idx);
2254 }
2255 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002256 }
2257
2258 processDisplayChangesLocked();
2259 }
2260
2261 mPendingHotplugEvents.clear();
2262}
2263
Lloyd Pique09594832018-01-22 17:48:03 -08002264sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2265 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2266 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002268 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002269
Lloyd Pique09594832018-01-22 17:48:03 -08002270 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002272 for (ColorMode colorMode : modes) {
2273 switch (colorMode) {
2274 case ColorMode::DISPLAY_P3:
2275 case ColorMode::ADOBE_RGB:
2276 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002278 break;
2279 default:
2280 break;
2281 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282
2283 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2284 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002285 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002286 }
2287 }
2288
Peiyong Lin62665892018-04-16 11:07:44 -07002289 HdrCapabilities hdrCapabilities;
2290 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002291
2292 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2293 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2294
2295 /*
2296 * Create our display's surface
2297 */
2298 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2299 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2300 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2301 renderSurface->setNativeWindow(nativeWindow.get());
2302 const int displayWidth = renderSurface->queryWidth();
2303 const int displayHeight = renderSurface->queryHeight();
2304
2305 // Make sure that composition can never be stalled by a virtual display
2306 // consumer that isn't processing buffers fast enough. We have to do this
2307 // in two places:
2308 // * Here, in case the display is composed entirely by HWC.
2309 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2310 // window's swap interval in eglMakeCurrent, so they'll override the
2311 // interval we set here.
2312 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2313 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2314 }
2315
2316 // virtual displays are always considered enabled
2317 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2318 : HWC_POWER_MODE_OFF;
2319
2320 sp<DisplayDevice> hw =
2321 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2322 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002323 hasWideColorGamut, hdrCapabilities,
2324 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002325 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002326
2327 if (maxFrameBufferAcquiredBuffers >= 3) {
2328 nativeWindowSurface->preallocateBuffers();
2329 }
2330
2331 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2333 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002334 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002335 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002336 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002337 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2338 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002339 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2340 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2341 }
Lloyd Pique09594832018-01-22 17:48:03 -08002342 hw->setLayerStack(state.layerStack);
2343 hw->setProjection(state.orientation, state.viewport, state.frame);
2344 hw->setDisplayName(state.displayName);
2345
2346 return hw;
2347}
2348
Lloyd Pique347200f2017-12-14 17:00:15 -08002349void SurfaceFlinger::processDisplayChangesLocked() {
2350 // here we take advantage of Vector's copy-on-write semantics to
2351 // improve performance by skipping the transaction entirely when
2352 // know that the lists are identical
2353 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2354 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2355 if (!curr.isIdenticalTo(draw)) {
2356 mVisibleRegionsDirty = true;
2357 const size_t cc = curr.size();
2358 size_t dc = draw.size();
2359
2360 // find the displays that were removed
2361 // (ie: in drawing state but not in current state)
2362 // also handle displays that changed
2363 // (ie: displays that are in both lists)
2364 for (size_t i = 0; i < dc;) {
2365 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2366 if (j < 0) {
2367 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002368 // Call makeCurrent() on the primary display so we can
2369 // be sure that nothing associated with this display
2370 // is current.
2371 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2372 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2373 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2374 if (hw != nullptr) hw->disconnect(getHwComposer());
2375 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2376 mEventThread->onHotplugReceived(draw[i].type, false);
2377 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 } else {
2379 // this display is in both lists. see if something changed.
2380 const DisplayDeviceState& state(curr[j]);
2381 const wp<IBinder>& display(curr.keyAt(j));
2382 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2383 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2384 if (state_binder != draw_binder) {
2385 // changing the surface is like destroying and
2386 // recreating the DisplayDevice, so we just remove it
2387 // from the drawing state, so that it get re-added
2388 // below.
2389 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2390 if (hw != nullptr) hw->disconnect(getHwComposer());
2391 mDisplays.removeItem(display);
2392 mDrawingState.displays.removeItemsAt(i);
2393 dc--;
2394 // at this point we must loop to the next item
2395 continue;
2396 }
2397
2398 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2399 if (disp != nullptr) {
2400 if (state.layerStack != draw[i].layerStack) {
2401 disp->setLayerStack(state.layerStack);
2402 }
2403 if ((state.orientation != draw[i].orientation) ||
2404 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2405 disp->setProjection(state.orientation, state.viewport, state.frame);
2406 }
2407 if (state.width != draw[i].width || state.height != draw[i].height) {
2408 disp->setDisplaySize(state.width, state.height);
2409 }
2410 }
2411 }
2412 ++i;
2413 }
2414
2415 // find displays that were added
2416 // (ie: in current state but not in drawing state)
2417 for (size_t i = 0; i < cc; i++) {
2418 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2419 const DisplayDeviceState& state(curr[i]);
2420
2421 sp<DisplaySurface> dispSurface;
2422 sp<IGraphicBufferProducer> producer;
2423 sp<IGraphicBufferProducer> bqProducer;
2424 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002425 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002426
2427 int32_t hwcId = -1;
2428 if (state.isVirtualDisplay()) {
2429 // Virtual displays without a surface are dormant:
2430 // they have external state (layer stack, projection,
2431 // etc.) but no internal state (i.e. a DisplayDevice).
2432 if (state.surface != nullptr) {
2433 // Allow VR composer to use virtual displays.
2434 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2435 int width = 0;
2436 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2437 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2438 int height = 0;
2439 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2440 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2441 int intFormat = 0;
2442 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2443 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002444 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445
2446 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2447 }
2448
2449 // TODO: Plumb requested format back up to consumer
2450
2451 sp<VirtualDisplaySurface> vds =
2452 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2453 bqProducer, bqConsumer,
2454 state.displayName);
2455
2456 dispSurface = vds;
2457 producer = vds;
2458 }
2459 } else {
2460 ALOGE_IF(state.surface != nullptr,
2461 "adding a supported display, but rendering "
2462 "surface is provided (%p), ignoring it",
2463 state.surface.get());
2464
2465 hwcId = state.type;
2466 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2467 producer = bqProducer;
2468 }
2469
2470 const wp<IBinder>& display(curr.keyAt(i));
2471 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002472 mDisplays.add(display,
2473 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2474 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002475 if (!state.isVirtualDisplay()) {
2476 mEventThread->onHotplugReceived(state.type, true);
2477 }
2478 }
2479 }
2480 }
2481 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002482
2483 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002484}
2485
Mathias Agopian87baae12012-07-31 12:38:26 -07002486void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002487{
Dan Stoza7dde5992015-05-22 09:51:44 -07002488 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002489 mCurrentState.traverseInZOrder([](Layer* layer) {
2490 layer->notifyAvailableFrames();
2491 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 /*
2494 * Traversal of the children
2495 * (perform the transaction for each of them if needed)
2496 */
2497
Mathias Agopian3559b072012-08-15 13:46:03 -07002498 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002499 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002501 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
2503 const uint32_t flags = layer->doTransaction(0);
2504 if (flags & Layer::eVisibleRegion)
2505 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002506 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507 }
2508
2509 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002510 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511 */
2512
Mathias Agopiane57f2922012-08-09 16:29:12 -07002513 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002515 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002518 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002519 // The transform hint might have changed for some layers
2520 // (either because a display has changed, or because a layer
2521 // as changed).
2522 //
2523 // Walk through all the layers in currentLayers,
2524 // and update their transform hint.
2525 //
2526 // If a layer is visible only on a single display, then that
2527 // display is used to calculate the hint, otherwise we use the
2528 // default display.
2529 //
2530 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2531 // the hint is set before we acquire a buffer from the surface texture.
2532 //
2533 // NOTE: layer transactions have taken place already, so we use their
2534 // drawing state. However, SurfaceFlinger's own transaction has not
2535 // happened yet, so we must use the current state layer list
2536 // (soon to become the drawing state list).
2537 //
2538 sp<const DisplayDevice> disp;
2539 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002540 bool first = true;
2541 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002542 // NOTE: we rely on the fact that layers are sorted by
2543 // layerStack first (so we don't have to traverse the list
2544 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002546 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002547 currentlayerStack = layerStack;
2548 // figure out if this layerstack is mirrored
2549 // (more than one display) if so, pick the default display,
2550 // if not, pick the only display it's on.
2551 disp.clear();
2552 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2553 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002554 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002555 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002556 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002557 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002558 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002559 break;
2560 }
2561 }
2562 }
2563 }
Chet Haase91d25932013-04-11 15:24:55 -07002564
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002565 if (disp == nullptr) {
2566 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2567 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002568
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002569 // could be null when this layer is using a layerStack
2570 // that is not visible on any display. Also can occur at
2571 // screen off/on times.
2572 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002573 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002574
2575 // disp can be null if there is no display available at all to get
2576 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002577 if (disp != nullptr) {
2578 layer->updateTransformHint(disp);
2579 }
Robert Carr2047fae2016-11-28 14:09:09 -08002580
2581 first = false;
2582 });
Mathias Agopian84300952012-11-21 16:02:13 -08002583 }
2584
2585
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 /*
2587 * Perform our own transaction if needed
2588 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002589
2590 if (mLayersAdded) {
2591 mLayersAdded = false;
2592 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002593 mVisibleRegionsDirty = true;
2594 }
2595
2596 // some layers might have been removed, so
2597 // we need to update the regions they're exposing.
2598 if (mLayersRemoved) {
2599 mLayersRemoved = false;
2600 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002601 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002602 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002603 // this layer is not visible anymore
2604 // TODO: we could traverse the tree from front to back and
2605 // compute the actual visible region
2606 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607 Region visibleReg;
2608 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002609 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002610 }
Robert Carr2047fae2016-11-28 14:09:09 -08002611 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 }
2613
2614 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002615
2616 updateCursorAsync();
2617}
2618
2619void SurfaceFlinger::updateCursorAsync()
2620{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2622 auto& displayDevice = mDisplays[displayId];
2623 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002624 continue;
2625 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002626
2627 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2628 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002629 }
2630 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631}
2632
2633void SurfaceFlinger::commitTransaction()
2634{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002635 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002636 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 for (const auto& l : mLayersPendingRemoval) {
2638 recordBufferingStats(l->getName().string(),
2639 l->getOccupancyHistory(true));
2640 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002641 }
2642 mLayersPendingRemoval.clear();
2643 }
2644
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002645 // If this transaction is part of a window animation then the next frame
2646 // we composite should be considered an animation as well.
2647 mAnimCompositionPending = mAnimTransactionPending;
2648
Mathias Agopian4fec8732012-06-29 14:12:52 -07002649 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002650 // clear the "changed" flags in current state
2651 mCurrentState.colorMatrixChanged = false;
2652
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 mDrawingState.traverseInZOrder([](Layer* layer) {
2654 layer->commitChildList();
2655 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002656 mTransactionPending = false;
2657 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002658 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659}
2660
Chia-I Wuab0c3192017-08-01 11:29:00 -07002661void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002662 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663{
Mathias Agopian841cde52012-03-01 15:44:37 -08002664 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002666
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 Region aboveOpaqueLayers;
2668 Region aboveCoveredLayers;
2669 Region dirty;
2670
Mathias Agopian87baae12012-07-31 12:38:26 -07002671 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672
Robert Carr2047fae2016-11-28 14:09:09 -08002673 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002675 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676
Jesse Hall01e29052013-02-19 16:13:35 -08002677 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002678 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002679 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002680
Mathias Agopianab028732010-03-16 16:41:46 -07002681 /*
2682 * opaqueRegion: area of a surface that is fully opaque.
2683 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002685
2686 /*
2687 * visibleRegion: area of a surface that is visible on screen
2688 * and not fully transparent. This is essentially the layer's
2689 * footprint minus the opaque regions above it.
2690 * Areas covered by a translucent surface are considered visible.
2691 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002693
2694 /*
2695 * coveredRegion: area of a surface that is covered by all
2696 * visible regions above it (which includes the translucent areas).
2697 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002699
Jesse Halla8026d22012-09-25 13:25:04 -07002700 /*
2701 * transparentRegion: area of a surface that is hinted to be completely
2702 * transparent. This is only used to tell when the layer has no visible
2703 * non-transparent regions and can be removed from the layer list. It
2704 * does not affect the visibleRegion of this layer or any layers
2705 * beneath it. The hint may not be correct if apps don't respect the
2706 * SurfaceView restrictions (which, sadly, some don't).
2707 */
2708 Region transparentRegion;
2709
Mathias Agopianab028732010-03-16 16:41:46 -07002710
2711 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002712 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002713 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002714 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002717 if (!visibleRegion.isEmpty()) {
2718 // Remove the transparent area from the visible region
2719 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002720 if (tr.preserveRects()) {
2721 // transform the transparent region
2722 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002724 // transformation too complex, can't do the
2725 // transparent region optimization.
2726 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002727 }
Mathias Agopianab028732010-03-16 16:41:46 -07002728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729
Mathias Agopianab028732010-03-16 16:41:46 -07002730 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002732 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002733 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2734 // the opaque region is the layer's footprint
2735 opaqueRegion = visibleRegion;
2736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 }
2738 }
2739
Robert Carre5f4f692018-01-12 13:12:28 -08002740 if (visibleRegion.isEmpty()) {
2741 layer->clearVisibilityRegions();
2742 return;
2743 }
2744
Mathias Agopianab028732010-03-16 16:41:46 -07002745 // Clip the covered region to the visible region
2746 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2747
2748 // Update aboveCoveredLayers for next (lower) layer
2749 aboveCoveredLayers.orSelf(visibleRegion);
2750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 // subtract the opaque region covered by the layers above us
2752 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753
2754 // compute this layer's dirty region
2755 if (layer->contentDirty) {
2756 // we need to invalidate the whole region
2757 dirty = visibleRegion;
2758 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 layer->contentDirty = false;
2761 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002762 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002763 * the exposed region consists of two components:
2764 * 1) what's VISIBLE now and was COVERED before
2765 * 2) what's EXPOSED now less what was EXPOSED before
2766 *
2767 * note that (1) is conservative, we start with the whole
2768 * visible region but only keep what used to be covered by
2769 * something -- which mean it may have been exposed.
2770 *
2771 * (2) handles areas that were not covered by anything but got
2772 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002773 */
Mathias Agopianab028732010-03-16 16:41:46 -07002774 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 const Region oldVisibleRegion = layer->visibleRegion;
2776 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002777 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2778 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 }
2780 dirty.subtractSelf(aboveOpaqueLayers);
2781
2782 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002783 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784
Mathias Agopianab028732010-03-16 16:41:46 -07002785 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002787
Jesse Halla8026d22012-09-25 13:25:04 -07002788 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 layer->setVisibleRegion(visibleRegion);
2790 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002791 layer->setVisibleNonTransparentRegion(
2792 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002793 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794
Mathias Agopian87baae12012-07-31 12:38:26 -07002795 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796}
2797
Chia-I Wuab0c3192017-08-01 11:29:00 -07002798void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002799 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002800 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002801 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002802 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002803 }
2804 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002805}
2806
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 ALOGV("handlePageFlip");
2810
Brian Andersond6927fb2016-07-23 23:37:30 -07002811 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
Mathias Agopian4fec8732012-06-29 14:12:52 -07002813 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002815 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002816
2817 // Store the set of layers that need updates. This set must not change as
2818 // buffers are being latched, as this could result in a deadlock.
2819 // Example: Two producers share the same command stream and:
2820 // 1.) Layer 0 is latched
2821 // 2.) Layer 0 gets a new frame
2822 // 2.) Layer 1 gets a new frame
2823 // 3.) Layer 1 is latched.
2824 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2825 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002826 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002827 if (layer->hasQueuedFrame()) {
2828 frameQueued = true;
2829 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002830 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002831 } else {
2832 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002834 } else {
2835 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002836 }
Robert Carr2047fae2016-11-28 14:09:09 -08002837 });
2838
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002840 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002841 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002842 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002843 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002844 newDataLatched = true;
2845 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002847
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002848 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849
2850 // If we will need to wake up at some time in the future to deal with a
2851 // queued frame that shouldn't be displayed during this vsync period, wake
2852 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002853 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002854 signalLayerUpdate();
2855 }
2856
2857 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002858 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Mathias Agopianad456f92011-01-13 17:53:01 -08002861void SurfaceFlinger::invalidateHwcGeometry()
2862{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002863 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002864}
2865
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002866
Fabien Sanglard830b8472016-11-30 16:35:58 -08002867void SurfaceFlinger::doDisplayComposition(
2868 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002869 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870{
Dan Stoza71433162014-02-04 16:22:36 -08002871 // We only need to actually compose the display if:
2872 // 1) It is being handled by hardware composer, which may need this to
2873 // keep its virtual display state machine in sync, or
2874 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002875 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002876 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002878 return;
2879 }
2880
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002882 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002883
2884 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002885 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886}
2887
Chia-I Wub02087d2017-11-09 10:19:54 -08002888bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002889{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002890 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002891
Chia-I Wub02087d2017-11-09 10:19:54 -08002892 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002893 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002894 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002895 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002896 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002897
Chia-I Wu8e50e692018-05-04 10:12:37 -07002898 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002899 bool needsLegacyColorMatrix = false;
2900 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002901
Dan Stoza9e56aa02015-11-02 13:00:03 -08002902 if (hasClientComposition) {
2903 ALOGV("hasClientComposition");
2904
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002905 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002906 if (displayDevice->hasWideColorGamut()) {
2907 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002908 }
2909 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002910 getBE().mRenderEngine->setDisplayMaxLuminance(
2911 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002912
Chia-I Wu8e50e692018-05-04 10:12:37 -07002913 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2914 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2915 HWC2::Capability::SkipClientColorTransform);
2916
2917 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2918 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002919 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002920 }
2921
Chia-I Wubbb44462018-05-21 15:33:27 -07002922 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002923 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002924 outputDataspace != Dataspace::UNKNOWN &&
2925 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002926
Chia-I Wu7f402902017-11-09 12:51:10 -08002927 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002928 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002930 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002931
2932 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002933 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002934 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2935 }
2936 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002937 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002938
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002939 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002940 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002941 // when using overlays, we assume a fully transparent framebuffer
2942 // NOTE: we could reduce how much we need to clear, for instance
2943 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002944 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002945 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002946 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002947 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002948 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002949 // we're left with the letterbox region
2950 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002952
2953 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002955
Mathias Agopianb9494d52012-04-18 02:28:45 -07002956 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002957 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002958 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002960 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002961 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002962
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002964 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002965 // scissor on the main display. It should never be needed
2966 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 const Rect& bounds(displayDevice->getBounds());
2968 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002969 if (scissor != bounds) {
2970 // scissor doesn't match the screen's dimensions, so we
2971 // need to clear everything outside of it and enable
2972 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002973
Mathias Agopianf45c5102012-10-24 16:29:17 -07002974 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002976 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002977 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002978 }
2979 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002980 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002981
Mathias Agopian85d751c2012-08-29 16:59:24 -07002982 /*
2983 * and then, render the layers targeted at the framebuffer
2984 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002985
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 ALOGV("Rendering client layers");
2987 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002988 bool firstLayer = true;
2989 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2990 const Region clip(bounds.intersect(
2991 displayTransform.transform(layer->visibleRegion)));
2992 ALOGV("Layer: %s", layer->getName().string());
2993 ALOGV(" Composition type: %s",
2994 to_string(layer->getCompositionType(hwcId)).c_str());
2995 if (!clip.isEmpty()) {
2996 switch (layer->getCompositionType(hwcId)) {
2997 case HWC2::Composition::Cursor:
2998 case HWC2::Composition::Device:
2999 case HWC2::Composition::Sideband:
3000 case HWC2::Composition::SolidColor: {
3001 const Layer::State& state(layer->getDrawingState());
3002 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3003 layer->isOpaque(state) && (state.color.a == 1.0f)
3004 && hasClientComposition) {
3005 // never clear the very first layer since we're
3006 // guaranteed the FB is already cleared
3007 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003008 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003009 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003010 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003011 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003012 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003013 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3014 if (!legacyColorMatrixApplied) {
3015 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3016 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003017 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003018 } else if (legacyColorMatrixApplied) {
3019 getRenderEngine().setSaturationMatrix(mat4());
3020 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003021 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003022
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003023 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003024 break;
3025 }
3026 default:
3027 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003028 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003029 } else {
3030 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003031 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003032 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003033 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003034
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003035 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003036 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003037 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003038 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3039 getRenderEngine().setSaturationMatrix(mat4());
3040 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003041
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
Fabien Sanglard830b8472016-11-30 16:35:58 -08003047void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3048 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003049 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003050 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051}
3052
Dan Stoza7d89d062015-04-30 13:29:25 -07003053status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003054 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003055 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003056 const sp<Layer>& lbc,
3057 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003058{
Dan Stoza7d89d062015-04-30 13:29:25 -07003059 // add this layer to the current state list
3060 {
3061 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003063 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3064 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003065 return NO_MEMORY;
3066 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 if (parent == nullptr) {
3068 mCurrentState.layersSortedByZ.add(lbc);
3069 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003070 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003071 ALOGE("addClientLayer called with a removed parent");
3072 return NAME_NOT_FOUND;
3073 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003074 parent->addChild(lbc);
3075 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003076
Yiwei Zhang243b3782018-05-15 17:40:04 -07003077 if (gbc != nullptr) {
3078 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3079 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3080 mMaxGraphicBufferProducerListSize,
3081 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3082 mGraphicBufferProducerList.size(),
3083 mMaxGraphicBufferProducerListSize, mNumLayers);
3084 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003085 mLayersAdded = true;
3086 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003087 }
3088
Mathias Agopian96f08192010-06-02 23:28:45 -07003089 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003090 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003091
Dan Stoza7d89d062015-04-30 13:29:25 -07003092 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003093}
3094
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003095status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003096 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003097 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3098}
Robert Carr7f9b8992017-03-10 11:08:39 -08003099
chaviwca27f252018-02-06 16:46:39 -08003100status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3101 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003102 if (layer->isPendingRemoval()) {
3103 return NO_ERROR;
3104 }
3105
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003107 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003108 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003109 if (topLevelOnly) {
3110 return NO_ERROR;
3111 }
3112
Chia-I Wu98f1c102017-05-30 14:54:08 -07003113 sp<Layer> ancestor = p;
3114 while (ancestor->getParent() != nullptr) {
3115 ancestor = ancestor->getParent();
3116 }
3117 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3118 ALOGE("removeLayer called with a layer whose parent has been removed");
3119 return NAME_NOT_FOUND;
3120 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003121
3122 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003123 } else {
3124 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003125 }
3126
Robert Carr136e2f62017-02-08 17:54:29 -08003127 // As a matter of normal operation, the LayerCleaner will produce a second
3128 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3129 // so we will succeed in promoting it, but it's already been removed
3130 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3131 // otherwise something has gone wrong and we are leaking the layer.
3132 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3134 layer->getName().string(),
3135 (p != nullptr) ? p->getName().string() : "no-parent");
3136 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003137 } else if (index < 0) {
3138 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003139 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003140
Chia-I Wuc6657022017-08-15 11:18:17 -07003141 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142 mLayersPendingRemoval.add(layer);
3143 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003144 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 setTransactionFlags(eTransactionNeeded);
3146 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147}
3148
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003149uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003150 return android_atomic_release_load(&mTransactionFlags);
3151}
3152
Mathias Agopian3f844832013-08-07 21:24:32 -07003153uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3155}
3156
Mathias Agopian3f844832013-08-07 21:24:32 -07003157uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003158 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3159}
3160
3161uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3162 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003164 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003166 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 }
3168 return old;
3169}
3170
chaviwca27f252018-02-06 16:46:39 -08003171bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3172 for (const ComposerState& state : states) {
3173 // Here we need to check that the interface we're given is indeed
3174 // one of our own. A malicious client could give us a nullptr
3175 // IInterface, or one of its own or even one of our own but a
3176 // different type. All these situations would cause us to crash.
3177 if (state.client == nullptr) {
3178 return true;
3179 }
3180
3181 sp<IBinder> binder = IInterface::asBinder(state.client);
3182 if (binder == nullptr) {
3183 return true;
3184 }
3185
3186 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3187 return true;
3188 }
3189 }
3190 return false;
3191}
3192
Mathias Agopian8b33f032012-07-24 20:43:54 -07003193void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003194 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003195 const Vector<DisplayState>& displays,
3196 uint32_t flags)
3197{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003199 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003200 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003201
chaviwca27f252018-02-06 16:46:39 -08003202 if (containsAnyInvalidClientState(states)) {
3203 return;
3204 }
3205
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003206 if (flags & eAnimation) {
3207 // For window updates that are part of an animation we must wait for
3208 // previous animation "frames" to be handled.
3209 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003210 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003211 if (CC_UNLIKELY(err != NO_ERROR)) {
3212 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003213 // caller after a few seconds.
3214 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3215 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003216 mAnimTransactionPending = false;
3217 break;
3218 }
3219 }
3220 }
3221
chaviwca27f252018-02-06 16:46:39 -08003222 for (const DisplayState& display : displays) {
3223 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003224 }
3225
chaviwca27f252018-02-06 16:46:39 -08003226 for (const ComposerState& state : states) {
3227 transactionFlags |= setClientStateLocked(state);
3228 }
3229
3230 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3231 // as destroyed should only occur after setting all other states. This is to allow for a
3232 // child re-parent to happen before marking its original parent as destroyed (which would
3233 // then mark the child as destroyed).
3234 for (const ComposerState& state : states) {
3235 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003236 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003237
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003238 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3239 // anyway. This can be used as a flush mechanism for previous async transactions.
3240 // Empty animation transaction can be used to simulate back-pressure, so also force a
3241 // transaction for empty animation transactions.
3242 if (transactionFlags == 0 &&
3243 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003244 transactionFlags = eTransactionNeeded;
3245 }
3246
Mathias Agopian386aa982011-11-07 21:58:03 -08003247 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003248 if (mInterceptor->isEnabled()) {
3249 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003250 }
Irvel468051e2016-06-13 16:44:44 -07003251
Mathias Agopian386aa982011-11-07 21:58:03 -08003252 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003253 const auto start = (flags & eEarlyWakeup)
3254 ? VSyncModulator::TransactionStart::EARLY
3255 : VSyncModulator::TransactionStart::NORMAL;
3256 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003257
3258 // if this is a synchronous transaction, wait for it to take effect
3259 // before returning.
3260 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003261 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003262 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 if (flags & eAnimation) {
3264 mAnimTransactionPending = true;
3265 }
3266 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003267 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3268 if (CC_UNLIKELY(err != NO_ERROR)) {
3269 // just in case something goes wrong in SF, return to the
3270 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003271 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3272 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003273 break;
3274 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276 }
3277}
3278
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3280{
Jesse Hall9a143922012-10-04 16:29:19 -07003281 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3282 if (dpyIdx < 0)
3283 return 0;
3284
Mathias Agopiane57f2922012-08-09 16:29:12 -07003285 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003286 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003287 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 const uint32_t what = s.what;
3289 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003290 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003291 disp.surface = s.surface;
3292 flags |= eDisplayTransactionNeeded;
3293 }
3294 }
3295 if (what & DisplayState::eLayerStackChanged) {
3296 if (disp.layerStack != s.layerStack) {
3297 disp.layerStack = s.layerStack;
3298 flags |= eDisplayTransactionNeeded;
3299 }
3300 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003301 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003302 if (disp.orientation != s.orientation) {
3303 disp.orientation = s.orientation;
3304 flags |= eDisplayTransactionNeeded;
3305 }
3306 if (disp.frame != s.frame) {
3307 disp.frame = s.frame;
3308 flags |= eDisplayTransactionNeeded;
3309 }
3310 if (disp.viewport != s.viewport) {
3311 disp.viewport = s.viewport;
3312 flags |= eDisplayTransactionNeeded;
3313 }
3314 }
Michael Lentine47e45402014-07-18 15:34:25 -07003315 if (what & DisplayState::eDisplaySizeChanged) {
3316 if (disp.width != s.width) {
3317 disp.width = s.width;
3318 flags |= eDisplayTransactionNeeded;
3319 }
3320 if (disp.height != s.height) {
3321 disp.height = s.height;
3322 flags |= eDisplayTransactionNeeded;
3323 }
3324 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003325 }
3326 return flags;
3327}
3328
chaviwca27f252018-02-06 16:46:39 -08003329uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3330 const layer_state_t& s = composerState.state;
3331 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3332
Mathias Agopian13127d82013-03-05 17:47:11 -08003333 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003334 if (layer == nullptr) {
3335 return 0;
3336 }
3337
3338 if (layer->isPendingRemoval()) {
3339 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3340 return 0;
3341 }
3342
3343 uint32_t flags = 0;
3344
3345 const uint32_t what = s.what;
3346 bool geometryAppliesWithResize =
3347 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003348
3349 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3350 // pending state will also be deferred.
3351 if (what & layer_state_t::eDeferTransaction) {
3352 layer->pushPendingState();
3353 }
3354
chaviw8b3871a2017-11-01 17:41:01 -07003355 if (what & layer_state_t::ePositionChanged) {
3356 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3357 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003358 }
chaviw8b3871a2017-11-01 17:41:01 -07003359 }
3360 if (what & layer_state_t::eLayerChanged) {
3361 // NOTE: index needs to be calculated before we update the state
3362 const auto& p = layer->getParent();
3363 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003364 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003365 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 mCurrentState.layersSortedByZ.removeAt(idx);
3367 mCurrentState.layersSortedByZ.add(layer);
3368 // we need traversal (state changed)
3369 // AND transaction (list changed)
3370 flags |= eTransactionNeeded|eTraversalNeeded;
3371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 } else {
3373 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003374 flags |= eTransactionNeeded|eTraversalNeeded;
3375 }
3376 }
chaviw8b3871a2017-11-01 17:41:01 -07003377 }
3378 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003379 // NOTE: index needs to be calculated before we update the state
3380 const auto& p = layer->getParent();
3381 if (p == nullptr) {
3382 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3383 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3384 mCurrentState.layersSortedByZ.removeAt(idx);
3385 mCurrentState.layersSortedByZ.add(layer);
3386 // we need traversal (state changed)
3387 // AND transaction (list changed)
3388 flags |= eTransactionNeeded|eTraversalNeeded;
3389 }
3390 } else {
3391 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3392 flags |= eTransactionNeeded|eTraversalNeeded;
3393 }
chaviw8b3871a2017-11-01 17:41:01 -07003394 }
3395 }
3396 if (what & layer_state_t::eSizeChanged) {
3397 if (layer->setSize(s.w, s.h)) {
3398 flags |= eTraversalNeeded;
3399 }
3400 }
3401 if (what & layer_state_t::eAlphaChanged) {
3402 if (layer->setAlpha(s.alpha))
3403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eColorChanged) {
3406 if (layer->setColor(s.color))
3407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eMatrixChanged) {
3410 if (layer->setMatrix(s.matrix))
3411 flags |= eTraversalNeeded;
3412 }
3413 if (what & layer_state_t::eTransparentRegionChanged) {
3414 if (layer->setTransparentRegionHint(s.transparentRegion))
3415 flags |= eTraversalNeeded;
3416 }
3417 if (what & layer_state_t::eFlagsChanged) {
3418 if (layer->setFlags(s.flags, s.mask))
3419 flags |= eTraversalNeeded;
3420 }
3421 if (what & layer_state_t::eCropChanged) {
3422 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3423 flags |= eTraversalNeeded;
3424 }
3425 if (what & layer_state_t::eFinalCropChanged) {
3426 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3427 flags |= eTraversalNeeded;
3428 }
3429 if (what & layer_state_t::eLayerStackChanged) {
3430 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3431 // We only allow setting layer stacks for top level layers,
3432 // everything else inherits layer stack from its parent.
3433 if (layer->hasParent()) {
3434 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3435 layer->getName().string());
3436 } else if (idx < 0) {
3437 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3438 "that also does not appear in the top level layer list. Something"
3439 " has gone wrong.", layer->getName().string());
3440 } else if (layer->setLayerStack(s.layerStack)) {
3441 mCurrentState.layersSortedByZ.removeAt(idx);
3442 mCurrentState.layersSortedByZ.add(layer);
3443 // we need traversal (state changed)
3444 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003445 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 }
3448 if (what & layer_state_t::eDeferTransaction) {
3449 if (s.barrierHandle != nullptr) {
3450 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3451 } else if (s.barrierGbp != nullptr) {
3452 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3453 if (authenticateSurfaceTextureLocked(gbp)) {
3454 const auto& otherLayer =
3455 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3456 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3457 } else {
3458 ALOGE("Attempt to defer transaction to to an"
3459 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003460 }
3461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 // We don't trigger a traversal here because if no other state is
3463 // changed, we don't want this to cause any more work
3464 }
3465 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003466 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003467 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003468 if (!hadParent) {
3469 mCurrentState.layersSortedByZ.remove(layer);
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003472 }
chaviw8b3871a2017-11-01 17:41:01 -07003473 }
3474 if (what & layer_state_t::eReparentChildren) {
3475 if (layer->reparentChildren(s.reparentHandle)) {
3476 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003477 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 if (what & layer_state_t::eDetachChildren) {
3480 layer->detachChildren();
3481 }
3482 if (what & layer_state_t::eOverrideScalingModeChanged) {
3483 layer->setOverrideScalingMode(s.overrideScalingMode);
3484 // We don't trigger a traversal here because if no other state is
3485 // changed, we don't want this to cause any more work
3486 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003487 return flags;
3488}
3489
chaviwca27f252018-02-06 16:46:39 -08003490void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3491 const layer_state_t& state = composerState.state;
3492 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3493
3494 sp<Layer> layer(client->getLayerUser(state.surface));
3495 if (layer == nullptr) {
3496 return;
3497 }
3498
3499 if (layer->isPendingRemoval()) {
3500 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3501 return;
3502 }
3503
3504 if (state.what & layer_state_t::eDestroySurface) {
3505 removeLayerLocked(mStateLock, layer);
3506 }
3507}
3508
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003509status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003510 const String8& name,
3511 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003513 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003514 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003516 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003517 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003518 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003520 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003521
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522 status_t result = NO_ERROR;
3523
3524 sp<Layer> layer;
3525
Cody Northropbc755282017-03-31 12:00:08 -06003526 String8 uniqueName = getUniqueLayerName(name);
3527
Mathias Agopian3165cc22012-08-08 19:42:09 -07003528 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3529 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003530 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003531 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 break;
chaviw13fdc492017-06-27 12:40:18 -07003535 case ISurfaceComposerClient::eFXSurfaceColor:
3536 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003537 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003538 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 break;
3540 default:
3541 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 break;
3543 }
3544
Dan Stoza7d89d062015-04-30 13:29:25 -07003545 if (result != NO_ERROR) {
3546 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003548
Chia-I Wuab0c3192017-08-01 11:29:00 -07003549 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3550 // TODO b/64227542
3551 if (windowType == 441731) {
3552 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3553 layer->setPrimaryDisplayOnly();
3554 }
3555
Albert Chaulk479c60c2017-01-27 14:21:34 -05003556 layer->setInfo(windowType, ownerUid);
3557
Robert Carr1f0a16a2016-10-24 16:27:39 -07003558 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003559 if (result != NO_ERROR) {
3560 return result;
3561 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003562 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003563
3564 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566}
3567
Cody Northropbc755282017-03-31 12:00:08 -06003568String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3569{
3570 bool matchFound = true;
3571 uint32_t dupeCounter = 0;
3572
3573 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3574 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3575
3576 // Loop over layers until we're sure there is no matching name
3577 while (matchFound) {
3578 matchFound = false;
3579 mDrawingState.traverseInZOrder([&](Layer* layer) {
3580 if (layer->getName() == uniqueName) {
3581 matchFound = true;
3582 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3583 }
3584 });
3585 }
3586
3587 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3588
3589 return uniqueName;
3590}
3591
David Sodman0c69cad2017-08-21 12:12:51 -07003592status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595{
3596 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003597 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 case PIXEL_FORMAT_TRANSPARENT:
3599 case PIXEL_FORMAT_TRANSLUCENT:
3600 format = PIXEL_FORMAT_RGBA_8888;
3601 break;
3602 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003603 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
3605 }
3606
David Sodman0c69cad2017-08-21 12:12:51 -07003607 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3608 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003610 *handle = layer->getHandle();
3611 *gbp = layer->getProducer();
3612 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614
David Sodman0c69cad2017-08-21 12:12:51 -07003615 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617}
3618
chaviw13fdc492017-06-27 12:40:18 -07003619status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003621 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622{
chaviw13fdc492017-06-27 12:40:18 -07003623 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003626}
3627
Mathias Agopianac9fa422013-02-11 16:40:36 -08003628status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629{
Robert Carr9524cb32017-02-13 11:32:32 -08003630 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003631 status_t err = NO_ERROR;
3632 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003633 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003634 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003635 err = removeLayer(l);
3636 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3637 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003638 }
3639 return err;
3640}
3641
Mathias Agopian13127d82013-03-05 17:47:11 -08003642status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003643{
Mathias Agopian67106042013-03-14 19:18:13 -07003644 // called by ~LayerCleaner() when all references to the IBinder (handle)
3645 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003646 sp<Layer> l = layer.promote();
3647 if (l == nullptr) {
3648 // The layer has already been removed, carry on
3649 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003650 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003651 // If we have a parent, then we can continue to live as long as it does.
3652 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653}
3654
Mathias Agopianb60314a2012-04-10 22:09:54 -07003655// ---------------------------------------------------------------------------
3656
Andy McFadden13a082e2012-08-24 10:16:42 -07003657void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003658 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003659 Vector<ComposerState> state;
3660 Vector<DisplayState> displays;
3661 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.what = DisplayState::eDisplayProjectionChanged |
3663 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003664 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003667 d.frame.makeInvalid();
3668 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003669 d.width = 0;
3670 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 displays.add(d);
3672 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003673 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3674 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003675
David Sodman105b7dc2017-11-04 20:28:14 -07003676 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003677 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003679
Brian Andersond0010582017-03-07 13:20:31 -08003680 // Use phase of 0 since phase is not known.
3681 // Use latency of 0, which will snap to the ideal latency.
3682 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003683}
3684
3685void SurfaceFlinger::initializeDisplays() {
3686 class MessageScreenInitialized : public MessageBase {
3687 SurfaceFlinger* flinger;
3688 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003689 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 virtual bool handler() {
3691 flinger->onInitializeDisplays();
3692 return true;
3693 }
3694 };
3695 sp<MessageBase> msg = new MessageScreenInitialized(this);
3696 postMessageAsync(msg); // we may be called from main thread, use async message
3697}
3698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003700 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3702 this);
3703 int32_t type = hw->getDisplayType();
3704 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003705
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003707 return;
3708 }
3709
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 hw->setPowerMode(mode);
3711 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3712 ALOGW("Trying to set power mode for virtual display");
3713 return;
3714 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715
Lloyd Pique4d234852018-01-22 17:21:36 -08003716 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003717 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003718 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3719 if (idx < 0) {
3720 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3721 return;
3722 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003723 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003724 }
3725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003727 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003728 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003729 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3730 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731 // FIXME: eventthread only knows about the main display right now
3732 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003733 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003735
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003736 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003737 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003738 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003739
3740 struct sched_param param = {0};
3741 param.sched_priority = 1;
3742 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3743 ALOGW("Couldn't set SCHED_FIFO on display on");
3744 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003745 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003746 // Turn off the display
3747 struct sched_param param = {0};
3748 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3749 ALOGW("Couldn't set SCHED_OTHER on display off");
3750 }
3751
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003752 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3753 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003754 disableHardwareVsync(true); // also cancels any in-progress resync
3755
Mathias Agopiancde87a32012-09-13 14:09:01 -07003756 // FIXME: eventthread only knows about the main display right now
3757 mEventThread->onScreenReleased();
3758 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760 getHwComposer().setPowerMode(type, mode);
3761 mVisibleRegionsDirty = true;
3762 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003763 } else if (mode == HWC_POWER_MODE_DOZE ||
3764 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003765 // Update display while dozing
3766 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003767 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3768 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003769 // FIXME: eventthread only knows about the main display right now
3770 mEventThread->onScreenAcquired();
3771 resyncToHardwareVsync(true);
3772 }
3773 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3774 // Leave display going to doze
3775 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3776 disableHardwareVsync(true); // also cancels any in-progress resync
3777 // FIXME: eventthread only knows about the main display right now
3778 mEventThread->onScreenReleased();
3779 }
3780 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003782 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003783 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003785 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003786}
3787
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3789 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003790 SurfaceFlinger& mFlinger;
3791 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003792 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 MessageSetPowerMode(SurfaceFlinger& flinger,
3795 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3796 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003797 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003798 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003799 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003801 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003802 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 ALOGW("Attempt to set power mode = %d for virtual display",
3804 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003805 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003806 mFlinger.setPowerModeInternal(
3807 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003808 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 return true;
3810 }
3811 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003813 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003814}
3815
3816// ---------------------------------------------------------------------------
3817
Lloyd Pique755e3192018-01-31 16:46:15 -08003818status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3819 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003821
Mathias Agopianbd115332013-04-18 16:41:04 -07003822 IPCThreadState* ipc = IPCThreadState::self();
3823 const int pid = ipc->getCallingPid();
3824 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003825
Mathias Agopianbd115332013-04-18 16:41:04 -07003826 if ((uid != AID_SHELL) &&
3827 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003828 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003829 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003831 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003832 // (this would indicate SF is stuck, but we want to be able to
3833 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 status_t err = mStateLock.timedLock(s2ns(1));
3835 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003836 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003837 result.appendFormat(
3838 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3839 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003840 }
3841
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003842 bool dumpAll = true;
3843 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003845
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003846 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847 if ((index < numArgs) &&
3848 (args[index] == String16("--list"))) {
3849 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003850 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003851 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003852 }
3853
3854 if ((index < numArgs) &&
3855 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003857 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003858 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003860
3861 if ((index < numArgs) &&
3862 (args[index] == String16("--latency-clear"))) {
3863 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003864 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003865 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003866 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003867
3868 if ((index < numArgs) &&
3869 (args[index] == String16("--dispsync"))) {
3870 index++;
3871 mPrimaryDispSync.dump(result);
3872 dumpAll = false;
3873 }
Dan Stozab90cf072015-03-05 11:05:59 -08003874
3875 if ((index < numArgs) &&
3876 (args[index] == String16("--static-screen"))) {
3877 index++;
3878 dumpStaticScreenStats(result);
3879 dumpAll = false;
3880 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003881
3882 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003883 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003885 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003886 dumpAll = false;
3887 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003888
3889 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3890 index++;
3891 dumpWideColorInfo(result);
3892 dumpAll = false;
3893 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003894
3895 if ((index < numArgs) &&
3896 (args[index] == String16("--enable-layer-stats"))) {
3897 index++;
3898 mLayerStats.enable();
3899 dumpAll = false;
3900 }
3901
3902 if ((index < numArgs) &&
3903 (args[index] == String16("--disable-layer-stats"))) {
3904 index++;
3905 mLayerStats.disable();
3906 dumpAll = false;
3907 }
3908
3909 if ((index < numArgs) &&
3910 (args[index] == String16("--clear-layer-stats"))) {
3911 index++;
3912 mLayerStats.clear();
3913 dumpAll = false;
3914 }
3915
3916 if ((index < numArgs) &&
3917 (args[index] == String16("--dump-layer-stats"))) {
3918 index++;
3919 mLayerStats.dump(result);
3920 dumpAll = false;
3921 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003922
3923 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3924 index++;
3925 mTimeStats.parseArgs(asProto, args, index, result);
3926 dumpAll = false;
3927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003929
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003931 if (asProto) {
3932 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3933 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3934 } else {
3935 dumpAllLocked(args, index, result);
3936 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003937 }
3938
Mathias Agopian9795c422009-08-26 16:36:26 -07003939 if (locked) {
3940 mStateLock.unlock();
3941 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 }
3943 write(fd, result.string(), result.size());
3944 return NO_ERROR;
3945}
3946
Dan Stozac7014012014-02-14 15:03:43 -08003947void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3948 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949{
Robert Carr2047fae2016-11-28 14:09:09 -08003950 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003952 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953}
3954
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957{
3958 String8 name;
3959 if (index < args.size()) {
3960 name = String8(args[index]);
3961 index++;
3962 }
3963
David Sodman105b7dc2017-11-04 20:28:14 -07003964 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003965 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003966 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967
3968 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003969 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003970 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003973 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003974 }
Robert Carr2047fae2016-11-28 14:09:09 -08003975 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976 }
3977}
3978
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003980 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981{
3982 String8 name;
3983 if (index < args.size()) {
3984 name = String8(args[index]);
3985 index++;
3986 }
3987
Robert Carr2047fae2016-11-28 14:09:09 -08003988 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003990 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003991 }
Robert Carr2047fae2016-11-28 14:09:09 -08003992 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003993
Svetoslavd85084b2014-03-20 10:28:31 -07003994 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995}
3996
Jamie Gennis6547ff42013-07-16 20:12:42 -07003997// This should only be called from the main thread. Otherwise it would need
3998// the lock and should use mCurrentState rather than mDrawingState.
3999void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004000 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004002 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004003
4004 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4005}
4006
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004007void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004008{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004010
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004011 if (isLayerTripleBufferingDisabled())
4012 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004013
4014 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004015 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004016 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004017 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004018 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4019 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004020 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004021}
4022
Dan Stozab90cf072015-03-05 11:05:59 -08004023void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4024{
4025 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004026 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4027 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004028 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004029 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004030 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4031 b + 1, bucketTimeSec, percent);
4032 }
David Sodman4a36e932017-11-07 14:29:47 -08004033 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004035 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004037 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004038}
4039
Dan Stozae77c7662016-05-13 11:37:28 -07004040void SurfaceFlinger::recordBufferingStats(const char* layerName,
4041 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004042 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4043 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004044 for (const auto& segment : history) {
4045 if (!segment.usedThirdBuffer) {
4046 stats.twoBufferTime += segment.totalTime;
4047 }
4048 if (segment.occupancyAverage < 1.0f) {
4049 stats.doubleBufferedTime += segment.totalTime;
4050 } else if (segment.occupancyAverage < 2.0f) {
4051 stats.tripleBufferedTime += segment.totalTime;
4052 }
4053 ++stats.numSegments;
4054 stats.totalTime += segment.totalTime;
4055 }
4056}
4057
Brian Andersond6927fb2016-07-23 23:37:30 -07004058void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4059 result.appendFormat("Layer frame timestamps:\n");
4060
4061 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4062 const size_t count = currentLayers.size();
4063 for (size_t i=0 ; i<count ; i++) {
4064 currentLayers[i]->dumpFrameEvents(result);
4065 }
4066}
4067
Dan Stozae77c7662016-05-13 11:37:28 -07004068void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4069 result.append("Buffering stats:\n");
4070 result.append(" [Layer name] <Active time> <Two buffer> "
4071 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004072 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004073 typedef std::tuple<std::string, float, float, float> BufferTuple;
4074 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004075 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004076 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004077 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004078 if (stats.numSegments == 0) {
4079 continue;
4080 }
4081 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4082 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4083 stats.totalTime;
4084 float doubleBufferRatio = static_cast<float>(
4085 stats.doubleBufferedTime) / stats.totalTime;
4086 float tripleBufferRatio = static_cast<float>(
4087 stats.tripleBufferedTime) / stats.totalTime;
4088 sorted.insert({activeTime, {name, twoBufferRatio,
4089 doubleBufferRatio, tripleBufferRatio}});
4090 }
4091 for (const auto& sortedPair : sorted) {
4092 float activeTime = sortedPair.first;
4093 const BufferTuple& values = sortedPair.second;
4094 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4095 std::get<0>(values).c_str(), activeTime,
4096 std::get<1>(values), std::get<2>(values),
4097 std::get<3>(values));
4098 }
4099 result.append("\n");
4100}
4101
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004102void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4103 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004104 result.appendFormat("DisplayColorSetting: %s\n",
4105 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004106
4107 // TODO: print out if wide-color mode is active or not
4108
4109 for (size_t d = 0; d < mDisplays.size(); d++) {
4110 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4111 int32_t hwcId = displayDevice->getHwcDisplayId();
4112 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4113 continue;
4114 }
4115
4116 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004117 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004118 for (auto&& mode : modes) {
4119 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4120 }
4121
Peiyong Lina52f0292018-03-14 17:26:31 -07004122 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004123 result.appendFormat(" Current color mode: %s (%d)\n",
4124 decodeColorMode(currentMode).c_str(), currentMode);
4125 }
4126 result.append("\n");
4127}
4128
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004129LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004130 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004131 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4132 const State& state = useDrawing ? mDrawingState : mCurrentState;
4133 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004134 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004135 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004136 });
4137
4138 return layersProto;
4139}
4140
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004141LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4142 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004143 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004144
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004145 SizeProto* resolution = layersProto.mutable_resolution();
4146 resolution->set_w(displayDevice->getWidth());
4147 resolution->set_h(displayDevice->getHeight());
4148
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004149 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4150 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4151 layersProto.set_global_transform(
4152 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4153
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004154 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004155 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004156 LayerProto* layerProto = layersProto.add_layers();
4157 layer->writeToProto(layerProto, hwcId);
4158 }
4159 });
4160
4161 return layersProto;
4162}
4163
Mathias Agopian74d211a2013-04-22 16:55:35 +02004164void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4165 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004166{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004167 bool colorize = false;
4168 if (index < args.size()
4169 && (args[index] == String16("--color"))) {
4170 colorize = true;
4171 index++;
4172 }
4173
4174 Colorizer colorizer(colorize);
4175
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004176 // figure out if we're stuck somewhere
4177 const nsecs_t now = systemTime();
4178 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4179 const nsecs_t inTransaction(mDebugInTransaction);
4180 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4181 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4182
4183 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004184 * Dump library configuration.
4185 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004186
4187 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004188 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004189 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004190 appendSfConfigString(result);
4191 appendUiConfigString(result);
4192 appendGuiConfigString(result);
4193 result.append("\n");
4194
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004195 result.append("\nWide-Color information:\n");
4196 dumpWideColorInfo(result);
4197
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004198 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004199 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004201 result.append(SyncFeatures::getInstance().toString());
4202 result.append("\n");
4203
David Sodman105b7dc2017-11-04 20:28:14 -07004204 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004205
Andy McFadden41d67d72014-04-25 16:58:34 -07004206 colorizer.bold(result);
4207 result.append("DispSync configuration: ");
4208 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004209 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4210 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4211 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004212 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004213 result.append("\n");
4214
Dan Stozab90cf072015-03-05 11:05:59 -08004215 // Dump static screen stats
4216 result.append("\n");
4217 dumpStaticScreenStats(result);
4218 result.append("\n");
4219
Dan Stozae77c7662016-05-13 11:37:28 -07004220 dumpBufferingStats(result);
4221
Andy McFadden4803b742012-09-24 19:07:20 -07004222 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223 * Dump the visible layer list
4224 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004225 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004226 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004227 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4228 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004230
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004231 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004232 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004233 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004234 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235
4236 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004237 * Dump Display state
4238 */
4239
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004240 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004241 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004242 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004243 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4244 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004245 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004246 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004247 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004248
4249 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004250 * Dump SurfaceFlinger global state
4251 */
4252
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004254 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256
Mathias Agopian888c8222012-08-04 21:10:38 -07004257 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004258 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004259
David Sodmanbc815282017-11-05 18:57:52 -08004260 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004262 if (hw) {
4263 hw->undefinedRegion.dump(result, "undefinedRegion");
4264 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4265 hw->getOrientation(), hw->isDisplayOn());
4266 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004267 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268 " last eglSwapBuffers() time: %f us\n"
4269 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004270 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271 " refresh-rate : %f fps\n"
4272 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004273 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004274 " gpu_to_cpu_unsupported : %d\n"
4275 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004276 mLastSwapBufferTime/1000.0,
4277 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004278 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004279 1e9 / activeConfig->getVsyncPeriod(),
4280 activeConfig->getDpiX(),
4281 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004282 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283
Mathias Agopian74d211a2013-04-22 16:55:35 +02004284 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004285 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004286
Mathias Agopian74d211a2013-04-22 16:55:35 +02004287 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289
4290 /*
4291 * VSYNC state
4292 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004293 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004294 result.append("\n");
4295
4296 /*
4297 * HWC layer minidump
4298 */
4299 for (size_t d = 0; d < mDisplays.size(); d++) {
4300 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4301 int32_t hwcId = displayDevice->getHwcDisplayId();
4302 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4303 continue;
4304 }
4305
4306 result.appendFormat("Display %d HWC layers:\n", hwcId);
4307 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004308 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004309 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004310 });
Dan Stozae22aec72016-08-01 13:20:59 -07004311 result.append("\n");
4312 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
4314 /*
4315 * Dump HWComposer state
4316 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004317 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004318 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004319 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004320 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004321 result.appendFormat(" h/w composer %s\n",
4322 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004323 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324
4325 /*
4326 * Dump gralloc state
4327 */
4328 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4329 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004330
4331 /*
4332 * Dump VrFlinger state if in use.
4333 */
4334 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4335 result.append("VrFlinger state:\n");
4336 result.append(mVrFlinger->Dump().c_str());
4337 result.append("\n");
4338 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004339}
4340
Mathias Agopian13127d82013-03-05 17:47:11 -08004341const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004342SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004343 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004344 wp<IBinder> dpy;
4345 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4346 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4347 dpy = mDisplays.keyAt(i);
4348 break;
4349 }
4350 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004351 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004352 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4353 // Just use the primary display so we have something to return
4354 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4355 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004356 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004357}
4358
Keun young Park63f165f2012-08-31 10:53:36 -07004359bool SurfaceFlinger::startDdmConnection()
4360{
4361 void* libddmconnection_dso =
4362 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4363 if (!libddmconnection_dso) {
4364 return false;
4365 }
4366 void (*DdmConnection_start)(const char* name);
4367 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004368 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004369 if (!DdmConnection_start) {
4370 dlclose(libddmconnection_dso);
4371 return false;
4372 }
4373 (*DdmConnection_start)(getServiceName());
4374 return true;
4375}
4376
Chia-I Wu28f320b2018-05-03 11:02:56 -07004377void SurfaceFlinger::updateColorMatrixLocked() {
4378 mat4 colorMatrix;
4379 if (mGlobalSaturationFactor != 1.0f) {
4380 // Rec.709 luma coefficients
4381 float3 luminance{0.213f, 0.715f, 0.072f};
4382 luminance *= 1.0f - mGlobalSaturationFactor;
4383 mat4 saturationMatrix = mat4(
4384 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4385 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4386 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4387 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4388 );
4389 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4390 } else {
4391 colorMatrix = mClientColorMatrix * mDaltonizer();
4392 }
4393
4394 if (mCurrentState.colorMatrix != colorMatrix) {
4395 mCurrentState.colorMatrix = colorMatrix;
4396 mCurrentState.colorMatrixChanged = true;
4397 setTransactionFlags(eTransactionNeeded);
4398 }
4399}
4400
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004401status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 switch (code) {
4403 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004404 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004405 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004406 case CLEAR_ANIMATION_FRAME_STATS:
4407 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004408 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004409 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004410 case ENABLE_VSYNC_INJECTIONS:
4411 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004412 {
4413 // codes that require permission check
4414 IPCThreadState* ipc = IPCThreadState::self();
4415 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004416 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004417 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004418 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004419 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004420 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004422 break;
4423 }
Robert Carr1db73f62016-12-21 12:58:51 -08004424 /*
4425 * Calling setTransactionState is safe, because you need to have been
4426 * granted a reference to Client* and Handle* to do anything with it.
4427 *
4428 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4429 */
4430 case SET_TRANSACTION_STATE:
4431 case CREATE_SCOPED_CONNECTION:
4432 {
4433 return OK;
4434 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004435 case CAPTURE_SCREEN:
4436 {
4437 // codes that require permission check
4438 IPCThreadState* ipc = IPCThreadState::self();
4439 const int pid = ipc->getCallingPid();
4440 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004441 if ((uid != AID_GRAPHICS) &&
4442 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004443 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004444 return PERMISSION_DENIED;
4445 }
4446 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 }
chaviwa76b2712017-09-20 12:02:26 -07004448 case CAPTURE_LAYERS: {
4449 IPCThreadState* ipc = IPCThreadState::self();
4450 const int pid = ipc->getCallingPid();
4451 const int uid = ipc->getCallingUid();
4452 if ((uid != AID_GRAPHICS) &&
4453 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4454 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4455 return PERMISSION_DENIED;
4456 }
4457 break;
4458 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004460 return OK;
4461}
4462
4463status_t SurfaceFlinger::onTransact(
4464 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4465{
4466 status_t credentialCheck = CheckTransactCodeCredentials(code);
4467 if (credentialCheck != OK) {
4468 return credentialCheck;
4469 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004470
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4472 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004473 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004474 IPCThreadState* ipc = IPCThreadState::self();
4475 const int uid = ipc->getCallingUid();
4476 if (CC_UNLIKELY(uid != AID_SYSTEM
4477 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004478 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004479 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004480 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 return PERMISSION_DENIED;
4482 }
4483 int n;
4484 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004485 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004486 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 return NO_ERROR;
4488 case 1002: // SHOW_UPDATES
4489 n = data.readInt32();
4490 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004491 invalidateHwcGeometry();
4492 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004495 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004496 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004498 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004499 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004500 setTransactionFlags(
4501 eTransactionNeeded|
4502 eDisplayTransactionNeeded|
4503 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004504 return NO_ERROR;
4505 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004506 case 1006:{ // send empty update
4507 signalRefresh();
4508 return NO_ERROR;
4509 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004510 case 1008: // toggle use of hw composer
4511 n = data.readInt32();
4512 mDebugDisableHWC = n ? 1 : 0;
4513 invalidateHwcGeometry();
4514 repaintEverything();
4515 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004516 case 1009: // toggle use of transform hint
4517 n = data.readInt32();
4518 mDebugDisableTransformHint = n ? 1 : 0;
4519 invalidateHwcGeometry();
4520 repaintEverything();
4521 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004523 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524 reply->writeInt32(0);
4525 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004526 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004527 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 return NO_ERROR;
4529 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004530 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004531 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004532 return NO_ERROR;
4533 }
4534 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004535 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004536 // daltonize
4537 n = data.readInt32();
4538 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004539 case 1:
4540 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4541 break;
4542 case 2:
4543 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4544 break;
4545 case 3:
4546 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4547 break;
4548 default:
4549 mDaltonizer.setType(ColorBlindnessType::None);
4550 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004551 }
4552 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004553 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004554 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004555 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004556 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004557
4558 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004559 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004561 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004562 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004563 // apply a color matrix
4564 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004565 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004566 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004567 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004568 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004569 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004570 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004571 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004572 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004573 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004574 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004575
4576 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4577 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004578 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004579 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4580 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4581 }
4582
Chia-I Wu28f320b2018-05-03 11:02:56 -07004583 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004584 return NO_ERROR;
4585 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004586 // This is an experimental interface
4587 // Needs to be shifted to proper binder interface when we productize
4588 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004589 n = data.readInt32();
4590 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004591 return NO_ERROR;
4592 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004593 case 1017: {
4594 n = data.readInt32();
4595 mForceFullDamage = static_cast<bool>(n);
4596 return NO_ERROR;
4597 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004598 case 1018: { // Modify Choreographer's phase offset
4599 n = data.readInt32();
4600 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4601 return NO_ERROR;
4602 }
4603 case 1019: { // Modify SurfaceFlinger's phase offset
4604 n = data.readInt32();
4605 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4606 return NO_ERROR;
4607 }
Irvel468051e2016-06-13 16:44:44 -07004608 case 1020: { // Layer updates interceptor
4609 n = data.readInt32();
4610 if (n) {
4611 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004612 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004613 }
4614 else{
4615 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004616 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004617 }
4618 return NO_ERROR;
4619 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004620 case 1021: { // Disable HWC virtual displays
4621 n = data.readInt32();
4622 mUseHwcVirtualDisplays = !n;
4623 return NO_ERROR;
4624 }
Romain Guy0147a172017-06-01 13:53:56 -07004625 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004626 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004627 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004628
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004630 return NO_ERROR;
4631 }
Romain Guy54f154a2017-10-24 21:40:32 +01004632 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004633 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004634 invalidateHwcGeometry();
4635 repaintEverything();
4636 return NO_ERROR;
4637 }
4638 case 1024: { // Is wide color gamut rendering/color management supported?
4639 reply->writeBool(hasWideColorDisplay);
4640 return NO_ERROR;
4641 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004642 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004643 n = data.readInt32();
4644 if (n) {
4645 ALOGV("LayerTracing enabled");
4646 mTracing.enable();
4647 doTracing("tracing.enable");
4648 reply->writeInt32(NO_ERROR);
4649 } else {
4650 ALOGV("LayerTracing disabled");
4651 status_t err = mTracing.disable();
4652 reply->writeInt32(err);
4653 }
4654 return NO_ERROR;
4655 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004656 case 1026: { // Get layer tracing status
4657 reply->writeBool(mTracing.isEnabled());
4658 return NO_ERROR;
4659 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004660 // Is a DisplayColorSetting supported?
4661 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004662 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4663 if (!hw) {
4664 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004665 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004666
4667 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4668 switch (setting) {
4669 case DisplayColorSetting::MANAGED:
4670 reply->writeBool(hasWideColorDisplay);
4671 break;
4672 case DisplayColorSetting::UNMANAGED:
4673 reply->writeBool(true);
4674 break;
4675 case DisplayColorSetting::ENHANCED:
4676 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4677 break;
4678 default: // vendor display color setting
4679 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4680 break;
4681 }
4682 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004683 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004684 }
4685 }
4686 return err;
4687}
4688
Steven Thomas6d8110b2017-08-31 18:24:21 -07004689void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004690 android_atomic_or(1, &mRepaintEverything);
4691 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004692}
4693
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004694// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4695class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004696public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004697 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4698 ~WindowDisconnector() {
4699 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004700 }
4701
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004702private:
4703 ANativeWindow* mWindow;
4704 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004705};
4706
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004707status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4708 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4709 int32_t minLayerZ, int32_t maxLayerZ,
4710 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004711 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004712 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004713
chaviwa76b2712017-09-20 12:02:26 -07004714 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4715
4716 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004717 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4718
chaviwa76b2712017-09-20 12:02:26 -07004719 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4720
4721 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4722 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004723 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004724}
4725
4726status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004727 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004728 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004729 ATRACE_CALL();
4730
4731 class LayerRenderArea : public RenderArea {
4732 public:
Robert Carr578038f2018-03-09 12:25:24 -08004733 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4734 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004735 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004736 mLayer(layer),
4737 mCrop(crop),
4738 mFlinger(flinger),
4739 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004740 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004741 Rect getBounds() const override {
4742 const Layer::State& layerState(mLayer->getDrawingState());
4743 return Rect(layerState.active.w, layerState.active.h);
4744 }
4745 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4746 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4747 bool isSecure() const override { return false; }
4748 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004749 Rect getSourceCrop() const override {
4750 if (mCrop.isEmpty()) {
4751 return getBounds();
4752 } else {
4753 return mCrop;
4754 }
4755 }
Robert Carr578038f2018-03-09 12:25:24 -08004756 class ReparentForDrawing {
4757 public:
4758 const sp<Layer>& oldParent;
4759 const sp<Layer>& newParent;
4760
4761 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4762 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004763 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004764 }
Robert Carr15eae092018-03-23 13:43:53 -07004765 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004766 };
4767
4768 void render(std::function<void()> drawLayers) override {
4769 if (!mChildrenOnly) {
4770 mTransform = mLayer->getTransform().inverse();
4771 drawLayers();
4772 } else {
4773 Rect bounds = getBounds();
4774 screenshotParentLayer =
4775 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4776 bounds.getWidth(), bounds.getHeight(), 0);
4777
4778 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4779 drawLayers();
4780 }
4781 }
chaviwa76b2712017-09-20 12:02:26 -07004782
chaviwa76b2712017-09-20 12:02:26 -07004783 private:
chaviw7206d492017-11-10 16:16:12 -08004784 const sp<Layer> mLayer;
4785 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004786
4787 // In the "childrenOnly" case we reparent the children to a screenshot
4788 // layer which has no properties set and which does not draw.
4789 sp<ContainerLayer> screenshotParentLayer;
4790 Transform mTransform;
4791
4792 SurfaceFlinger* mFlinger;
4793 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004794 };
4795
4796 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4797 auto parent = layerHandle->owner.promote();
4798
chaviw7206d492017-11-10 16:16:12 -08004799 if (parent == nullptr || parent->isPendingRemoval()) {
4800 ALOGE("captureLayers called with a removed parent");
4801 return NAME_NOT_FOUND;
4802 }
4803
Robert Carr578038f2018-03-09 12:25:24 -08004804 const int uid = IPCThreadState::self()->getCallingUid();
4805 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4806 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4807 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4808 return PERMISSION_DENIED;
4809 }
4810
chaviw7206d492017-11-10 16:16:12 -08004811 Rect crop(sourceCrop);
4812 if (sourceCrop.width() <= 0) {
4813 crop.left = 0;
4814 crop.right = parent->getCurrentState().active.w;
4815 }
4816
4817 if (sourceCrop.height() <= 0) {
4818 crop.top = 0;
4819 crop.bottom = parent->getCurrentState().active.h;
4820 }
4821
4822 int32_t reqWidth = crop.width() * frameScale;
4823 int32_t reqHeight = crop.height() * frameScale;
4824
Robert Carr578038f2018-03-09 12:25:24 -08004825 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004826
Robert Carr578038f2018-03-09 12:25:24 -08004827 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004828 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4829 if (!layer->isVisible()) {
4830 return;
Robert Carr578038f2018-03-09 12:25:24 -08004831 } else if (childrenOnly && layer == parent.get()) {
4832 return;
chaviwa76b2712017-09-20 12:02:26 -07004833 }
4834 visitor(layer);
4835 });
4836 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004837 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004838}
4839
4840status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4841 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004842 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004843 bool useIdentityTransform) {
4844 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004845
Iris Chang7501ed62018-04-30 14:45:42 +08004846 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004847
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004848 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4849 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4850 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4851 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004852
4853 // This mutex protects syncFd and captureResult for communication of the return values from the
4854 // main thread back to this Binder thread
4855 std::mutex captureMutex;
4856 std::condition_variable captureCondition;
4857 std::unique_lock<std::mutex> captureLock(captureMutex);
4858 int syncFd = -1;
4859 std::optional<status_t> captureResult;
4860
Robert Carr03480e22018-01-04 16:02:06 -08004861 const int uid = IPCThreadState::self()->getCallingUid();
4862 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4863
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004864 sp<LambdaMessage> message = new LambdaMessage([&]() {
4865 // If there is a refresh pending, bug out early and tell the binder thread to try again
4866 // after the refresh.
4867 if (mRefreshPending) {
4868 ATRACE_NAME("Skipping screenshot for now");
4869 std::unique_lock<std::mutex> captureLock(captureMutex);
4870 captureResult = std::make_optional<status_t>(EAGAIN);
4871 captureCondition.notify_one();
4872 return;
4873 }
4874
4875 status_t result = NO_ERROR;
4876 int fd = -1;
4877 {
4878 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004879 renderArea.render([&]() {
4880 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4881 useIdentityTransform, forSystem, &fd);
4882 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 }
4884
4885 {
4886 std::unique_lock<std::mutex> captureLock(captureMutex);
4887 syncFd = fd;
4888 captureResult = std::make_optional<status_t>(result);
4889 captureCondition.notify_one();
4890 }
4891 });
4892
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004893 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004894 if (result == NO_ERROR) {
4895 captureCondition.wait(captureLock, [&]() { return captureResult; });
4896 while (*captureResult == EAGAIN) {
4897 captureResult.reset();
4898 result = postMessageAsync(message);
4899 if (result != NO_ERROR) {
4900 return result;
4901 }
4902 captureCondition.wait(captureLock, [&]() { return captureResult; });
4903 }
4904 result = *captureResult;
4905 }
4906
4907 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004908 sync_wait(syncFd, -1);
4909 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004910 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004911
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004912 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004913}
4914
chaviwa76b2712017-09-20 12:02:26 -07004915void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4916 TraverseLayersFunction traverseLayers, bool yswap,
4917 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004918 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004919
Lloyd Pique144e1162017-12-20 16:44:52 -08004920 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004921
4922 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004923 const auto raWidth = renderArea.getWidth();
4924 const auto raHeight = renderArea.getHeight();
4925
4926 const auto reqWidth = renderArea.getReqWidth();
4927 const auto reqHeight = renderArea.getReqHeight();
4928 Rect sourceCrop = renderArea.getSourceCrop();
4929
Iris Chang7501ed62018-04-30 14:45:42 +08004930 bool filtering = false;
4931 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4932 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4933 static_cast<int32_t>(reqHeight) != raWidth;
4934 } else {
4935 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4936 static_cast<int32_t>(reqHeight) != raHeight;
4937 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004938
Dan Stozac1879002014-05-22 15:59:05 -07004939 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004940 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004941 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004942 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004943 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4944 Transform tr;
4945 uint32_t flags = 0x00;
4946 switch (mPrimaryDisplayOrientation) {
4947 case DisplayState::eOrientation90:
4948 flags = Transform::ROT_90;
4949 break;
4950 case DisplayState::eOrientation180:
4951 flags = Transform::ROT_180;
4952 break;
4953 case DisplayState::eOrientation270:
4954 flags = Transform::ROT_270;
4955 break;
4956 }
4957 tr.set(flags, raWidth, raHeight);
4958 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004959 }
4960
4961 // ensure that sourceCrop is inside screen
4962 if (sourceCrop.left < 0) {
4963 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4964 }
chaviwa76b2712017-09-20 12:02:26 -07004965 if (sourceCrop.right > raWidth) {
4966 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004967 }
4968 if (sourceCrop.top < 0) {
4969 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4970 }
chaviwa76b2712017-09-20 12:02:26 -07004971 if (sourceCrop.bottom > raHeight) {
4972 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004973 }
4974
Chia-I Wu36574d92018-05-16 10:54:36 -07004975 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4976 engine.setOutputDataSpace(Dataspace::SRGB);
4977 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004978
Mathias Agopian180f10d2013-04-10 22:55:41 -07004979 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004980 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004981
Iris Chang7501ed62018-04-30 14:45:42 +08004982 Transform::orientation_flags rotation = renderArea.getRotationFlags();
4983 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4984 // convert hw orientation into flag presentation
4985 // here inverse transform needed
4986 uint8_t hw_rot_90 = 0x00;
4987 uint8_t hw_flip_hv = 0x00;
4988 switch (mPrimaryDisplayOrientation) {
4989 case DisplayState::eOrientation90:
4990 hw_rot_90 = Transform::ROT_90;
4991 hw_flip_hv = Transform::ROT_180;
4992 break;
4993 case DisplayState::eOrientation180:
4994 hw_flip_hv = Transform::ROT_180;
4995 break;
4996 case DisplayState::eOrientation270:
4997 hw_rot_90 = Transform::ROT_90;
4998 break;
4999 }
5000
5001 // transform flags operation
5002 // 1) flip H V if both have ROT_90 flag
5003 // 2) XOR these flags
5004 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5005 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5006 if (rotation_rot_90 & hw_rot_90) {
5007 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5008 }
5009 rotation = static_cast<Transform::orientation_flags>
5010 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5011 }
5012
Mathias Agopian180f10d2013-04-10 22:55:41 -07005013 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005014 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005015 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005016 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005017
chaviw50da5042018-04-09 13:49:37 -07005018 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005019 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005020 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005021
chaviwa76b2712017-09-20 12:02:26 -07005022 traverseLayers([&](Layer* layer) {
5023 if (filtering) layer->setFiltering(true);
5024 layer->draw(renderArea, useIdentityTransform);
5025 if (filtering) layer->setFiltering(false);
5026 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005027}
5028
chaviwa76b2712017-09-20 12:02:26 -07005029status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5030 TraverseLayersFunction traverseLayers,
5031 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005032 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005033 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005034 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005035 ATRACE_CALL();
5036
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005037 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005038
5039 traverseLayers([&](Layer* layer) {
5040 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5041 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005042
Robert Carr03480e22018-01-04 16:02:06 -08005043 // We allow the system server to take screenshots of secure layers for
5044 // use in situations like the Screen-rotation animation and place
5045 // the impetus on WindowManager to not persist them.
5046 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005047 ALOGW("FB is protected: PERMISSION_DENIED");
5048 return PERMISSION_DENIED;
5049 }
5050
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005051 // this binds the given EGLImage as a framebuffer for the
5052 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005053 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005054 if (bufferBond.getStatus() != NO_ERROR) {
5055 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005056 return INVALID_OPERATION;
5057 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005058
Dan Stozaabcda352017-06-01 14:37:39 -07005059 // this will in fact render into our dequeued buffer
5060 // via an FBO, which means we didn't have to create
5061 // an EGLSurface and therefore we're not
5062 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005063 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005064
Dan Stozaabcda352017-06-01 14:37:39 -07005065 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005066 getRenderEngine().finish();
5067 *outSyncFd = -1;
5068
chaviwa76b2712017-09-20 12:02:26 -07005069 const auto reqWidth = renderArea.getReqWidth();
5070 const auto reqHeight = renderArea.getReqHeight();
5071
Dan Stozaabcda352017-06-01 14:37:39 -07005072 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5073 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005074 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005075 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005076 } else {
5077 base::unique_fd syncFd = getRenderEngine().flush();
5078 if (syncFd < 0) {
5079 getRenderEngine().finish();
5080 }
5081 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005082 }
5083
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005084 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005085}
5086
Mathias Agopiand5556842013-09-19 17:08:37 -07005087void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005088 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005089 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005090 for (size_t y = 0; y < h; y++) {
5091 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5092 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005093 if (p[x] != 0xFF000000) return;
5094 }
5095 }
chaviwa76b2712017-09-20 12:02:26 -07005096 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005097
Robert Carr2047fae2016-11-28 14:09:09 -08005098 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005099 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005100 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005101 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5102 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5103 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5104 static_cast<float>(state.color.a));
5105 i++;
5106 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005107 }
5108}
5109
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005110// ---------------------------------------------------------------------------
5111
Dan Stoza412903f2017-04-27 13:42:17 -07005112void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5113 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005114}
5115
Dan Stoza412903f2017-04-27 13:42:17 -07005116void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5117 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005118}
5119
chaviwa76b2712017-09-20 12:02:26 -07005120void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5121 int32_t maxLayerZ,
5122 const LayerVector::Visitor& visitor) {
5123 // We loop through the first level of layers without traversing,
5124 // as we need to interpret min/max layer Z in the top level Z space.
5125 for (const auto& layer : mDrawingState.layersSortedByZ) {
5126 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5127 continue;
5128 }
5129 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005130 // relative layers are traversed in Layer::traverseInZOrder
5131 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005132 continue;
5133 }
5134 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005135 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5136 return;
5137 }
chaviwa76b2712017-09-20 12:02:26 -07005138 if (!layer->isVisible()) {
5139 return;
5140 }
5141 visitor(layer);
5142 });
5143 }
5144}
5145
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005147
5148
5149#if defined(__gl_h_)
5150#error "don't include gl/gl.h in this file"
5151#endif
5152
5153#if defined(__gl2_h_)
5154#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005155#endif