blob: 66b41f5c76e01e3e1701831eedf1578e6d8403ed [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
Jorim Jaggie203e042018-06-19 15:57:08 +0200334 property_get("debug.sf.early_phase_offset_ns", value, "-1");
335 const int earlySfOffsetNs = atoi(value);
336
337 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
338 const int earlyGlSfOffsetNs = atoi(value);
339
340 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
341 const int earlyAppOffsetNs = atoi(value);
342
343 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
344 const int earlyGlAppOffsetNs = atoi(value);
345
346 const VSyncModulator::Offsets earlyOffsets =
347 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
348 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
349 const VSyncModulator::Offsets earlyGlOffsets =
350 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
351 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
352 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
353 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700354
Romain Guy11d63f42017-07-20 12:47:14 -0700355 // We should be reading 'persist.sys.sf.color_saturation' here
356 // but since /data may be encrypted, we need to wait until after vold
357 // comes online to attempt to read the property. The property is
358 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800359
360 if (useTrebleTestingOverride()) {
361 // Without the override SurfaceFlinger cannot connect to HIDL
362 // services that are not listed in the manifests. Considered
363 // deriving the setting from the set service name, but it
364 // would be brittle if the name that's not 'default' is used
365 // for production purposes later on.
366 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
367 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368}
369
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800370void SurfaceFlinger::onFirstRef()
371{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800372 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800373}
374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375SurfaceFlinger::~SurfaceFlinger()
376{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377}
378
Dan Stozac7014012014-02-14 15:03:43 -0800379void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380{
381 // the window manager died on us. prepare its eulogy.
382
Andy McFadden13a082e2012-08-24 10:16:42 -0700383 // restore initial conditions (default device unblank, etc)
384 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385
386 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700387 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800388}
389
Robert Carr1db73f62016-12-21 12:58:51 -0800390static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700391 status_t err = client->initCheck();
392 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800393 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394 }
Robert Carr1db73f62016-12-21 12:58:51 -0800395 return nullptr;
396}
397
398sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
399 return initClient(new Client(this));
400}
401
402sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
403 const sp<IGraphicBufferProducer>& gbp) {
404 if (authenticateSurfaceTexture(gbp) == false) {
405 return nullptr;
406 }
407 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
408 if (layer == nullptr) {
409 return nullptr;
410 }
411
412 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700415sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
416 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417{
418 class DisplayToken : public BBinder {
419 sp<SurfaceFlinger> flinger;
420 virtual ~DisplayToken() {
421 // no more references, this display must be terminated
422 Mutex::Autolock _l(flinger->mStateLock);
423 flinger->mCurrentState.displays.removeItem(this);
424 flinger->setTransactionFlags(eDisplayTransactionNeeded);
425 }
426 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700427 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700428 : flinger(flinger) {
429 }
430 };
431
432 sp<BBinder> token = new DisplayToken(this);
433
434 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700435 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700436 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800438 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 return token;
440}
441
Jesse Hall6c913be2013-08-08 12:15:49 -0700442void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
443 Mutex::Autolock _l(mStateLock);
444
445 ssize_t idx = mCurrentState.displays.indexOfKey(display);
446 if (idx < 0) {
447 ALOGW("destroyDisplay: invalid display token");
448 return;
449 }
450
451 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
452 if (!info.isVirtualDisplay()) {
453 ALOGE("destroyDisplay called for non-virtual display");
454 return;
455 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800456 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 mCurrentState.displays.removeItemsAt(idx);
458 setTransactionFlags(eDisplayTransactionNeeded);
459}
460
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700462 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700463 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800464 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 }
Jesse Hall692c7232012-11-08 15:41:56 -0800466 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467}
468
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469void SurfaceFlinger::bootFinished()
470{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700471 if (mStartPropertySetThread->join() != NO_ERROR) {
472 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800473 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800474 const nsecs_t now = systemTime();
475 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000476 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700477
478 // wait patiently for the window manager death
479 const String16 name("window");
480 sp<IBinder> window(defaultServiceManager()->getService(name));
481 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700482 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700483 }
484
Steven Thomas050b2c82017-03-06 11:45:16 -0800485 if (mVrFlinger) {
486 mVrFlinger->OnBootFinished();
487 }
488
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700489 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700490 // formerly we would just kill the process, but we now ask it to exit so it
491 // can choose where to stop the animation.
492 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700493
494 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
495 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
496 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700497
Thierry Strudel2924d012017-08-14 15:19:37 -0700498 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700499 readPersistentProperties();
500 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700501 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502}
503
Mathias Agopian3f844832013-08-07 21:24:32 -0700504void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700505 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800506 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700507 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700508 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800509 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
510 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700511 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700512 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700513 return true;
514 }
515 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700516 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700517}
518
Lloyd Piquee83f9312018-02-01 12:53:17 -0800519class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700521 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000522 const char* name) :
523 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700524 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700525 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000526 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
527 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700528 mDispSync(dispSync),
529 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700530 mVsyncMutex(),
531 mPhaseOffset(phaseOffset),
532 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700533
Lloyd Piquee83f9312018-02-01 12:53:17 -0800534 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000539 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 static_cast<DispSync::Callback*>(this));
541 if (err != NO_ERROR) {
542 ALOGE("error registering vsync callback: %s (%d)",
543 strerror(-err), err);
544 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546 } else {
547 status_t err = mDispSync->removeEventListener(
548 static_cast<DispSync::Callback*>(this));
549 if (err != NO_ERROR) {
550 ALOGE("error unregistering vsync callback: %s (%d)",
551 strerror(-err), err);
552 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700553 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700555 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 }
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560 mCallback = callback;
561 }
562
Lloyd Piquee83f9312018-02-01 12:53:17 -0800563 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700564 Mutex::Autolock lock(mVsyncMutex);
565
566 // Normalize phaseOffset to [0, period)
567 auto period = mDispSync->getPeriod();
568 phaseOffset %= period;
569 if (phaseOffset < 0) {
570 // If we're here, then phaseOffset is in (-period, 0). After this
571 // operation, it will be in (0, period)
572 phaseOffset += period;
573 }
574 mPhaseOffset = phaseOffset;
575
576 // If we're not enabled, we don't need to mess with the listeners
577 if (!mEnabled) {
578 return;
579 }
580
Dan Stoza2713c302018-03-28 17:07:36 -0700581 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
582 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700583 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700584 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700585 strerror(-err), err);
586 }
587 }
588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589private:
590 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800591 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 callback = mCallback;
595
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700596 if (mTraceVsync) {
597 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700598 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700599 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600 }
601
Peiyong Lin566a3b42018-01-09 18:22:43 -0800602 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 callback->onVSyncEvent(when);
604 }
605 }
606
Tim Murray4a4e4a22016-04-19 16:29:23 +0000607 const char* const mName;
608
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700609 int mValue;
610
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700611 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700612 const String8 mVsyncOnLabel;
613 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700614
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700616
617 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800618 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700619
620 Mutex mVsyncMutex; // Protects the following
621 nsecs_t mPhaseOffset;
622 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623};
624
Lloyd Piquee83f9312018-02-01 12:53:17 -0800625class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700626public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800627 InjectVSyncSource() = default;
628 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700629
Lloyd Piquee83f9312018-02-01 12:53:17 -0800630 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700631 std::lock_guard<std::mutex> lock(mCallbackMutex);
632 mCallback = callback;
633 }
634
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700637 if (mCallback) {
638 mCallback->onVSyncEvent(when);
639 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700640 }
641
Lloyd Piquee83f9312018-02-01 12:53:17 -0800642 void setVSyncEnabled(bool) override {}
643 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700644
645private:
646 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800647 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700648};
649
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650// Do not call property_set on main thread which will be blocked by init
651// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700652void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700653 ALOGI( "SurfaceFlinger's main thread ready to run. "
654 "Initializing graphics H/W...");
655
Thierry Strudel2924d012017-08-14 15:19:37 -0700656 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900657
Steven Thomasb02664d2017-07-26 18:48:28 -0700658 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659
Steven Thomasb02664d2017-07-26 18:48:28 -0700660 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800661 mEventThreadSource =
662 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
663 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800664 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
665 [this]() { resyncWithRateLimit(); },
666 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800667 "appEventThread");
668 mSfEventThreadSource =
669 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
670 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800671
Lloyd Pique24b0a482018-03-09 18:52:26 -0800672 mSFEventThread =
673 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
674 [this]() { resyncWithRateLimit(); },
675 [this](nsecs_t timestamp) {
676 mInterceptor->saveVSyncEvent(timestamp);
677 },
678 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800679 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200680 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681
Steven Thomasb02664d2017-07-26 18:48:28 -0700682 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800683 getBE().mRenderEngine =
684 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
685 hasWideColorDisplay
686 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
687 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800688 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700689
690 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
691 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800692 getBE().mHwc.reset(
693 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700694 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800695 // Process any initial hotplug and resulting display changes.
696 processDisplayHotplugEventsLocked();
697 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
698 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800699
Lloyd Piquefcd86612017-12-14 17:15:36 -0800700 // make the default display GLContext current so that we can create textures
701 // when creating Layers (which may happens before we render something)
702 getDefaultDisplayDeviceLocked()->makeCurrent();
703
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 if (useVrFlinger) {
705 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700706 // This callback is called from the vr flinger dispatch thread. We
707 // need to call signalTransaction(), which requires holding
708 // mStateLock when we're not on the main thread. Acquiring
709 // mStateLock from the vr flinger dispatch thread might trigger a
710 // deadlock in surface flinger (see b/66916578), so post a message
711 // to be handled on the main thread instead.
712 sp<LambdaMessage> message = new LambdaMessage([=]() {
713 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
714 mVrFlingerRequestsDisplay = requestDisplay;
715 signalTransaction();
716 });
717 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800718 };
David Sodman105b7dc2017-11-04 20:28:14 -0700719 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
720 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800721 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800722 if (!mVrFlinger) {
723 ALOGE("Failed to start vrflinger");
724 }
725 }
726
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800727 mEventControlThread = std::make_unique<impl::EventControlThread>(
728 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700729
Mathias Agopian92a979a2012-08-02 18:32:23 -0700730 // initialize our drawing state
731 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700732
Andy McFadden13a082e2012-08-24 10:16:42 -0700733 // set initial conditions (e.g. unblank default device)
734 initializeDisplays();
735
David Sodmanbc815282017-11-05 18:57:52 -0800736 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700737
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 // Inform native graphics APIs whether the present timestamp is supported:
739 if (getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 mStartPropertySetThread = new StartPropertySetThread(false);
742 } else {
743 mStartPropertySetThread = new StartPropertySetThread(true);
744 }
745
746 if (mStartPropertySetThread->Start() != NO_ERROR) {
747 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
751 Dataspace::SRGB_LINEAR);
752
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700754}
755
Romain Guy11d63f42017-07-20 12:47:14 -0700756void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700757 Mutex::Autolock _l(mStateLock);
758
Romain Guy11d63f42017-07-20 12:47:14 -0700759 char value[PROPERTY_VALUE_MAX];
760
761 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800762 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700763 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100765
766 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700767 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700768}
769
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800771 // Start boot animation service by setting a property mailbox
772 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700773 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800774 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 if (mStartPropertySetThread->join() != NO_ERROR) {
776 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800777 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700778}
779
Mathias Agopian875d8e12013-06-07 15:35:48 -0700780size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800781 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700782}
783
Mathias Agopian875d8e12013-06-07 15:35:48 -0700784size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800785 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700786}
787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800788// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800789
Jamie Gennis582270d2011-08-17 18:19:00 -0700790bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800792 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800793 return authenticateSurfaceTextureLocked(bufferProducer);
794}
795
796bool SurfaceFlinger::authenticateSurfaceTextureLocked(
797 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800798 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800799 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800800}
801
Brian Anderson6b376712017-04-04 10:51:39 -0700802status_t SurfaceFlinger::getSupportedFrameTimestamps(
803 std::vector<FrameEvent>* outSupported) const {
804 *outSupported = {
805 FrameEvent::REQUESTED_PRESENT,
806 FrameEvent::ACQUIRE,
807 FrameEvent::LATCH,
808 FrameEvent::FIRST_REFRESH_START,
809 FrameEvent::LAST_REFRESH_START,
810 FrameEvent::GPU_COMPOSITION_DONE,
811 FrameEvent::DEQUEUE_READY,
812 FrameEvent::RELEASE,
813 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700814 ConditionalLock _l(mStateLock,
815 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700816 if (!getHwComposer().hasCapability(
817 HWC2::Capability::PresentFenceIsNotReliable)) {
818 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
819 }
820 return NO_ERROR;
821}
822
Dan Stoza7f7da322014-05-02 15:26:25 -0700823status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
824 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 return BAD_VALUE;
827 }
828
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500829 if (!display.get())
830 return NAME_NOT_FOUND;
831
Jesse Hall692c7232012-11-08 15:41:56 -0800832 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700833 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800834 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700835 type = i;
836 break;
837 }
838 }
839
840 if (type < 0) {
841 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700842 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 // TODO: Not sure if display density should handled by SF any longer
845 class Density {
846 static int getDensityFromProperty(char const* propName) {
847 char property[PROPERTY_VALUE_MAX];
848 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800849 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 density = atoi(property);
851 }
852 return density;
853 }
854 public:
855 static int getEmuDensity() {
856 return getDensityFromProperty("qemu.sf.lcd_density"); }
857 static int getBuildDensity() {
858 return getDensityFromProperty("ro.sf.lcd_density"); }
859 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700862
Steven Thomas6d8110b2017-08-31 18:24:21 -0700863 ConditionalLock _l(mStateLock,
864 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 DisplayInfo info = DisplayInfo();
867
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 float xdpi = hwConfig->getDpiX();
869 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700870
871 if (type == DisplayDevice::DISPLAY_PRIMARY) {
872 // The density of the device is provided by a build property
873 float density = Density::getBuildDensity() / 160.0f;
874 if (density == 0) {
875 // the build doesn't provide a density -- this is wrong!
876 // use xdpi instead
877 ALOGE("ro.sf.lcd_density must be defined as a build property");
878 density = xdpi / 160.0f;
879 }
880 if (Density::getEmuDensity()) {
881 // if "qemu.sf.lcd_density" is specified, it overrides everything
882 xdpi = ydpi = density = Density::getEmuDensity();
883 density /= 160.0f;
884 }
885 info.density = density;
886
887 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700888 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800889 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 } else {
891 // TODO: where should this value come from?
892 static const int TV_DENSITY = 213;
893 info.density = TV_DENSITY / 160.0f;
894 info.orientation = 0;
895 }
896
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 info.w = hwConfig->getWidth();
898 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 info.xdpi = xdpi;
900 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900902 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903
Andy McFadden91b2ca82014-06-13 14:04:23 -0700904 // This is how far in advance a buffer must be queued for
905 // presentation at a given time. If you want a buffer to appear
906 // on the screen at time N, you must submit the buffer before
907 // (N - presentationDeadline).
908 //
909 // Normally it's one full refresh period (to give SF a chance to
910 // latch the buffer), but this can be reduced by configuring a
911 // DispSync offset. Any additional delays introduced by the hardware
912 // composer or panel must be accounted for here.
913 //
914 // We add an additional 1ms to allow for processing time and
915 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800916 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800917 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700918
919 // All non-virtual displays are currently considered secure.
920 info.secure = true;
921
Iris Chang7501ed62018-04-30 14:45:42 +0800922 if (type == DisplayDevice::DISPLAY_PRIMARY &&
923 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
924 std::swap(info.w, info.h);
925 }
926
Michael Wright28f24d02016-07-12 13:30:53 -0700927 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700928 }
929
Dan Stoza7f7da322014-05-02 15:26:25 -0700930 return NO_ERROR;
931}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700932
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800933status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700934 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800935 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return BAD_VALUE;
937 }
938
939 // FIXME for now we always return stats for the primary display
940 memset(stats, 0, sizeof(*stats));
941 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
942 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
943 return NO_ERROR;
944}
945
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700946int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800947 if (display == nullptr) {
948 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800949 return BAD_VALUE;
950 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700951
952 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800953 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700954 return device->getActiveConfig();
955 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956
Dan Stoza24a42e92015-03-09 10:04:11 -0700957 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700958}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700959
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
961 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
962 this);
963 int32_t type = hw->getDisplayType();
964 int currentMode = hw->getActiveConfig();
965
966 if (mode == currentMode) {
967 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
968 return;
969 }
970
971 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
976 hw->setActiveConfig(mode);
977 getHwComposer().setActiveConfig(type, mode);
978}
979
980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
981 class MessageSetActiveConfig: public MessageBase {
982 SurfaceFlinger& mFlinger;
983 sp<IBinder> mDisplay;
984 int mMode;
985 public:
986 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
987 int mode) :
988 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
989 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700990 Vector<DisplayInfo> configs;
991 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700992 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700993 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700994 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700996 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700997 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800998 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001000 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001001 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1002 ALOGW("Attempt to set active config = %d for virtual display",
1003 mMode);
1004 } else {
1005 mFlinger.setActiveConfigInternal(hw, mMode);
1006 }
1007 return true;
1008 }
1009 };
1010 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1011 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001012 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001013}
Michael Wright28f24d02016-07-12 13:30:53 -07001014status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001015 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1017 return BAD_VALUE;
1018 }
1019
1020 if (!display.get()) {
1021 return NAME_NOT_FOUND;
1022 }
1023
1024 int32_t type = NAME_NOT_FOUND;
1025 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1026 if (display == mBuiltinDisplays[i]) {
1027 type = i;
1028 break;
1029 }
1030 }
1031
1032 if (type < 0) {
1033 return type;
1034 }
1035
Peiyong Lina52f0292018-03-14 17:26:31 -07001036 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001037 {
1038 ConditionalLock _l(mStateLock,
1039 std::this_thread::get_id() != mMainThreadId);
1040 modes = getHwComposer().getColorModes(type);
1041 }
Michael Wright28f24d02016-07-12 13:30:53 -07001042 outColorModes->clear();
1043 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1044
1045 return NO_ERROR;
1046}
1047
Peiyong Lina52f0292018-03-14 17:26:31 -07001048ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001049 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001050 if (device != nullptr) {
1051 return device->getActiveColorMode();
1052 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001054}
1055
1056void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001057 ColorMode mode, Dataspace dataSpace,
1058 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001060 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001061 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001062 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001063
Peiyong Lin38e9a562018-04-10 16:24:20 -07001064 if (mode == currentMode && dataSpace == currentDataSpace &&
1065 renderIntent == currentRenderIntent) {
1066 return;
1067 }
1068
1069 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1070 ALOGW("Trying to set config for virtual display");
1071 return;
1072 }
1073
1074 hw->setActiveColorMode(mode);
1075 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001076 hw->setActiveRenderIntent(renderIntent);
1077 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1078
1079 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1080 decodeColorMode(mode).c_str(), mode,
1081 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1082 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001083}
1084
1085
1086status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001087 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001088 class MessageSetActiveColorMode: public MessageBase {
1089 SurfaceFlinger& mFlinger;
1090 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001091 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001092 public:
1093 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001094 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001095 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1096 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001097 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001098 mFlinger.getDisplayColorModes(mDisplay, &modes);
1099 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001100 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001101 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1102 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001103 return true;
1104 }
1105 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1106 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001107 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1108 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001109 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001110 ALOGW("Attempt to set active color mode %s %d for virtual display",
1111 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001112 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001113 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1114 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001115 }
1116 return true;
1117 }
1118 };
1119 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1120 postMessageSync(msg);
1121 return NO_ERROR;
1122}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001123
Svetoslavd85084b2014-03-20 10:28:31 -07001124status_t SurfaceFlinger::clearAnimationFrameStats() {
1125 Mutex::Autolock _l(mStateLock);
1126 mAnimFrameTracker.clearStats();
1127 return NO_ERROR;
1128}
1129
1130status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1131 Mutex::Autolock _l(mStateLock);
1132 mAnimFrameTracker.getStats(outStats);
1133 return NO_ERROR;
1134}
1135
Dan Stozac4f471e2016-03-24 09:31:08 -07001136status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1137 HdrCapabilities* outCapabilities) const {
1138 Mutex::Autolock _l(mStateLock);
1139
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001140 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001141 if (displayDevice == nullptr) {
1142 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1143 return BAD_VALUE;
1144 }
1145
Peiyong Linfb069302018-04-25 14:34:31 -07001146 // At this point the DisplayDeivce should already be set up,
1147 // meaning the luminance information is already queried from
1148 // hardware composer and stored properly.
1149 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1150 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1151 capabilities.getDesiredMaxLuminance(),
1152 capabilities.getDesiredMaxAverageLuminance(),
1153 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001154
1155 return NO_ERROR;
1156}
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1160 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 if (mInjectVSyncs == enable) {
1163 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001164 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165
1166 if (enable) {
1167 ALOGV("VSync Injections enabled");
1168 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001169 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001170 mInjectorEventThread = std::make_unique<
1171 impl::EventThread>(mVSyncInjector.get(),
1172 [this]() { resyncWithRateLimit(); },
1173 impl::EventThread::InterceptVSyncsCallback(),
1174 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001176 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 } else {
1178 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001179 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 }
1181
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 });
1184 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185 return NO_ERROR;
1186}
1187
1188status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 Mutex::Autolock _l(mStateLock);
1190
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001191 if (!mInjectVSyncs) {
1192 ALOGE("VSync Injections not enabled");
1193 return BAD_VALUE;
1194 }
1195 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1196 ALOGV("Injecting VSync inside SurfaceFlinger");
1197 mVSyncInjector->onInjectSyncEvent(when);
1198 }
1199 return NO_ERROR;
1200}
1201
Lloyd Pique755e3192018-01-31 16:46:15 -08001202status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1203 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001204 IPCThreadState* ipc = IPCThreadState::self();
1205 const int pid = ipc->getCallingPid();
1206 const int uid = ipc->getCallingUid();
1207 if ((uid != AID_SHELL) &&
1208 !PermissionCache::checkPermission(sDump, pid, uid)) {
1209 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1210 return PERMISSION_DENIED;
1211 }
1212
1213 // Try to acquire a lock for 1s, fail gracefully
1214 const status_t err = mStateLock.timedLock(s2ns(1));
1215 const bool locked = (err == NO_ERROR);
1216 if (!locked) {
1217 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1218 return TIMED_OUT;
1219 }
1220
1221 outLayers->clear();
1222 mCurrentState.traverseInZOrder([&](Layer* layer) {
1223 outLayers->push_back(layer->getLayerDebugInfo());
1224 });
1225
1226 mStateLock.unlock();
1227 return NO_ERROR;
1228}
1229
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001230// ----------------------------------------------------------------------------
1231
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001232sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1233 ISurfaceComposer::VsyncSource vsyncSource) {
1234 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1235 return mSFEventThread->createEventConnection();
1236 } else {
1237 return mEventThread->createEventConnection();
1238 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001239}
1240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242
1243void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001244 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245}
1246
1247void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001248 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001252 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253}
1254
1255void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001256 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001257 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001261 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001262 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001266 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001267 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268 if (res == NO_ERROR) {
1269 msg->wait();
1270 }
1271 return res;
1272}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001273
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001274void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001275 do {
1276 waitForEvent();
1277 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001278}
1279
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280void SurfaceFlinger::enableHardwareVsync() {
1281 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001284 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1285 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001286 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001287 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288}
1289
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 Mutex::Autolock _l(mHWVsyncLock);
1292
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 if (makeAvailable) {
1294 mHWVsyncAvailable = true;
1295 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001296 // Hardware vsync is not currently available, so abort the resync
1297 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001298 return;
1299 }
1300
David Sodman105b7dc2017-11-04 20:28:14 -07001301 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303
1304 mPrimaryDispSync.reset();
1305 mPrimaryDispSync.setPeriod(period);
1306
1307 if (!mPrimaryHWVsyncEnabled) {
1308 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1310 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 mPrimaryHWVsyncEnabled = true;
1312 }
1313}
1314
Jesse Hall948fe0c2013-10-14 12:56:09 -07001315void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 Mutex::Autolock _l(mHWVsyncLock);
1317 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001318 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1319 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320 mPrimaryDispSync.endResync();
1321 mPrimaryHWVsyncEnabled = false;
1322 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001323 if (makeUnavailable) {
1324 mHWVsyncAvailable = false;
1325 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326}
1327
Tim Murray4a4e4a22016-04-19 16:29:23 +00001328void SurfaceFlinger::resyncWithRateLimit() {
1329 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001330
1331 // No explicit locking is needed here since EventThread holds a lock while calling this method
1332 static nsecs_t sLastResyncAttempted = 0;
1333 const nsecs_t now = systemTime();
1334 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001335 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001336 }
Dan Stoza57164302017-05-08 14:03:54 -07001337 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001338}
1339
Steven Thomasb02664d2017-07-26 18:48:28 -07001340void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1341 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001342 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001344 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 return;
1346 }
1347
1348 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001349 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001350 return;
1351 }
1352
Jamie Gennisd1700752013-10-14 12:22:52 -07001353 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354
Jamie Gennisd1700752013-10-14 12:22:52 -07001355 { // Scope for the lock
1356 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001358 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001359 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001360 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001361
1362 if (needsHwVsync) {
1363 enableHardwareVsync();
1364 } else {
1365 disableHardwareVsync(false);
1366 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001367}
1368
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001369void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001370 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1371 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001372}
1373
Lloyd Pique715a2c12017-12-14 17:18:08 -08001374void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1375 HWC2::Connection connection) {
1376 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1377 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378
Lloyd Piqueba04e622017-12-14 17:11:26 -08001379 // Ignore events that do not have the right sequenceId.
1380 if (sequenceId != getBE().mComposerSequenceId) {
1381 return;
1382 }
1383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Only lock if we're not on the main thread. This function is normally
1385 // called on a hwbinder thread, but for the primary display it's called on
1386 // the main thread with the state lock already held, so don't attempt to
1387 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001388 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001389
Lloyd Pique715a2c12017-12-14 17:18:08 -08001390 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001391
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001392 if (std::this_thread::get_id() == mMainThreadId) {
1393 // Process all pending hot plug events immediately if we are on the main thread.
1394 processDisplayHotplugEventsLocked();
1395 }
1396
Lloyd Piqueba04e622017-12-14 17:11:26 -08001397 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001398}
1399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400void SurfaceFlinger::onRefreshReceived(int sequenceId,
1401 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001402 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001405 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001406 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001407}
1408
Dan Stoza9e56aa02015-11-02 13:00:03 -08001409void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001410 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001412 getHwComposer().setVsyncEnabled(disp,
1413 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001414}
1415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001417void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001418 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419 // Clear the drawing state so that the logic inside of
1420 // handleTransactionLocked will fire. It will determine the delta between
1421 // mCurrentState and mDrawingState and re-apply all changes when we make the
1422 // transition.
1423 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001424 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001425 mDisplays.clear();
1426}
1427
Steven Thomas050b2c82017-03-06 11:45:16 -08001428void SurfaceFlinger::updateVrFlinger() {
1429 if (!mVrFlinger)
1430 return;
1431 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001432 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001433 return;
1434 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435
David Sodman105b7dc2017-11-04 20:28:14 -07001436 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 ALOGE("Vr flinger is only supported for remote hardware composer"
1438 " service connections. Ignoring request to transition to vr"
1439 " flinger.");
1440 mVrFlingerRequestsDisplay = false;
1441 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001442 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 int currentDisplayPowerMode = getDisplayDeviceLocked(
1447 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001448
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001451 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001454 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001455 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1456 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001457 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
David Sodman105b7dc2017-11-04 20:28:14 -07001459 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1460 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001461
1462 if (vrFlingerRequestsDisplay) {
1463 mVrFlinger->GrantDisplayOwnership();
1464 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001466 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001467
1468 mVisibleRegionsDirty = true;
1469 invalidateHwcGeometry();
1470
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1473 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1474 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001477 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 const nsecs_t period = activeConfig->getVsyncPeriod();
1479 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 // Use phase of 0 since phase is not known.
1482 // Use latency of 0, which will snap to the ideal latency.
1483 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001484
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485 android_atomic_or(1, &mRepaintEverything);
1486 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001487}
1488
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001490 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001491 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001493 bool frameMissed = !mHadClientComposition &&
1494 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001495 (mPreviousPresentFence->getSignalTime() ==
1496 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001497 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001498 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001499 mTimeStats.incrementMissedFrames();
1500 if (mPropagateBackpressure) {
1501 signalLayerUpdate();
1502 break;
1503 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001504 }
Dan Stoza50182882016-07-08 12:02:20 -07001505
Steven Thomas050b2c82017-03-06 11:45:16 -08001506 // Now that we're going to make it to the handleMessageTransaction()
1507 // call below it's safe to call updateVrFlinger(), which will
1508 // potentially trigger a display handoff.
1509 updateVrFlinger();
1510
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 bool refreshNeeded = handleMessageTransaction();
1512 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001513 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001515 // Signal a refresh if a transaction modified the window state,
1516 // a new buffer was latched, or if HWC has requested a full
1517 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 signalRefresh();
1519 }
1520 break;
1521 }
1522 case MessageQueue::REFRESH: {
1523 handleMessageRefresh();
1524 break;
1525 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526 }
1527}
1528
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001530 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001532 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001533 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001535 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001536}
1537
Dan Stoza6b9454d2014-11-07 16:00:59 -08001538bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001540 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001541}
1542
1543void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001545
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001546 mRefreshPending = false;
1547
Pablo Ceballos40845df2016-01-25 17:41:15 -08001548 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001549
Brian Andersond6927fb2016-07-23 23:37:30 -07001550 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001551 rebuildLayerStacks();
1552 setUpHWComposer();
1553 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001555 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001556 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001558
David Sodman105b7dc2017-11-04 20:28:14 -07001559 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001560
1561 mHadClientComposition = false;
1562 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1563 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1564 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001565 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001566 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001567 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001568
Dan Stoza9e56aa02015-11-02 13:00:03 -08001569 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001571
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572void SurfaceFlinger::doDebugFlashRegions()
1573{
1574 // is debugging enabled
1575 if (CC_LIKELY(!mDebugRegion))
1576 return;
1577
1578 const bool repaintEverything = mRepaintEverything;
1579 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1580 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001581 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 // transform the dirty region into this screen's coordinate space
1583 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1584 if (!dirtyRegion.isEmpty()) {
1585 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001586 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587
1588 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001590 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001591 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1592
Mathias Agopianda27af92012-09-13 18:17:13 -07001593 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594 }
1595 }
1596 }
1597
1598 postFramebuffer();
1599
1600 if (mDebugRegion > 1) {
1601 usleep(mDebugRegion * 1000);
1602 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001603
Dan Stoza9e56aa02015-11-02 13:00:03 -08001604 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001605 auto& displayDevice = mDisplays[displayId];
1606 if (!displayDevice->isDisplayOn()) {
1607 continue;
1608 }
1609
David Sodman105b7dc2017-11-04 20:28:14 -07001610 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1611 ALOGE_IF(result != NO_ERROR,
1612 "prepareFrame for display %zd failed:"
1613 " %d (%s)",
1614 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001615 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616}
1617
Adrian Roos1e1a1282017-11-01 19:05:31 +01001618void SurfaceFlinger::doTracing(const char* where) {
1619 ATRACE_CALL();
1620 ATRACE_NAME(where);
1621 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001622 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001623 }
1624}
1625
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001626void SurfaceFlinger::logLayerStats() {
1627 ATRACE_CALL();
1628 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1629 int32_t hwcId = -1;
1630 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1631 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1632 if (displayDevice->isPrimary()) {
1633 hwcId = displayDevice->getHwcDisplayId();
1634 break;
1635 }
1636 }
1637 if (hwcId < 0) {
1638 ALOGE("LayerStats: Hmmm, no primary display?");
1639 return;
1640 }
1641 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1642 }
1643}
1644
Brian Andersond6927fb2016-07-23 23:37:30 -07001645void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001646{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001647 ATRACE_CALL();
1648 ALOGV("preComposition");
1649
Mathias Agopiancd60f992012-08-16 16:28:27 -07001650 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001651 mDrawingState.traverseInZOrder([&](Layer* layer) {
1652 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653 needExtraInvalidate = true;
1654 }
Robert Carr2047fae2016-11-28 14:09:09 -08001655 });
1656
Mathias Agopiancd60f992012-08-16 16:28:27 -07001657 if (needExtraInvalidate) {
1658 signalLayerUpdate();
1659 }
1660}
1661
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662void SurfaceFlinger::updateCompositorTiming(
1663 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1664 std::shared_ptr<FenceTime>& presentFenceTime) {
1665 // Update queue of past composite+present times and determine the
1666 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001667 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001669 while (!getBE().mCompositePresentTimes.empty()) {
1670 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 // Cached values should have been updated before calling this method,
1672 // which helps avoid duplicate syscalls.
1673 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1674 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1675 break;
1676 }
1677 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001678 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 }
1680
1681 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001682 while (getBE().mCompositePresentTimes.size() > 16) {
1683 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 }
1685
Brian Andersond0010582017-03-07 13:20:31 -08001686 setCompositorTimingSnapped(
1687 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1688}
1689
1690void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1691 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 // Integer division and modulo round toward 0 not -inf, so we need to
1693 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001694 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1696 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1697
Brian Andersond0010582017-03-07 13:20:31 -08001698 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1699 if (idealLatency <= 0) {
1700 idealLatency = vsyncInterval;
1701 }
1702
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001703 // Snap the latency to a value that removes scheduling jitter from the
1704 // composition and present times, which often have >1ms of jitter.
1705 // Reducing jitter is important if an app attempts to extrapolate
1706 // something (such as user input) to an accurate diasplay time.
1707 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1708 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001709 nsecs_t bias = vsyncInterval / 2;
1710 int64_t extraVsyncs =
1711 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1712 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1713 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714
David Sodman99974d22017-11-28 12:04:33 -08001715 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1716 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1717 getBE().mCompositorTiming.interval = vsyncInterval;
1718 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001719}
1720
1721void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001722{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 ATRACE_CALL();
1724 ALOGV("postComposition");
1725
Brian Anderson3546a3f2016-07-14 11:51:14 -07001726 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001727 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001728 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001729 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001730 }
1731
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001732 // |mStateLock| not needed as we are on the main thread
1733 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001734
David Sodman73beded2017-11-15 11:56:06 -08001735 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001736 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001737 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001738 glCompositionDoneFenceTime =
1739 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001740 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001741 } else {
1742 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1743 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744
David Sodman73beded2017-11-15 11:56:06 -08001745 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001746 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001747 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001748 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001749
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001750 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1751 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1752
1753 // We use the refreshStartTime which might be sampled a little later than
1754 // when we started doing work for this frame, but that should be okay
1755 // since updateCompositorTiming has snapping logic.
1756 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001757 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001758 CompositorTiming compositorTiming;
1759 {
David Sodman99974d22017-11-28 12:04:33 -08001760 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1761 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001762 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763
Robert Carr2047fae2016-11-28 14:09:09 -08001764 mDrawingState.traverseInZOrder([&](Layer* layer) {
1765 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001766 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001767 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001768 recordBufferingStats(layer->getName().string(),
1769 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001770 }
Robert Carr2047fae2016-11-28 14:09:09 -08001771 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001772
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001773 if (presentFenceTime->isValid()) {
1774 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001775 enableHardwareVsync();
1776 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001777 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001778 }
1779 }
1780
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001781 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001782 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001783 enableHardwareVsync();
1784 }
1785 }
1786
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001787 if (mAnimCompositionPending) {
1788 mAnimCompositionPending = false;
1789
Brian Anderson4e606e32017-03-16 15:34:57 -07001790 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001791 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001792 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001793 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001794 // The HWC doesn't support present fences, so use the refresh
1795 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001797 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001798 mAnimFrameTracker.setActualPresentTime(presentTime);
1799 }
1800 mAnimFrameTracker.advanceFrame();
1801 }
Dan Stozab90cf072015-03-05 11:05:59 -08001802
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001803 mTimeStats.incrementTotalFrames();
1804 if (mHadClientComposition) {
1805 mTimeStats.incrementClientCompositionFrames();
1806 }
1807
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001808 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1809 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001810 return;
1811 }
1812
1813 nsecs_t currentTime = systemTime();
1814 if (mHasPoweredOff) {
1815 mHasPoweredOff = false;
1816 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001817 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001819 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1820 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001821 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001822 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001823 }
David Sodman4a36e932017-11-07 14:29:47 -08001824 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001825 }
David Sodman4a36e932017-11-07 14:29:47 -08001826 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827}
1828
1829void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 ATRACE_CALL();
1831 ALOGV("rebuildLayerStacks");
1832
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001834 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001835 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001836 mVisibleRegionsDirty = false;
1837 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001838
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1840 Region opaqueRegion;
1841 Region dirtyRegion;
1842 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001843 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001844 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1845 const Transform& tr(displayDevice->getTransform());
1846 const Rect bounds(displayDevice->getBounds());
1847 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001848 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001849
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001851 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001852 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1853 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001854 Region drawRegion(tr.transform(
1855 layer->visibleNonTransparentRegion));
1856 drawRegion.andSelf(bounds);
1857 if (!drawRegion.isEmpty()) {
1858 layersSortedByZ.add(layer);
1859 } else {
1860 // Clear out the HWC layer if this layer was
1861 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001862 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001863 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001865 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001866 // WM changes displayDevice->layerStack upon sleep/awake.
1867 // Here we make sure we delete the HWC layers even if
1868 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001869 hwcLayerDestroyed = layer->destroyHwcLayer(
1870 displayDevice->getHwcDisplayId());
1871 }
1872
1873 // If a layer is not going to get a release fence because
1874 // it is invisible, but it is also going to release its
1875 // old buffer, add it to the list of layers needing
1876 // fences.
1877 if (hwcLayerDestroyed) {
1878 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1879 mLayersWithQueuedFrames.cend(), layer);
1880 if (found != mLayersWithQueuedFrames.cend()) {
1881 layersNeedingFences.add(layer);
1882 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001883 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001884 });
1885 }
1886 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001887 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001888 displayDevice->undefinedRegion.set(bounds);
1889 displayDevice->undefinedRegion.subtractSelf(
1890 tr.transform(opaqueRegion));
1891 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001892 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001893 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001895
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001896// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001898// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001899// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001900// The returned HDR data space is one of
1901// - Dataspace::UNKNOWN
1902// - Dataspace::BT2020_HLG
1903// - Dataspace::BT2020_PQ
1904Dataspace SurfaceFlinger::getBestDataspace(
1905 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1906 Dataspace bestDataSpace = Dataspace::SRGB;
1907 *outHdrDataSpace = Dataspace::UNKNOWN;
1908
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001910 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 case Dataspace::V0_SCRGB:
1912 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001913 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001914 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001915 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916 case Dataspace::BT2020_PQ:
1917 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001918 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001920 case Dataspace::BT2020_HLG:
1921 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001922 // When there's mixed PQ content and HLG content, we set the HDR
1923 // data space to be BT2020_PQ and convert HLG to PQ.
1924 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1925 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001926 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 break;
1928 default:
1929 break;
1930 }
Romain Guy54f154a2017-10-24 21:40:32 +01001931 }
1932
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001933 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001934}
1935
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001938 ColorMode* outMode, Dataspace* outDataSpace,
1939 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1941 *outMode = ColorMode::NATIVE;
1942 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001943 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001945 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001946
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001947 Dataspace hdrDataSpace;
1948 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1949
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001950 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001951 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001952 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001953 if (isHdr) {
1954 bestDataSpace = hdrDataSpace;
1955 }
1956
Chia-I Wu0d711262018-05-21 15:19:35 -07001957 RenderIntent intent;
1958 switch (mDisplayColorSetting) {
1959 case DisplayColorSetting::MANAGED:
1960 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001961 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001962 break;
1963 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001964 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001965 break;
1966 default: // vendor display color setting
1967 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1968 break;
1969 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001970
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001971 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001972}
1973
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 ATRACE_CALL();
1976 ALOGV("setUpHWComposer");
1977
Jesse Hall028dc8f2013-08-20 16:35:32 -07001978 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001979 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001980 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1981 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1982
1983 // If nothing has changed (!dirty), don't recompose.
1984 // If something changed, but we don't currently have any visible layers,
1985 // and didn't when we last did a composition, then skip it this time.
1986 // The second rule does two things:
1987 // - When all layers are removed from a display, we'll emit one black
1988 // frame, then nothing more until we get new layers.
1989 // - When a display is created with a private layer stack, we won't
1990 // emit any black frames until a layer is added to the layer stack.
1991 bool mustRecompose = dirty && !(empty && wasEmpty);
1992
1993 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1994 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1995 mustRecompose ? "doing" : "skipping",
1996 dirty ? "+" : "-",
1997 empty ? "+" : "-",
1998 wasEmpty ? "+" : "-");
1999
Dan Stoza71433162014-02-04 16:22:36 -08002000 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002001
2002 if (mustRecompose) {
2003 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2004 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002005 }
2006
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 // build the h/w work list
2008 if (CC_UNLIKELY(mGeometryInvalid)) {
2009 mGeometryInvalid = false;
2010 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2011 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2012 const auto hwcId = displayDevice->getHwcDisplayId();
2013 if (hwcId >= 0) {
2014 const Vector<sp<Layer>>& currentLayers(
2015 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002016 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002017 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002019 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002022 }
2023 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002024
Robert Carrae060832016-11-28 10:51:00 -08002025 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002026 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002028 }
2029 }
2030 }
2031 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 }
Riley Andrews03414a12014-07-01 14:22:59 -07002033
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 // Set the per-frame data
2035 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2036 auto& displayDevice = mDisplays[displayId];
2037 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002038
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 if (hwcId < 0) {
2040 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002041 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002042 if (mDrawingState.colorMatrixChanged) {
2043 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2044 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002045 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2046 "display %zd: %d", displayId, result);
2047 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002049 if (layer->isHdrY410()) {
2050 layer->forceClientComposition(hwcId);
2051 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2052 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002053 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002054 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002055 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2056 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002057 !displayDevice->hasHLGSupport()) {
2058 layer->forceClientComposition(hwcId);
2059 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002060
chaviwc9232ed2017-11-14 15:31:15 -08002061 if (layer->getForceClientComposition(hwcId)) {
2062 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2063 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2064 continue;
2065 }
2066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 layer->setPerFrameData(displayDevice);
2068 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002069
2070 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002071 ColorMode colorMode;
2072 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002073 RenderIntent renderIntent;
2074 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2075 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002076 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 }
2078
Chia-I Wu28f320b2018-05-03 11:02:56 -07002079 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002080
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002082 auto& displayDevice = mDisplays[displayId];
2083 if (!displayDevice->isDisplayOn()) {
2084 continue;
2085 }
2086
David Sodman105b7dc2017-11-04 20:28:14 -07002087 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2089 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002090 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002091}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002092
Mathias Agopiancd60f992012-08-16 16:28:27 -07002093void SurfaceFlinger::doComposition() {
2094 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 ALOGV("doComposition");
2096
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002097 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002098 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002099 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002100 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002101 // transform the dirty region into this screen's coordinate space
2102 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002103
2104 // repaint the framebuffer (if needed)
2105 doDisplayComposition(hw, dirtyRegion);
2106
Mathias Agopiancd60f992012-08-16 16:28:27 -07002107 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002108 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002109 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002110 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002111 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002112}
2113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114void SurfaceFlinger::postFramebuffer()
2115{
Mathias Agopian841cde52012-03-01 15:44:37 -08002116 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002118
Mathias Agopiana44b0412011-10-16 18:46:35 -07002119 const nsecs_t now = systemTime();
2120 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002121
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2123 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002124 if (!displayDevice->isDisplayOn()) {
2125 continue;
2126 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127 const auto hwcId = displayDevice->getHwcDisplayId();
2128 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002129 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002130 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002131 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002132 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002134 // The layer buffer from the previous frame (if any) is released
2135 // by HWC only when the release fence from this frame (if any) is
2136 // signaled. Always get the release fence from HWC first.
2137 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002138 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002139
2140 // If the layer was client composited in the previous frame, we
2141 // need to merge with the previous client target acquire fence.
2142 // Since we do not track that, always merge with the current
2143 // client target acquire fence when it is available, even though
2144 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002146 releaseFence = Fence::merge("LayerRelease", releaseFence,
2147 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002148 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002149
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 layer->onLayerDisplayed(releaseFence);
2151 }
Chia-I Wu83806892017-11-16 10:50:20 -08002152
2153 // We've got a list of layers needing fences, that are disjoint with
2154 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2155 // supply them with the present fence.
2156 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002157 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002158 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2159 layer->onLayerDisplayed(presentFence);
2160 }
2161 }
2162
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002164 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002165 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002166 }
2167
Mathias Agopiana44b0412011-10-16 18:46:35 -07002168 mLastSwapBufferTime = systemTime() - now;
2169 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002170
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002171 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002172 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2173 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2174 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2175 logFrameStats();
2176 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178}
2179
Mathias Agopian87baae12012-07-31 12:38:26 -07002180void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002181{
Mathias Agopian841cde52012-03-01 15:44:37 -08002182 ATRACE_CALL();
2183
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002184 // here we keep a copy of the drawing state (that is the state that's
2185 // going to be overwritten by handleTransactionLocked()) outside of
2186 // mStateLock so that the side-effects of the State assignment
2187 // don't happen with mStateLock held (which can cause deadlocks).
2188 State drawingState(mDrawingState);
2189
Mathias Agopianca4d3602011-05-19 15:38:14 -07002190 Mutex::Autolock _l(mStateLock);
2191 const nsecs_t now = systemTime();
2192 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
Mathias Agopianca4d3602011-05-19 15:38:14 -07002194 // Here we're guaranteed that some transaction flags are set
2195 // so we can call handleTransactionLocked() unconditionally.
2196 // We call getTransactionFlags(), which will also clear the flags,
2197 // with mStateLock held to guarantee that mCurrentState won't change
2198 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002199
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002200 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002201 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002202 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002203
Mathias Agopianca4d3602011-05-19 15:38:14 -07002204 mLastTransactionTime = systemTime() - now;
2205 mDebugInTransaction = 0;
2206 invalidateHwcGeometry();
2207 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002208}
2209
Lloyd Pique715a2c12017-12-14 17:18:08 -08002210DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002211 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002212 // Figure out whether the event is for the primary display or an
2213 // external display by matching the Hwc display id against one for a
2214 // connected display. If we did not find a match, we then check what
2215 // displays are not already connected to determine the type. If we don't
2216 // have a connected primary display, we assume the new display is meant to
2217 // be the primary display, and then if we don't have an external display,
2218 // we assume it is that.
2219 const auto primaryDisplayId =
2220 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2221 const auto externalDisplayId =
2222 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2223 if (primaryDisplayId && primaryDisplayId == display) {
2224 return DisplayDevice::DISPLAY_PRIMARY;
2225 } else if (externalDisplayId && externalDisplayId == display) {
2226 return DisplayDevice::DISPLAY_EXTERNAL;
2227 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2228 return DisplayDevice::DISPLAY_PRIMARY;
2229 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2230 return DisplayDevice::DISPLAY_EXTERNAL;
2231 }
2232
2233 return DisplayDevice::DISPLAY_ID_INVALID;
2234}
2235
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2237 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002238 auto displayType = determineDisplayType(event.display, event.connection);
2239 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2240 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2241 continue;
2242 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002243
2244 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2245 ALOGE("External displays are not supported by the vr hardware composer.");
2246 continue;
2247 }
2248
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002250
2251 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002252 if (!mBuiltinDisplays[displayType].get()) {
2253 ALOGV("Creating built in display %d", displayType);
2254 mBuiltinDisplays[displayType] = new BBinder();
2255 // All non-virtual displays are currently considered secure.
2256 DisplayDeviceState info(displayType, true);
2257 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2258 "Built-in Screen" : "External Screen";
2259 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002260 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002261 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002262 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002263 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002264
Lloyd Piquefcd86612017-12-14 17:15:36 -08002265 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2266 if (idx >= 0) {
2267 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002268 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002269 mCurrentState.displays.removeItemsAt(idx);
2270 }
2271 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002272 }
2273
2274 processDisplayChangesLocked();
2275 }
2276
2277 mPendingHotplugEvents.clear();
2278}
2279
Lloyd Pique09594832018-01-22 17:48:03 -08002280sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2281 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2282 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002284 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002285
Lloyd Pique09594832018-01-22 17:48:03 -08002286 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002287 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002288 for (ColorMode colorMode : modes) {
2289 switch (colorMode) {
2290 case ColorMode::DISPLAY_P3:
2291 case ColorMode::ADOBE_RGB:
2292 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002294 break;
2295 default:
2296 break;
2297 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298
2299 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2300 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002301 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002302 }
2303 }
2304
Peiyong Lin62665892018-04-16 11:07:44 -07002305 HdrCapabilities hdrCapabilities;
2306 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002307
2308 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2309 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2310
2311 /*
2312 * Create our display's surface
2313 */
2314 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2315 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2316 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2317 renderSurface->setNativeWindow(nativeWindow.get());
2318 const int displayWidth = renderSurface->queryWidth();
2319 const int displayHeight = renderSurface->queryHeight();
2320
2321 // Make sure that composition can never be stalled by a virtual display
2322 // consumer that isn't processing buffers fast enough. We have to do this
2323 // in two places:
2324 // * Here, in case the display is composed entirely by HWC.
2325 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2326 // window's swap interval in eglMakeCurrent, so they'll override the
2327 // interval we set here.
2328 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2329 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2330 }
2331
2332 // virtual displays are always considered enabled
2333 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2334 : HWC_POWER_MODE_OFF;
2335
2336 sp<DisplayDevice> hw =
2337 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2338 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002339 hasWideColorGamut, hdrCapabilities,
2340 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002341 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002342
2343 if (maxFrameBufferAcquiredBuffers >= 3) {
2344 nativeWindowSurface->preallocateBuffers();
2345 }
2346
2347 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2349 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002350 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002351 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002352 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002353 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2354 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002355 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2356 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2357 }
Lloyd Pique09594832018-01-22 17:48:03 -08002358 hw->setLayerStack(state.layerStack);
2359 hw->setProjection(state.orientation, state.viewport, state.frame);
2360 hw->setDisplayName(state.displayName);
2361
2362 return hw;
2363}
2364
Lloyd Pique347200f2017-12-14 17:00:15 -08002365void SurfaceFlinger::processDisplayChangesLocked() {
2366 // here we take advantage of Vector's copy-on-write semantics to
2367 // improve performance by skipping the transaction entirely when
2368 // know that the lists are identical
2369 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2370 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2371 if (!curr.isIdenticalTo(draw)) {
2372 mVisibleRegionsDirty = true;
2373 const size_t cc = curr.size();
2374 size_t dc = draw.size();
2375
2376 // find the displays that were removed
2377 // (ie: in drawing state but not in current state)
2378 // also handle displays that changed
2379 // (ie: displays that are in both lists)
2380 for (size_t i = 0; i < dc;) {
2381 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2382 if (j < 0) {
2383 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002384 // Call makeCurrent() on the primary display so we can
2385 // be sure that nothing associated with this display
2386 // is current.
2387 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2388 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2389 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2390 if (hw != nullptr) hw->disconnect(getHwComposer());
2391 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2392 mEventThread->onHotplugReceived(draw[i].type, false);
2393 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002394 } else {
2395 // this display is in both lists. see if something changed.
2396 const DisplayDeviceState& state(curr[j]);
2397 const wp<IBinder>& display(curr.keyAt(j));
2398 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2399 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2400 if (state_binder != draw_binder) {
2401 // changing the surface is like destroying and
2402 // recreating the DisplayDevice, so we just remove it
2403 // from the drawing state, so that it get re-added
2404 // below.
2405 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2406 if (hw != nullptr) hw->disconnect(getHwComposer());
2407 mDisplays.removeItem(display);
2408 mDrawingState.displays.removeItemsAt(i);
2409 dc--;
2410 // at this point we must loop to the next item
2411 continue;
2412 }
2413
2414 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2415 if (disp != nullptr) {
2416 if (state.layerStack != draw[i].layerStack) {
2417 disp->setLayerStack(state.layerStack);
2418 }
2419 if ((state.orientation != draw[i].orientation) ||
2420 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2421 disp->setProjection(state.orientation, state.viewport, state.frame);
2422 }
2423 if (state.width != draw[i].width || state.height != draw[i].height) {
2424 disp->setDisplaySize(state.width, state.height);
2425 }
2426 }
2427 }
2428 ++i;
2429 }
2430
2431 // find displays that were added
2432 // (ie: in current state but not in drawing state)
2433 for (size_t i = 0; i < cc; i++) {
2434 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2435 const DisplayDeviceState& state(curr[i]);
2436
2437 sp<DisplaySurface> dispSurface;
2438 sp<IGraphicBufferProducer> producer;
2439 sp<IGraphicBufferProducer> bqProducer;
2440 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002441 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442
2443 int32_t hwcId = -1;
2444 if (state.isVirtualDisplay()) {
2445 // Virtual displays without a surface are dormant:
2446 // they have external state (layer stack, projection,
2447 // etc.) but no internal state (i.e. a DisplayDevice).
2448 if (state.surface != nullptr) {
2449 // Allow VR composer to use virtual displays.
2450 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2451 int width = 0;
2452 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2453 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2454 int height = 0;
2455 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2456 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2457 int intFormat = 0;
2458 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2459 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002460 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002461
2462 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2463 }
2464
2465 // TODO: Plumb requested format back up to consumer
2466
2467 sp<VirtualDisplaySurface> vds =
2468 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2469 bqProducer, bqConsumer,
2470 state.displayName);
2471
2472 dispSurface = vds;
2473 producer = vds;
2474 }
2475 } else {
2476 ALOGE_IF(state.surface != nullptr,
2477 "adding a supported display, but rendering "
2478 "surface is provided (%p), ignoring it",
2479 state.surface.get());
2480
2481 hwcId = state.type;
2482 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2483 producer = bqProducer;
2484 }
2485
2486 const wp<IBinder>& display(curr.keyAt(i));
2487 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002488 mDisplays.add(display,
2489 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2490 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 if (!state.isVirtualDisplay()) {
2492 mEventThread->onHotplugReceived(state.type, true);
2493 }
2494 }
2495 }
2496 }
2497 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002498
2499 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002500}
2501
Mathias Agopian87baae12012-07-31 12:38:26 -07002502void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002503{
Dan Stoza7dde5992015-05-22 09:51:44 -07002504 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002505 mCurrentState.traverseInZOrder([](Layer* layer) {
2506 layer->notifyAvailableFrames();
2507 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 /*
2510 * Traversal of the children
2511 * (perform the transaction for each of them if needed)
2512 */
2513
Mathias Agopian3559b072012-08-15 13:46:03 -07002514 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002515 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002517 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
2519 const uint32_t flags = layer->doTransaction(0);
2520 if (flags & Layer::eVisibleRegion)
2521 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002522 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523 }
2524
2525 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002526 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 */
2528
Mathias Agopiane57f2922012-08-09 16:29:12 -07002529 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002530 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002534 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002535 // The transform hint might have changed for some layers
2536 // (either because a display has changed, or because a layer
2537 // as changed).
2538 //
2539 // Walk through all the layers in currentLayers,
2540 // and update their transform hint.
2541 //
2542 // If a layer is visible only on a single display, then that
2543 // display is used to calculate the hint, otherwise we use the
2544 // default display.
2545 //
2546 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2547 // the hint is set before we acquire a buffer from the surface texture.
2548 //
2549 // NOTE: layer transactions have taken place already, so we use their
2550 // drawing state. However, SurfaceFlinger's own transaction has not
2551 // happened yet, so we must use the current state layer list
2552 // (soon to become the drawing state list).
2553 //
2554 sp<const DisplayDevice> disp;
2555 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002556 bool first = true;
2557 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002558 // NOTE: we rely on the fact that layers are sorted by
2559 // layerStack first (so we don't have to traverse the list
2560 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002561 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002562 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002563 currentlayerStack = layerStack;
2564 // figure out if this layerstack is mirrored
2565 // (more than one display) if so, pick the default display,
2566 // if not, pick the only display it's on.
2567 disp.clear();
2568 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2569 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002570 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002571 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002572 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002573 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002574 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002575 break;
2576 }
2577 }
2578 }
2579 }
Chet Haase91d25932013-04-11 15:24:55 -07002580
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002581 if (disp == nullptr) {
2582 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2583 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002584
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002585 // could be null when this layer is using a layerStack
2586 // that is not visible on any display. Also can occur at
2587 // screen off/on times.
2588 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002589 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002590
2591 // disp can be null if there is no display available at all to get
2592 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002593 if (disp != nullptr) {
2594 layer->updateTransformHint(disp);
2595 }
Robert Carr2047fae2016-11-28 14:09:09 -08002596
2597 first = false;
2598 });
Mathias Agopian84300952012-11-21 16:02:13 -08002599 }
2600
2601
Mathias Agopian3559b072012-08-15 13:46:03 -07002602 /*
2603 * Perform our own transaction if needed
2604 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002605
2606 if (mLayersAdded) {
2607 mLayersAdded = false;
2608 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002609 mVisibleRegionsDirty = true;
2610 }
2611
2612 // some layers might have been removed, so
2613 // we need to update the regions they're exposing.
2614 if (mLayersRemoved) {
2615 mLayersRemoved = false;
2616 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002617 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002618 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002619 // this layer is not visible anymore
2620 // TODO: we could traverse the tree from front to back and
2621 // compute the actual visible region
2622 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002623 Region visibleReg;
2624 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002625 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002626 }
Robert Carr2047fae2016-11-28 14:09:09 -08002627 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 }
2629
2630 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002631
2632 updateCursorAsync();
2633}
2634
2635void SurfaceFlinger::updateCursorAsync()
2636{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2638 auto& displayDevice = mDisplays[displayId];
2639 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002640 continue;
2641 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002642
2643 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2644 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002645 }
2646 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002647}
2648
2649void SurfaceFlinger::commitTransaction()
2650{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002651 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 for (const auto& l : mLayersPendingRemoval) {
2654 recordBufferingStats(l->getName().string(),
2655 l->getOccupancyHistory(true));
2656 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002657 }
2658 mLayersPendingRemoval.clear();
2659 }
2660
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002661 // If this transaction is part of a window animation then the next frame
2662 // we composite should be considered an animation as well.
2663 mAnimCompositionPending = mAnimTransactionPending;
2664
Mathias Agopian4fec8732012-06-29 14:12:52 -07002665 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002666 // clear the "changed" flags in current state
2667 mCurrentState.colorMatrixChanged = false;
2668
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 mDrawingState.traverseInZOrder([](Layer* layer) {
2670 layer->commitChildList();
2671 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002672 mTransactionPending = false;
2673 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675}
2676
Chia-I Wuab0c3192017-08-01 11:29:00 -07002677void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002678 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679{
Mathias Agopian841cde52012-03-01 15:44:37 -08002680 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002682
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 Region aboveOpaqueLayers;
2684 Region aboveCoveredLayers;
2685 Region dirty;
2686
Mathias Agopian87baae12012-07-31 12:38:26 -07002687 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688
Robert Carr2047fae2016-11-28 14:09:09 -08002689 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002691 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692
Jesse Hall01e29052013-02-19 16:13:35 -08002693 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002694 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002695 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002696
Mathias Agopianab028732010-03-16 16:41:46 -07002697 /*
2698 * opaqueRegion: area of a surface that is fully opaque.
2699 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002701
2702 /*
2703 * visibleRegion: area of a surface that is visible on screen
2704 * and not fully transparent. This is essentially the layer's
2705 * footprint minus the opaque regions above it.
2706 * Areas covered by a translucent surface are considered visible.
2707 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002709
2710 /*
2711 * coveredRegion: area of a surface that is covered by all
2712 * visible regions above it (which includes the translucent areas).
2713 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002715
Jesse Halla8026d22012-09-25 13:25:04 -07002716 /*
2717 * transparentRegion: area of a surface that is hinted to be completely
2718 * transparent. This is only used to tell when the layer has no visible
2719 * non-transparent regions and can be removed from the layer list. It
2720 * does not affect the visibleRegion of this layer or any layers
2721 * beneath it. The hint may not be correct if apps don't respect the
2722 * SurfaceView restrictions (which, sadly, some don't).
2723 */
2724 Region transparentRegion;
2725
Mathias Agopianab028732010-03-16 16:41:46 -07002726
2727 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002728 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002729 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002730 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002733 if (!visibleRegion.isEmpty()) {
2734 // Remove the transparent area from the visible region
2735 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002736 if (tr.preserveRects()) {
2737 // transform the transparent region
2738 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002740 // transformation too complex, can't do the
2741 // transparent region optimization.
2742 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 }
Mathias Agopianab028732010-03-16 16:41:46 -07002744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745
Mathias Agopianab028732010-03-16 16:41:46 -07002746 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002748 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002749 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2750 // the opaque region is the layer's footprint
2751 opaqueRegion = visibleRegion;
2752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753 }
2754 }
2755
Robert Carre5f4f692018-01-12 13:12:28 -08002756 if (visibleRegion.isEmpty()) {
2757 layer->clearVisibilityRegions();
2758 return;
2759 }
2760
Mathias Agopianab028732010-03-16 16:41:46 -07002761 // Clip the covered region to the visible region
2762 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2763
2764 // Update aboveCoveredLayers for next (lower) layer
2765 aboveCoveredLayers.orSelf(visibleRegion);
2766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 // subtract the opaque region covered by the layers above us
2768 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769
2770 // compute this layer's dirty region
2771 if (layer->contentDirty) {
2772 // we need to invalidate the whole region
2773 dirty = visibleRegion;
2774 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 layer->contentDirty = false;
2777 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002778 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002779 * the exposed region consists of two components:
2780 * 1) what's VISIBLE now and was COVERED before
2781 * 2) what's EXPOSED now less what was EXPOSED before
2782 *
2783 * note that (1) is conservative, we start with the whole
2784 * visible region but only keep what used to be covered by
2785 * something -- which mean it may have been exposed.
2786 *
2787 * (2) handles areas that were not covered by anything but got
2788 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002789 */
Mathias Agopianab028732010-03-16 16:41:46 -07002790 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002791 const Region oldVisibleRegion = layer->visibleRegion;
2792 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002793 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2794 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 }
2796 dirty.subtractSelf(aboveOpaqueLayers);
2797
2798 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002799 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
Mathias Agopianab028732010-03-16 16:41:46 -07002801 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002803
Jesse Halla8026d22012-09-25 13:25:04 -07002804 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 layer->setVisibleRegion(visibleRegion);
2806 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002807 layer->setVisibleNonTransparentRegion(
2808 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002809 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810
Mathias Agopian87baae12012-07-31 12:38:26 -07002811 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812}
2813
Chia-I Wuab0c3192017-08-01 11:29:00 -07002814void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002815 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002816 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002817 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002818 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002819 }
2820 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002821}
2822
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 ALOGV("handlePageFlip");
2826
Brian Andersond6927fb2016-07-23 23:37:30 -07002827 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002830 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002831 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002832
2833 // Store the set of layers that need updates. This set must not change as
2834 // buffers are being latched, as this could result in a deadlock.
2835 // Example: Two producers share the same command stream and:
2836 // 1.) Layer 0 is latched
2837 // 2.) Layer 0 gets a new frame
2838 // 2.) Layer 1 gets a new frame
2839 // 3.) Layer 1 is latched.
2840 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2841 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002842 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002843 if (layer->hasQueuedFrame()) {
2844 frameQueued = true;
2845 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002846 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002847 } else {
2848 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002850 } else {
2851 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852 }
Robert Carr2047fae2016-11-28 14:09:09 -08002853 });
2854
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002856 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002857 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002858 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002859 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002860 newDataLatched = true;
2861 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002862 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002863
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002864 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002865
2866 // If we will need to wake up at some time in the future to deal with a
2867 // queued frame that shouldn't be displayed during this vsync period, wake
2868 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002869 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002870 signalLayerUpdate();
2871 }
2872
2873 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002874 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875}
2876
Mathias Agopianad456f92011-01-13 17:53:01 -08002877void SurfaceFlinger::invalidateHwcGeometry()
2878{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002880}
2881
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002882
Fabien Sanglard830b8472016-11-30 16:35:58 -08002883void SurfaceFlinger::doDisplayComposition(
2884 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002885 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886{
Dan Stoza71433162014-02-04 16:22:36 -08002887 // We only need to actually compose the display if:
2888 // 1) It is being handled by hardware composer, which may need this to
2889 // keep its virtual display state machine in sync, or
2890 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002891 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002892 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002893 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002894 return;
2895 }
2896
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002898 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002899
2900 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002901 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902}
2903
Chia-I Wub02087d2017-11-09 10:19:54 -08002904bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002905{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002906 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002907
Chia-I Wub02087d2017-11-09 10:19:54 -08002908 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002909 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002910 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002911 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002912 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002913
Chia-I Wu8e50e692018-05-04 10:12:37 -07002914 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002915 bool needsLegacyColorMatrix = false;
2916 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002917
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 if (hasClientComposition) {
2919 ALOGV("hasClientComposition");
2920
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002921 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002922 if (displayDevice->hasWideColorGamut()) {
2923 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002924 }
2925 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002926 getBE().mRenderEngine->setDisplayMaxLuminance(
2927 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002928
Chia-I Wu8e50e692018-05-04 10:12:37 -07002929 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2930 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2931 HWC2::Capability::SkipClientColorTransform);
2932
2933 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2934 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002935 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002936 }
2937
Chia-I Wubbb44462018-05-21 15:33:27 -07002938 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002939 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002940 outputDataspace != Dataspace::UNKNOWN &&
2941 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002942
Chia-I Wu7f402902017-11-09 12:51:10 -08002943 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002944 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002946 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002947
2948 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002949 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002950 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2951 }
2952 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002953 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002954
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002955 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002957 // when using overlays, we assume a fully transparent framebuffer
2958 // NOTE: we could reduce how much we need to clear, for instance
2959 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002960 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002961 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002962 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002963 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002964 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002965 // we're left with the letterbox region
2966 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002968
2969 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002971
Mathias Agopianb9494d52012-04-18 02:28:45 -07002972 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002973 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002974 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002976 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002977 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002978
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002980 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002981 // scissor on the main display. It should never be needed
2982 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 const Rect& bounds(displayDevice->getBounds());
2984 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985 if (scissor != bounds) {
2986 // scissor doesn't match the screen's dimensions, so we
2987 // need to clear everything outside of it and enable
2988 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002989
Mathias Agopianf45c5102012-10-24 16:29:17 -07002990 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002992 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002993 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002994 }
2995 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002996 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002997
Mathias Agopian85d751c2012-08-29 16:59:24 -07002998 /*
2999 * and then, render the layers targeted at the framebuffer
3000 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003001
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 ALOGV("Rendering client layers");
3003 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003004 bool firstLayer = true;
3005 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3006 const Region clip(bounds.intersect(
3007 displayTransform.transform(layer->visibleRegion)));
3008 ALOGV("Layer: %s", layer->getName().string());
3009 ALOGV(" Composition type: %s",
3010 to_string(layer->getCompositionType(hwcId)).c_str());
3011 if (!clip.isEmpty()) {
3012 switch (layer->getCompositionType(hwcId)) {
3013 case HWC2::Composition::Cursor:
3014 case HWC2::Composition::Device:
3015 case HWC2::Composition::Sideband:
3016 case HWC2::Composition::SolidColor: {
3017 const Layer::State& state(layer->getDrawingState());
3018 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3019 layer->isOpaque(state) && (state.color.a == 1.0f)
3020 && hasClientComposition) {
3021 // never clear the very first layer since we're
3022 // guaranteed the FB is already cleared
3023 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003024 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003025 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003026 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003027 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003028 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003029 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3030 if (!legacyColorMatrixApplied) {
3031 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3032 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003033 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003034 } else if (legacyColorMatrixApplied) {
3035 getRenderEngine().setSaturationMatrix(mat4());
3036 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003037 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003038
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003039 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003040 break;
3041 }
3042 default:
3043 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003044 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003045 } else {
3046 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003047 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003048 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003049 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003050
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003051 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003052 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003053 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003054 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3055 getRenderEngine().setSaturationMatrix(mat4());
3056 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003057
Mathias Agopianf45c5102012-10-24 16:29:17 -07003058 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003059 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003060 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061}
3062
Fabien Sanglard830b8472016-11-30 16:35:58 -08003063void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3064 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003065 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003066 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067}
3068
Dan Stoza7d89d062015-04-30 13:29:25 -07003069status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003070 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003071 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 const sp<Layer>& lbc,
3073 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003074{
Dan Stoza7d89d062015-04-30 13:29:25 -07003075 // add this layer to the current state list
3076 {
3077 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003078 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003079 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3080 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003081 return NO_MEMORY;
3082 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003083 if (parent == nullptr) {
3084 mCurrentState.layersSortedByZ.add(lbc);
3085 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003086 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003087 ALOGE("addClientLayer called with a removed parent");
3088 return NAME_NOT_FOUND;
3089 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003090 parent->addChild(lbc);
3091 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003092
Yiwei Zhang243b3782018-05-15 17:40:04 -07003093 if (gbc != nullptr) {
3094 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3095 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3096 mMaxGraphicBufferProducerListSize,
3097 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3098 mGraphicBufferProducerList.size(),
3099 mMaxGraphicBufferProducerListSize, mNumLayers);
3100 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 mLayersAdded = true;
3102 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003103 }
3104
Mathias Agopian96f08192010-06-02 23:28:45 -07003105 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003106 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003107
Dan Stoza7d89d062015-04-30 13:29:25 -07003108 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003109}
3110
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003111status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003112 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003113 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3114}
Robert Carr7f9b8992017-03-10 11:08:39 -08003115
chaviwca27f252018-02-06 16:46:39 -08003116status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3117 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003118 if (layer->isPendingRemoval()) {
3119 return NO_ERROR;
3120 }
3121
Robert Carr1f0a16a2016-10-24 16:27:39 -07003122 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003123 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003124 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003125 if (topLevelOnly) {
3126 return NO_ERROR;
3127 }
3128
Chia-I Wu98f1c102017-05-30 14:54:08 -07003129 sp<Layer> ancestor = p;
3130 while (ancestor->getParent() != nullptr) {
3131 ancestor = ancestor->getParent();
3132 }
3133 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3134 ALOGE("removeLayer called with a layer whose parent has been removed");
3135 return NAME_NOT_FOUND;
3136 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003137
3138 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003139 } else {
3140 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003141 }
3142
Robert Carr136e2f62017-02-08 17:54:29 -08003143 // As a matter of normal operation, the LayerCleaner will produce a second
3144 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3145 // so we will succeed in promoting it, but it's already been removed
3146 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3147 // otherwise something has gone wrong and we are leaking the layer.
3148 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3150 layer->getName().string(),
3151 (p != nullptr) ? p->getName().string() : "no-parent");
3152 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003153 } else if (index < 0) {
3154 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003155 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003156
Chia-I Wuc6657022017-08-15 11:18:17 -07003157 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 mLayersPendingRemoval.add(layer);
3159 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003160 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003161 setTransactionFlags(eTransactionNeeded);
3162 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163}
3164
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003165uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003166 return android_atomic_release_load(&mTransactionFlags);
3167}
3168
Mathias Agopian3f844832013-08-07 21:24:32 -07003169uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3171}
3172
Mathias Agopian3f844832013-08-07 21:24:32 -07003173uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003174 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3175}
3176
3177uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3178 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003180 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003182 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 }
3184 return old;
3185}
3186
chaviwca27f252018-02-06 16:46:39 -08003187bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3188 for (const ComposerState& state : states) {
3189 // Here we need to check that the interface we're given is indeed
3190 // one of our own. A malicious client could give us a nullptr
3191 // IInterface, or one of its own or even one of our own but a
3192 // different type. All these situations would cause us to crash.
3193 if (state.client == nullptr) {
3194 return true;
3195 }
3196
3197 sp<IBinder> binder = IInterface::asBinder(state.client);
3198 if (binder == nullptr) {
3199 return true;
3200 }
3201
3202 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3203 return true;
3204 }
3205 }
3206 return false;
3207}
3208
Mathias Agopian8b33f032012-07-24 20:43:54 -07003209void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003210 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003211 const Vector<DisplayState>& displays,
3212 uint32_t flags)
3213{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003214 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003215 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003216 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217
chaviwca27f252018-02-06 16:46:39 -08003218 if (containsAnyInvalidClientState(states)) {
3219 return;
3220 }
3221
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003222 if (flags & eAnimation) {
3223 // For window updates that are part of an animation we must wait for
3224 // previous animation "frames" to be handled.
3225 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003226 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003227 if (CC_UNLIKELY(err != NO_ERROR)) {
3228 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003229 // caller after a few seconds.
3230 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3231 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003232 mAnimTransactionPending = false;
3233 break;
3234 }
3235 }
3236 }
3237
chaviwca27f252018-02-06 16:46:39 -08003238 for (const DisplayState& display : displays) {
3239 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003240 }
3241
chaviwca27f252018-02-06 16:46:39 -08003242 for (const ComposerState& state : states) {
3243 transactionFlags |= setClientStateLocked(state);
3244 }
3245
3246 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3247 // as destroyed should only occur after setting all other states. This is to allow for a
3248 // child re-parent to happen before marking its original parent as destroyed (which would
3249 // then mark the child as destroyed).
3250 for (const ComposerState& state : states) {
3251 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003252 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003253
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003254 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3255 // anyway. This can be used as a flush mechanism for previous async transactions.
3256 // Empty animation transaction can be used to simulate back-pressure, so also force a
3257 // transaction for empty animation transactions.
3258 if (transactionFlags == 0 &&
3259 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003260 transactionFlags = eTransactionNeeded;
3261 }
3262
Mathias Agopian386aa982011-11-07 21:58:03 -08003263 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003264 if (mInterceptor->isEnabled()) {
3265 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003266 }
Irvel468051e2016-06-13 16:44:44 -07003267
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003269 const auto start = (flags & eEarlyWakeup)
3270 ? VSyncModulator::TransactionStart::EARLY
3271 : VSyncModulator::TransactionStart::NORMAL;
3272 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003273
3274 // if this is a synchronous transaction, wait for it to take effect
3275 // before returning.
3276 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003277 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003278 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003279 if (flags & eAnimation) {
3280 mAnimTransactionPending = true;
3281 }
3282 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003283 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3284 if (CC_UNLIKELY(err != NO_ERROR)) {
3285 // just in case something goes wrong in SF, return to the
3286 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003287 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3288 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003289 break;
3290 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292 }
3293}
3294
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3296{
Jesse Hall9a143922012-10-04 16:29:19 -07003297 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3298 if (dpyIdx < 0)
3299 return 0;
3300
Mathias Agopiane57f2922012-08-09 16:29:12 -07003301 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003302 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003303 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304 const uint32_t what = s.what;
3305 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003306 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307 disp.surface = s.surface;
3308 flags |= eDisplayTransactionNeeded;
3309 }
3310 }
3311 if (what & DisplayState::eLayerStackChanged) {
3312 if (disp.layerStack != s.layerStack) {
3313 disp.layerStack = s.layerStack;
3314 flags |= eDisplayTransactionNeeded;
3315 }
3316 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003317 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003318 if (disp.orientation != s.orientation) {
3319 disp.orientation = s.orientation;
3320 flags |= eDisplayTransactionNeeded;
3321 }
3322 if (disp.frame != s.frame) {
3323 disp.frame = s.frame;
3324 flags |= eDisplayTransactionNeeded;
3325 }
3326 if (disp.viewport != s.viewport) {
3327 disp.viewport = s.viewport;
3328 flags |= eDisplayTransactionNeeded;
3329 }
3330 }
Michael Lentine47e45402014-07-18 15:34:25 -07003331 if (what & DisplayState::eDisplaySizeChanged) {
3332 if (disp.width != s.width) {
3333 disp.width = s.width;
3334 flags |= eDisplayTransactionNeeded;
3335 }
3336 if (disp.height != s.height) {
3337 disp.height = s.height;
3338 flags |= eDisplayTransactionNeeded;
3339 }
3340 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341 }
3342 return flags;
3343}
3344
chaviwca27f252018-02-06 16:46:39 -08003345uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3346 const layer_state_t& s = composerState.state;
3347 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3348
Mathias Agopian13127d82013-03-05 17:47:11 -08003349 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003350 if (layer == nullptr) {
3351 return 0;
3352 }
3353
3354 if (layer->isPendingRemoval()) {
3355 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3356 return 0;
3357 }
3358
3359 uint32_t flags = 0;
3360
3361 const uint32_t what = s.what;
3362 bool geometryAppliesWithResize =
3363 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003364
3365 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3366 // pending state will also be deferred.
3367 if (what & layer_state_t::eDeferTransaction) {
3368 layer->pushPendingState();
3369 }
3370
chaviw8b3871a2017-11-01 17:41:01 -07003371 if (what & layer_state_t::ePositionChanged) {
3372 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3373 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 }
chaviw8b3871a2017-11-01 17:41:01 -07003375 }
3376 if (what & layer_state_t::eLayerChanged) {
3377 // NOTE: index needs to be calculated before we update the state
3378 const auto& p = layer->getParent();
3379 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003380 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003381 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 mCurrentState.layersSortedByZ.removeAt(idx);
3383 mCurrentState.layersSortedByZ.add(layer);
3384 // we need traversal (state changed)
3385 // AND transaction (list changed)
3386 flags |= eTransactionNeeded|eTraversalNeeded;
3387 }
chaviw8b3871a2017-11-01 17:41:01 -07003388 } else {
3389 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003390 flags |= eTransactionNeeded|eTraversalNeeded;
3391 }
3392 }
chaviw8b3871a2017-11-01 17:41:01 -07003393 }
3394 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003395 // NOTE: index needs to be calculated before we update the state
3396 const auto& p = layer->getParent();
3397 if (p == nullptr) {
3398 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3399 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3400 mCurrentState.layersSortedByZ.removeAt(idx);
3401 mCurrentState.layersSortedByZ.add(layer);
3402 // we need traversal (state changed)
3403 // AND transaction (list changed)
3404 flags |= eTransactionNeeded|eTraversalNeeded;
3405 }
3406 } else {
3407 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3408 flags |= eTransactionNeeded|eTraversalNeeded;
3409 }
chaviw8b3871a2017-11-01 17:41:01 -07003410 }
3411 }
3412 if (what & layer_state_t::eSizeChanged) {
3413 if (layer->setSize(s.w, s.h)) {
3414 flags |= eTraversalNeeded;
3415 }
3416 }
3417 if (what & layer_state_t::eAlphaChanged) {
3418 if (layer->setAlpha(s.alpha))
3419 flags |= eTraversalNeeded;
3420 }
3421 if (what & layer_state_t::eColorChanged) {
3422 if (layer->setColor(s.color))
3423 flags |= eTraversalNeeded;
3424 }
3425 if (what & layer_state_t::eMatrixChanged) {
3426 if (layer->setMatrix(s.matrix))
3427 flags |= eTraversalNeeded;
3428 }
3429 if (what & layer_state_t::eTransparentRegionChanged) {
3430 if (layer->setTransparentRegionHint(s.transparentRegion))
3431 flags |= eTraversalNeeded;
3432 }
3433 if (what & layer_state_t::eFlagsChanged) {
3434 if (layer->setFlags(s.flags, s.mask))
3435 flags |= eTraversalNeeded;
3436 }
3437 if (what & layer_state_t::eCropChanged) {
3438 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3439 flags |= eTraversalNeeded;
3440 }
3441 if (what & layer_state_t::eFinalCropChanged) {
3442 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3443 flags |= eTraversalNeeded;
3444 }
3445 if (what & layer_state_t::eLayerStackChanged) {
3446 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3447 // We only allow setting layer stacks for top level layers,
3448 // everything else inherits layer stack from its parent.
3449 if (layer->hasParent()) {
3450 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3451 layer->getName().string());
3452 } else if (idx < 0) {
3453 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3454 "that also does not appear in the top level layer list. Something"
3455 " has gone wrong.", layer->getName().string());
3456 } else if (layer->setLayerStack(s.layerStack)) {
3457 mCurrentState.layersSortedByZ.removeAt(idx);
3458 mCurrentState.layersSortedByZ.add(layer);
3459 // we need traversal (state changed)
3460 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003461 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003462 }
3463 }
3464 if (what & layer_state_t::eDeferTransaction) {
3465 if (s.barrierHandle != nullptr) {
3466 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3467 } else if (s.barrierGbp != nullptr) {
3468 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3469 if (authenticateSurfaceTextureLocked(gbp)) {
3470 const auto& otherLayer =
3471 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3472 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3473 } else {
3474 ALOGE("Attempt to defer transaction to to an"
3475 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003476 }
3477 }
chaviw8b3871a2017-11-01 17:41:01 -07003478 // We don't trigger a traversal here because if no other state is
3479 // changed, we don't want this to cause any more work
3480 }
3481 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003482 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003483 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003484 if (!hadParent) {
3485 mCurrentState.layersSortedByZ.remove(layer);
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 }
3490 if (what & layer_state_t::eReparentChildren) {
3491 if (layer->reparentChildren(s.reparentHandle)) {
3492 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 }
chaviw8b3871a2017-11-01 17:41:01 -07003495 if (what & layer_state_t::eDetachChildren) {
3496 layer->detachChildren();
3497 }
3498 if (what & layer_state_t::eOverrideScalingModeChanged) {
3499 layer->setOverrideScalingMode(s.overrideScalingMode);
3500 // We don't trigger a traversal here because if no other state is
3501 // changed, we don't want this to cause any more work
3502 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003503 return flags;
3504}
3505
chaviwca27f252018-02-06 16:46:39 -08003506void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3507 const layer_state_t& state = composerState.state;
3508 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3509
3510 sp<Layer> layer(client->getLayerUser(state.surface));
3511 if (layer == nullptr) {
3512 return;
3513 }
3514
3515 if (layer->isPendingRemoval()) {
3516 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3517 return;
3518 }
3519
3520 if (state.what & layer_state_t::eDestroySurface) {
3521 removeLayerLocked(mStateLock, layer);
3522 }
3523}
3524
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003525status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003526 const String8& name,
3527 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003528 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003529 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003530 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003532 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003533 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003534 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003535 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003536 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003537
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003538 status_t result = NO_ERROR;
3539
3540 sp<Layer> layer;
3541
Cody Northropbc755282017-03-31 12:00:08 -06003542 String8 uniqueName = getUniqueLayerName(name);
3543
Mathias Agopian3165cc22012-08-08 19:42:09 -07003544 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3545 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003546 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003547 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003549
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550 break;
chaviw13fdc492017-06-27 12:40:18 -07003551 case ISurfaceComposerClient::eFXSurfaceColor:
3552 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003553 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003554 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003555 break;
3556 default:
3557 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003558 break;
3559 }
3560
Dan Stoza7d89d062015-04-30 13:29:25 -07003561 if (result != NO_ERROR) {
3562 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003564
Chia-I Wuab0c3192017-08-01 11:29:00 -07003565 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3566 // TODO b/64227542
3567 if (windowType == 441731) {
3568 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3569 layer->setPrimaryDisplayOnly();
3570 }
3571
Albert Chaulk479c60c2017-01-27 14:21:34 -05003572 layer->setInfo(windowType, ownerUid);
3573
Robert Carr1f0a16a2016-10-24 16:27:39 -07003574 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003575 if (result != NO_ERROR) {
3576 return result;
3577 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003578 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003579
3580 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582}
3583
Cody Northropbc755282017-03-31 12:00:08 -06003584String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3585{
3586 bool matchFound = true;
3587 uint32_t dupeCounter = 0;
3588
3589 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3590 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3591
3592 // Loop over layers until we're sure there is no matching name
3593 while (matchFound) {
3594 matchFound = false;
3595 mDrawingState.traverseInZOrder([&](Layer* layer) {
3596 if (layer->getName() == uniqueName) {
3597 matchFound = true;
3598 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3599 }
3600 });
3601 }
3602
3603 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3604
3605 return uniqueName;
3606}
3607
David Sodman0c69cad2017-08-21 12:12:51 -07003608status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3610 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611{
3612 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003613 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 case PIXEL_FORMAT_TRANSPARENT:
3615 case PIXEL_FORMAT_TRANSLUCENT:
3616 format = PIXEL_FORMAT_RGBA_8888;
3617 break;
3618 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003619 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003620 break;
3621 }
3622
David Sodman0c69cad2017-08-21 12:12:51 -07003623 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3624 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003626 *handle = layer->getHandle();
3627 *gbp = layer->getProducer();
3628 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630
David Sodman0c69cad2017-08-21 12:12:51 -07003631 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633}
3634
chaviw13fdc492017-06-27 12:40:18 -07003635status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003637 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638{
chaviw13fdc492017-06-27 12:40:18 -07003639 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003642}
3643
Mathias Agopianac9fa422013-02-11 16:40:36 -08003644status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645{
Robert Carr9524cb32017-02-13 11:32:32 -08003646 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003647 status_t err = NO_ERROR;
3648 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003649 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003650 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003651 err = removeLayer(l);
3652 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3653 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003654 }
3655 return err;
3656}
3657
Mathias Agopian13127d82013-03-05 17:47:11 -08003658status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003659{
Mathias Agopian67106042013-03-14 19:18:13 -07003660 // called by ~LayerCleaner() when all references to the IBinder (handle)
3661 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003662 sp<Layer> l = layer.promote();
3663 if (l == nullptr) {
3664 // The layer has already been removed, carry on
3665 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003666 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003667 // If we have a parent, then we can continue to live as long as it does.
3668 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669}
3670
Mathias Agopianb60314a2012-04-10 22:09:54 -07003671// ---------------------------------------------------------------------------
3672
Andy McFadden13a082e2012-08-24 10:16:42 -07003673void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003674 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003675 Vector<ComposerState> state;
3676 Vector<DisplayState> displays;
3677 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003678 d.what = DisplayState::eDisplayProjectionChanged |
3679 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003680 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003681 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003682 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003683 d.frame.makeInvalid();
3684 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003685 d.width = 0;
3686 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003687 displays.add(d);
3688 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003689 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3690 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003691
David Sodman105b7dc2017-11-04 20:28:14 -07003692 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003693 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003694 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003695
Brian Andersond0010582017-03-07 13:20:31 -08003696 // Use phase of 0 since phase is not known.
3697 // Use latency of 0, which will snap to the ideal latency.
3698 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003699}
3700
3701void SurfaceFlinger::initializeDisplays() {
3702 class MessageScreenInitialized : public MessageBase {
3703 SurfaceFlinger* flinger;
3704 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003705 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003706 virtual bool handler() {
3707 flinger->onInitializeDisplays();
3708 return true;
3709 }
3710 };
3711 sp<MessageBase> msg = new MessageScreenInitialized(this);
3712 postMessageAsync(msg); // we may be called from main thread, use async message
3713}
3714
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003715void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003716 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3718 this);
3719 int32_t type = hw->getDisplayType();
3720 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003721
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003723 return;
3724 }
3725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 hw->setPowerMode(mode);
3727 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3728 ALOGW("Trying to set power mode for virtual display");
3729 return;
3730 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731
Lloyd Pique4d234852018-01-22 17:21:36 -08003732 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003733 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003734 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3735 if (idx < 0) {
3736 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3737 return;
3738 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003739 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003740 }
3741
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003743 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003744 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003745 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3746 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003747 // FIXME: eventthread only knows about the main display right now
3748 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003749 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003751
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003752 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003753 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003754 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003755
3756 struct sched_param param = {0};
3757 param.sched_priority = 1;
3758 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3759 ALOGW("Couldn't set SCHED_FIFO on display on");
3760 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003762 // Turn off the display
3763 struct sched_param param = {0};
3764 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3765 ALOGW("Couldn't set SCHED_OTHER on display off");
3766 }
3767
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003768 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3769 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003770 disableHardwareVsync(true); // also cancels any in-progress resync
3771
Mathias Agopiancde87a32012-09-13 14:09:01 -07003772 // FIXME: eventthread only knows about the main display right now
3773 mEventThread->onScreenReleased();
3774 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 getHwComposer().setPowerMode(type, mode);
3777 mVisibleRegionsDirty = true;
3778 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003779 } else if (mode == HWC_POWER_MODE_DOZE ||
3780 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003781 // Update display while dozing
3782 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003783 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3784 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 // FIXME: eventthread only knows about the main display right now
3786 mEventThread->onScreenAcquired();
3787 resyncToHardwareVsync(true);
3788 }
3789 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3790 // Leave display going to doze
3791 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3792 disableHardwareVsync(true); // also cancels any in-progress resync
3793 // FIXME: eventthread only knows about the main display right now
3794 mEventThread->onScreenReleased();
3795 }
3796 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003798 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003801 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003802}
3803
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3805 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003806 SurfaceFlinger& mFlinger;
3807 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003810 MessageSetPowerMode(SurfaceFlinger& flinger,
3811 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3812 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003813 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003814 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003815 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003816 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003817 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003818 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003819 ALOGW("Attempt to set power mode = %d for virtual display",
3820 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003821 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003822 mFlinger.setPowerModeInternal(
3823 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003824 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003825 return true;
3826 }
3827 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003828 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003829 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003830}
3831
3832// ---------------------------------------------------------------------------
3833
Lloyd Pique755e3192018-01-31 16:46:15 -08003834status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3835 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003837
Mathias Agopianbd115332013-04-18 16:41:04 -07003838 IPCThreadState* ipc = IPCThreadState::self();
3839 const int pid = ipc->getCallingPid();
3840 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003841
Mathias Agopianbd115332013-04-18 16:41:04 -07003842 if ((uid != AID_SHELL) &&
3843 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003845 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003846 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003847 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003848 // (this would indicate SF is stuck, but we want to be able to
3849 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003850 status_t err = mStateLock.timedLock(s2ns(1));
3851 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003852 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003853 result.appendFormat(
3854 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3855 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003856 }
3857
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003858 bool dumpAll = true;
3859 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003860 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003861
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003862 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863 if ((index < numArgs) &&
3864 (args[index] == String16("--list"))) {
3865 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003866 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003867 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003868 }
3869
3870 if ((index < numArgs) &&
3871 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003872 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003873 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003874 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003875 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003876
3877 if ((index < numArgs) &&
3878 (args[index] == String16("--latency-clear"))) {
3879 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003880 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003881 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003882 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003883
3884 if ((index < numArgs) &&
3885 (args[index] == String16("--dispsync"))) {
3886 index++;
3887 mPrimaryDispSync.dump(result);
3888 dumpAll = false;
3889 }
Dan Stozab90cf072015-03-05 11:05:59 -08003890
3891 if ((index < numArgs) &&
3892 (args[index] == String16("--static-screen"))) {
3893 index++;
3894 dumpStaticScreenStats(result);
3895 dumpAll = false;
3896 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003897
3898 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003899 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003900 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003901 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003902 dumpAll = false;
3903 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003904
3905 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3906 index++;
3907 dumpWideColorInfo(result);
3908 dumpAll = false;
3909 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003910
3911 if ((index < numArgs) &&
3912 (args[index] == String16("--enable-layer-stats"))) {
3913 index++;
3914 mLayerStats.enable();
3915 dumpAll = false;
3916 }
3917
3918 if ((index < numArgs) &&
3919 (args[index] == String16("--disable-layer-stats"))) {
3920 index++;
3921 mLayerStats.disable();
3922 dumpAll = false;
3923 }
3924
3925 if ((index < numArgs) &&
3926 (args[index] == String16("--clear-layer-stats"))) {
3927 index++;
3928 mLayerStats.clear();
3929 dumpAll = false;
3930 }
3931
3932 if ((index < numArgs) &&
3933 (args[index] == String16("--dump-layer-stats"))) {
3934 index++;
3935 mLayerStats.dump(result);
3936 dumpAll = false;
3937 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003938
3939 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3940 index++;
3941 mTimeStats.parseArgs(asProto, args, index, result);
3942 dumpAll = false;
3943 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003945
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003947 if (asProto) {
3948 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3949 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3950 } else {
3951 dumpAllLocked(args, index, result);
3952 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003953 }
3954
Mathias Agopian9795c422009-08-26 16:36:26 -07003955 if (locked) {
3956 mStateLock.unlock();
3957 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 }
3959 write(fd, result.string(), result.size());
3960 return NO_ERROR;
3961}
3962
Dan Stozac7014012014-02-14 15:03:43 -08003963void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3964 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965{
Robert Carr2047fae2016-11-28 14:09:09 -08003966 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003967 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003968 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003969}
3970
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003971void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003972 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973{
3974 String8 name;
3975 if (index < args.size()) {
3976 name = String8(args[index]);
3977 index++;
3978 }
3979
David Sodman105b7dc2017-11-04 20:28:14 -07003980 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003981 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003982 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003983
3984 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003985 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003986 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003987 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003988 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003989 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003990 }
Robert Carr2047fae2016-11-28 14:09:09 -08003991 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992 }
3993}
3994
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003996 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997{
3998 String8 name;
3999 if (index < args.size()) {
4000 name = String8(args[index]);
4001 index++;
4002 }
4003
Robert Carr2047fae2016-11-28 14:09:09 -08004004 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004006 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007 }
Robert Carr2047fae2016-11-28 14:09:09 -08004008 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004009
Svetoslavd85084b2014-03-20 10:28:31 -07004010 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011}
4012
Jamie Gennis6547ff42013-07-16 20:12:42 -07004013// This should only be called from the main thread. Otherwise it would need
4014// the lock and should use mCurrentState rather than mDrawingState.
4015void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004016 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004017 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004018 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004019
4020 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4021}
4022
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004023void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004024{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004025 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004026
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004027 if (isLayerTripleBufferingDisabled())
4028 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004029
4030 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004031 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004032 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004033 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004034 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4035 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004036 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004037}
4038
Dan Stozab90cf072015-03-05 11:05:59 -08004039void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4040{
4041 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004042 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4043 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004045 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004046 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4047 b + 1, bucketTimeSec, percent);
4048 }
David Sodman4a36e932017-11-07 14:29:47 -08004049 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004050 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004051 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004052 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004053 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004054}
4055
Dan Stozae77c7662016-05-13 11:37:28 -07004056void SurfaceFlinger::recordBufferingStats(const char* layerName,
4057 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004058 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4059 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004060 for (const auto& segment : history) {
4061 if (!segment.usedThirdBuffer) {
4062 stats.twoBufferTime += segment.totalTime;
4063 }
4064 if (segment.occupancyAverage < 1.0f) {
4065 stats.doubleBufferedTime += segment.totalTime;
4066 } else if (segment.occupancyAverage < 2.0f) {
4067 stats.tripleBufferedTime += segment.totalTime;
4068 }
4069 ++stats.numSegments;
4070 stats.totalTime += segment.totalTime;
4071 }
4072}
4073
Brian Andersond6927fb2016-07-23 23:37:30 -07004074void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4075 result.appendFormat("Layer frame timestamps:\n");
4076
4077 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4078 const size_t count = currentLayers.size();
4079 for (size_t i=0 ; i<count ; i++) {
4080 currentLayers[i]->dumpFrameEvents(result);
4081 }
4082}
4083
Dan Stozae77c7662016-05-13 11:37:28 -07004084void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4085 result.append("Buffering stats:\n");
4086 result.append(" [Layer name] <Active time> <Two buffer> "
4087 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004088 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004089 typedef std::tuple<std::string, float, float, float> BufferTuple;
4090 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004091 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004092 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004093 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004094 if (stats.numSegments == 0) {
4095 continue;
4096 }
4097 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4098 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4099 stats.totalTime;
4100 float doubleBufferRatio = static_cast<float>(
4101 stats.doubleBufferedTime) / stats.totalTime;
4102 float tripleBufferRatio = static_cast<float>(
4103 stats.tripleBufferedTime) / stats.totalTime;
4104 sorted.insert({activeTime, {name, twoBufferRatio,
4105 doubleBufferRatio, tripleBufferRatio}});
4106 }
4107 for (const auto& sortedPair : sorted) {
4108 float activeTime = sortedPair.first;
4109 const BufferTuple& values = sortedPair.second;
4110 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4111 std::get<0>(values).c_str(), activeTime,
4112 std::get<1>(values), std::get<2>(values),
4113 std::get<3>(values));
4114 }
4115 result.append("\n");
4116}
4117
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004118void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4119 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004120 result.appendFormat("DisplayColorSetting: %s\n",
4121 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004122
4123 // TODO: print out if wide-color mode is active or not
4124
4125 for (size_t d = 0; d < mDisplays.size(); d++) {
4126 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4127 int32_t hwcId = displayDevice->getHwcDisplayId();
4128 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4129 continue;
4130 }
4131
4132 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004133 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004134 for (auto&& mode : modes) {
4135 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4136 }
4137
Peiyong Lina52f0292018-03-14 17:26:31 -07004138 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004139 result.appendFormat(" Current color mode: %s (%d)\n",
4140 decodeColorMode(currentMode).c_str(), currentMode);
4141 }
4142 result.append("\n");
4143}
4144
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004145LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004146 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004147 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4148 const State& state = useDrawing ? mDrawingState : mCurrentState;
4149 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004150 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004151 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004152 });
4153
4154 return layersProto;
4155}
4156
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004157LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4158 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004159 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004160
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004161 SizeProto* resolution = layersProto.mutable_resolution();
4162 resolution->set_w(displayDevice->getWidth());
4163 resolution->set_h(displayDevice->getHeight());
4164
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004165 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4166 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4167 layersProto.set_global_transform(
4168 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4169
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004170 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004171 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004172 LayerProto* layerProto = layersProto.add_layers();
4173 layer->writeToProto(layerProto, hwcId);
4174 }
4175 });
4176
4177 return layersProto;
4178}
4179
Mathias Agopian74d211a2013-04-22 16:55:35 +02004180void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4181 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004182{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004183 bool colorize = false;
4184 if (index < args.size()
4185 && (args[index] == String16("--color"))) {
4186 colorize = true;
4187 index++;
4188 }
4189
4190 Colorizer colorizer(colorize);
4191
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192 // figure out if we're stuck somewhere
4193 const nsecs_t now = systemTime();
4194 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4195 const nsecs_t inTransaction(mDebugInTransaction);
4196 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4197 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4198
4199 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004200 * Dump library configuration.
4201 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202
4203 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004204 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004205 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004206 appendSfConfigString(result);
4207 appendUiConfigString(result);
4208 appendGuiConfigString(result);
4209 result.append("\n");
4210
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004211 result.append("\nWide-Color information:\n");
4212 dumpWideColorInfo(result);
4213
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004215 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004216 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004217 result.append(SyncFeatures::getInstance().toString());
4218 result.append("\n");
4219
David Sodman105b7dc2017-11-04 20:28:14 -07004220 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004221
Andy McFadden41d67d72014-04-25 16:58:34 -07004222 colorizer.bold(result);
4223 result.append("DispSync configuration: ");
4224 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004225 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4226 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4227 result.appendFormat(
4228 "app phase %" PRId64 " ns, "
4229 "sf phase %" PRId64 " ns, "
4230 "early app phase %" PRId64 " ns, "
4231 "early sf phase %" PRId64 " ns, "
4232 "early app gl phase %" PRId64 " ns, "
4233 "early sf gl phase %" PRId64 " ns, "
4234 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4235 vsyncPhaseOffsetNs,
4236 sfVsyncPhaseOffsetNs,
4237 appEarlyOffset,
4238 sfEarlyOffset,
4239 appEarlyGlOffset,
4240 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004241 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004242 result.append("\n");
4243
Dan Stozab90cf072015-03-05 11:05:59 -08004244 // Dump static screen stats
4245 result.append("\n");
4246 dumpStaticScreenStats(result);
4247 result.append("\n");
4248
Dan Stozae77c7662016-05-13 11:37:28 -07004249 dumpBufferingStats(result);
4250
Andy McFadden4803b742012-09-24 19:07:20 -07004251 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252 * Dump the visible layer list
4253 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004254 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004255 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004256 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4257 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004258 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004259
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004260 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004261 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004262 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004263 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264
4265 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004266 * Dump Display state
4267 */
4268
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004270 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004271 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004272 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4273 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004275 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004276 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004277
4278 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279 * Dump SurfaceFlinger global state
4280 */
4281
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004282 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004285
Mathias Agopian888c8222012-08-04 21:10:38 -07004286 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004287 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004288
David Sodmanbc815282017-11-05 18:57:52 -08004289 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004291 if (hw) {
4292 hw->undefinedRegion.dump(result, "undefinedRegion");
4293 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4294 hw->getOrientation(), hw->isDisplayOn());
4295 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004296 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 " last eglSwapBuffers() time: %f us\n"
4298 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004299 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300 " refresh-rate : %f fps\n"
4301 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004302 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004303 " gpu_to_cpu_unsupported : %d\n"
4304 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305 mLastSwapBufferTime/1000.0,
4306 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004307 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004308 1e9 / activeConfig->getVsyncPeriod(),
4309 activeConfig->getDpiX(),
4310 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004311 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312
Mathias Agopian74d211a2013-04-22 16:55:35 +02004313 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315
Mathias Agopian74d211a2013-04-22 16:55:35 +02004316 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318
4319 /*
4320 * VSYNC state
4321 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004322 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004323 result.append("\n");
4324
4325 /*
4326 * HWC layer minidump
4327 */
4328 for (size_t d = 0; d < mDisplays.size(); d++) {
4329 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4330 int32_t hwcId = displayDevice->getHwcDisplayId();
4331 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4332 continue;
4333 }
4334
4335 result.appendFormat("Display %d HWC layers:\n", hwcId);
4336 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004337 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004338 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004339 });
Dan Stozae22aec72016-08-01 13:20:59 -07004340 result.append("\n");
4341 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342
4343 /*
4344 * Dump HWComposer state
4345 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004346 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004347 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004348 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004349 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004350 result.appendFormat(" h/w composer %s\n",
4351 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004352 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353
4354 /*
4355 * Dump gralloc state
4356 */
4357 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4358 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004359
4360 /*
4361 * Dump VrFlinger state if in use.
4362 */
4363 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4364 result.append("VrFlinger state:\n");
4365 result.append(mVrFlinger->Dump().c_str());
4366 result.append("\n");
4367 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368}
4369
Mathias Agopian13127d82013-03-05 17:47:11 -08004370const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004371SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004372 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004373 wp<IBinder> dpy;
4374 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4375 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4376 dpy = mDisplays.keyAt(i);
4377 break;
4378 }
4379 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004380 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004381 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4382 // Just use the primary display so we have something to return
4383 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4384 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004385 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004386}
4387
Keun young Park63f165f2012-08-31 10:53:36 -07004388bool SurfaceFlinger::startDdmConnection()
4389{
4390 void* libddmconnection_dso =
4391 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4392 if (!libddmconnection_dso) {
4393 return false;
4394 }
4395 void (*DdmConnection_start)(const char* name);
4396 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004397 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004398 if (!DdmConnection_start) {
4399 dlclose(libddmconnection_dso);
4400 return false;
4401 }
4402 (*DdmConnection_start)(getServiceName());
4403 return true;
4404}
4405
Chia-I Wu28f320b2018-05-03 11:02:56 -07004406void SurfaceFlinger::updateColorMatrixLocked() {
4407 mat4 colorMatrix;
4408 if (mGlobalSaturationFactor != 1.0f) {
4409 // Rec.709 luma coefficients
4410 float3 luminance{0.213f, 0.715f, 0.072f};
4411 luminance *= 1.0f - mGlobalSaturationFactor;
4412 mat4 saturationMatrix = mat4(
4413 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4414 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4415 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4416 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4417 );
4418 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4419 } else {
4420 colorMatrix = mClientColorMatrix * mDaltonizer();
4421 }
4422
4423 if (mCurrentState.colorMatrix != colorMatrix) {
4424 mCurrentState.colorMatrix = colorMatrix;
4425 mCurrentState.colorMatrixChanged = true;
4426 setTransactionFlags(eTransactionNeeded);
4427 }
4428}
4429
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004430status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004431 switch (code) {
4432 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004433 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004435 case CLEAR_ANIMATION_FRAME_STATS:
4436 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004437 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004438 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004439 case ENABLE_VSYNC_INJECTIONS:
4440 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 {
4442 // codes that require permission check
4443 IPCThreadState* ipc = IPCThreadState::self();
4444 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004445 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004446 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004447 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004448 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004449 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004450 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004451 break;
4452 }
Robert Carr1db73f62016-12-21 12:58:51 -08004453 /*
4454 * Calling setTransactionState is safe, because you need to have been
4455 * granted a reference to Client* and Handle* to do anything with it.
4456 *
4457 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4458 */
4459 case SET_TRANSACTION_STATE:
4460 case CREATE_SCOPED_CONNECTION:
4461 {
4462 return OK;
4463 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004464 case CAPTURE_SCREEN:
4465 {
4466 // codes that require permission check
4467 IPCThreadState* ipc = IPCThreadState::self();
4468 const int pid = ipc->getCallingPid();
4469 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004470 if ((uid != AID_GRAPHICS) &&
4471 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004472 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004473 return PERMISSION_DENIED;
4474 }
4475 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 }
chaviwa76b2712017-09-20 12:02:26 -07004477 case CAPTURE_LAYERS: {
4478 IPCThreadState* ipc = IPCThreadState::self();
4479 const int pid = ipc->getCallingPid();
4480 const int uid = ipc->getCallingUid();
4481 if ((uid != AID_GRAPHICS) &&
4482 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4483 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4484 return PERMISSION_DENIED;
4485 }
4486 break;
4487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004489 return OK;
4490}
4491
4492status_t SurfaceFlinger::onTransact(
4493 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4494{
4495 status_t credentialCheck = CheckTransactCodeCredentials(code);
4496 if (credentialCheck != OK) {
4497 return credentialCheck;
4498 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004499
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004500 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4501 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004502 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004503 IPCThreadState* ipc = IPCThreadState::self();
4504 const int uid = ipc->getCallingUid();
4505 if (CC_UNLIKELY(uid != AID_SYSTEM
4506 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004507 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004508 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004509 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 return PERMISSION_DENIED;
4511 }
4512 int n;
4513 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004514 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004515 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 return NO_ERROR;
4517 case 1002: // SHOW_UPDATES
4518 n = data.readInt32();
4519 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004520 invalidateHwcGeometry();
4521 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004524 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004525 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004527 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004528 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004529 setTransactionFlags(
4530 eTransactionNeeded|
4531 eDisplayTransactionNeeded|
4532 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004533 return NO_ERROR;
4534 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004535 case 1006:{ // send empty update
4536 signalRefresh();
4537 return NO_ERROR;
4538 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004539 case 1008: // toggle use of hw composer
4540 n = data.readInt32();
4541 mDebugDisableHWC = n ? 1 : 0;
4542 invalidateHwcGeometry();
4543 repaintEverything();
4544 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004545 case 1009: // toggle use of transform hint
4546 n = data.readInt32();
4547 mDebugDisableTransformHint = n ? 1 : 0;
4548 invalidateHwcGeometry();
4549 repaintEverything();
4550 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004552 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 reply->writeInt32(0);
4554 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004555 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004556 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 return NO_ERROR;
4558 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004559 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004560 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004561 return NO_ERROR;
4562 }
4563 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004564 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004565 // daltonize
4566 n = data.readInt32();
4567 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004568 case 1:
4569 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4570 break;
4571 case 2:
4572 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4573 break;
4574 case 3:
4575 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4576 break;
4577 default:
4578 mDaltonizer.setType(ColorBlindnessType::None);
4579 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004580 }
4581 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004582 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004583 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004584 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004585 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004586
4587 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004588 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004590 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004591 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004592 // apply a color matrix
4593 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004594 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004595 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004596 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004597 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004598 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004599 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004601 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004602 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004603 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004604
4605 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4606 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004607 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004608 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4609 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4610 }
4611
Chia-I Wu28f320b2018-05-03 11:02:56 -07004612 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004613 return NO_ERROR;
4614 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004615 // This is an experimental interface
4616 // Needs to be shifted to proper binder interface when we productize
4617 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004618 n = data.readInt32();
4619 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004620 return NO_ERROR;
4621 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004622 case 1017: {
4623 n = data.readInt32();
4624 mForceFullDamage = static_cast<bool>(n);
4625 return NO_ERROR;
4626 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004627 case 1018: { // Modify Choreographer's phase offset
4628 n = data.readInt32();
4629 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4630 return NO_ERROR;
4631 }
4632 case 1019: { // Modify SurfaceFlinger's phase offset
4633 n = data.readInt32();
4634 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4635 return NO_ERROR;
4636 }
Irvel468051e2016-06-13 16:44:44 -07004637 case 1020: { // Layer updates interceptor
4638 n = data.readInt32();
4639 if (n) {
4640 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004641 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004642 }
4643 else{
4644 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004645 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004646 }
4647 return NO_ERROR;
4648 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004649 case 1021: { // Disable HWC virtual displays
4650 n = data.readInt32();
4651 mUseHwcVirtualDisplays = !n;
4652 return NO_ERROR;
4653 }
Romain Guy0147a172017-06-01 13:53:56 -07004654 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004655 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004656 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004657
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004659 return NO_ERROR;
4660 }
Romain Guy54f154a2017-10-24 21:40:32 +01004661 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004662 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004663 invalidateHwcGeometry();
4664 repaintEverything();
4665 return NO_ERROR;
4666 }
4667 case 1024: { // Is wide color gamut rendering/color management supported?
4668 reply->writeBool(hasWideColorDisplay);
4669 return NO_ERROR;
4670 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004671 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004672 n = data.readInt32();
4673 if (n) {
4674 ALOGV("LayerTracing enabled");
4675 mTracing.enable();
4676 doTracing("tracing.enable");
4677 reply->writeInt32(NO_ERROR);
4678 } else {
4679 ALOGV("LayerTracing disabled");
4680 status_t err = mTracing.disable();
4681 reply->writeInt32(err);
4682 }
4683 return NO_ERROR;
4684 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004685 case 1026: { // Get layer tracing status
4686 reply->writeBool(mTracing.isEnabled());
4687 return NO_ERROR;
4688 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004689 // Is a DisplayColorSetting supported?
4690 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004691 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4692 if (!hw) {
4693 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004694 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004695
4696 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4697 switch (setting) {
4698 case DisplayColorSetting::MANAGED:
4699 reply->writeBool(hasWideColorDisplay);
4700 break;
4701 case DisplayColorSetting::UNMANAGED:
4702 reply->writeBool(true);
4703 break;
4704 case DisplayColorSetting::ENHANCED:
4705 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4706 break;
4707 default: // vendor display color setting
4708 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4709 break;
4710 }
4711 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004713 }
4714 }
4715 return err;
4716}
4717
Steven Thomas6d8110b2017-08-31 18:24:21 -07004718void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004719 android_atomic_or(1, &mRepaintEverything);
4720 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004721}
4722
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004723// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4724class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004725public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004726 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4727 ~WindowDisconnector() {
4728 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004729 }
4730
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004731private:
4732 ANativeWindow* mWindow;
4733 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004734};
4735
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004736status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4737 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4738 int32_t minLayerZ, int32_t maxLayerZ,
4739 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004740 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004741 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004742
chaviwa76b2712017-09-20 12:02:26 -07004743 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4744
4745 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004746 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4747
chaviwa76b2712017-09-20 12:02:26 -07004748 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4749
4750 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4751 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004752 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004753}
4754
4755status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004756 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004757 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004758 ATRACE_CALL();
4759
4760 class LayerRenderArea : public RenderArea {
4761 public:
Robert Carr578038f2018-03-09 12:25:24 -08004762 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4763 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004764 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004765 mLayer(layer),
4766 mCrop(crop),
4767 mFlinger(flinger),
4768 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004769 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004770 Rect getBounds() const override {
4771 const Layer::State& layerState(mLayer->getDrawingState());
4772 return Rect(layerState.active.w, layerState.active.h);
4773 }
4774 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4775 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4776 bool isSecure() const override { return false; }
4777 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004778 Rect getSourceCrop() const override {
4779 if (mCrop.isEmpty()) {
4780 return getBounds();
4781 } else {
4782 return mCrop;
4783 }
4784 }
Robert Carr578038f2018-03-09 12:25:24 -08004785 class ReparentForDrawing {
4786 public:
4787 const sp<Layer>& oldParent;
4788 const sp<Layer>& newParent;
4789
4790 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4791 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004792 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004793 }
Robert Carr15eae092018-03-23 13:43:53 -07004794 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004795 };
4796
4797 void render(std::function<void()> drawLayers) override {
4798 if (!mChildrenOnly) {
4799 mTransform = mLayer->getTransform().inverse();
4800 drawLayers();
4801 } else {
4802 Rect bounds = getBounds();
4803 screenshotParentLayer =
4804 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4805 bounds.getWidth(), bounds.getHeight(), 0);
4806
4807 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4808 drawLayers();
4809 }
4810 }
chaviwa76b2712017-09-20 12:02:26 -07004811
chaviwa76b2712017-09-20 12:02:26 -07004812 private:
chaviw7206d492017-11-10 16:16:12 -08004813 const sp<Layer> mLayer;
4814 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004815
4816 // In the "childrenOnly" case we reparent the children to a screenshot
4817 // layer which has no properties set and which does not draw.
4818 sp<ContainerLayer> screenshotParentLayer;
4819 Transform mTransform;
4820
4821 SurfaceFlinger* mFlinger;
4822 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004823 };
4824
4825 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4826 auto parent = layerHandle->owner.promote();
4827
chaviw7206d492017-11-10 16:16:12 -08004828 if (parent == nullptr || parent->isPendingRemoval()) {
4829 ALOGE("captureLayers called with a removed parent");
4830 return NAME_NOT_FOUND;
4831 }
4832
Robert Carr578038f2018-03-09 12:25:24 -08004833 const int uid = IPCThreadState::self()->getCallingUid();
4834 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4835 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4836 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4837 return PERMISSION_DENIED;
4838 }
4839
chaviw7206d492017-11-10 16:16:12 -08004840 Rect crop(sourceCrop);
4841 if (sourceCrop.width() <= 0) {
4842 crop.left = 0;
4843 crop.right = parent->getCurrentState().active.w;
4844 }
4845
4846 if (sourceCrop.height() <= 0) {
4847 crop.top = 0;
4848 crop.bottom = parent->getCurrentState().active.h;
4849 }
4850
4851 int32_t reqWidth = crop.width() * frameScale;
4852 int32_t reqHeight = crop.height() * frameScale;
4853
Robert Carr578038f2018-03-09 12:25:24 -08004854 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004855
Robert Carr578038f2018-03-09 12:25:24 -08004856 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004857 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4858 if (!layer->isVisible()) {
4859 return;
Robert Carr578038f2018-03-09 12:25:24 -08004860 } else if (childrenOnly && layer == parent.get()) {
4861 return;
chaviwa76b2712017-09-20 12:02:26 -07004862 }
4863 visitor(layer);
4864 });
4865 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004866 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004867}
4868
4869status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4870 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004871 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004872 bool useIdentityTransform) {
4873 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004874
Iris Chang7501ed62018-04-30 14:45:42 +08004875 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004876
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004877 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4878 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4879 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4880 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881
4882 // This mutex protects syncFd and captureResult for communication of the return values from the
4883 // main thread back to this Binder thread
4884 std::mutex captureMutex;
4885 std::condition_variable captureCondition;
4886 std::unique_lock<std::mutex> captureLock(captureMutex);
4887 int syncFd = -1;
4888 std::optional<status_t> captureResult;
4889
Robert Carr03480e22018-01-04 16:02:06 -08004890 const int uid = IPCThreadState::self()->getCallingUid();
4891 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4892
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004893 sp<LambdaMessage> message = new LambdaMessage([&]() {
4894 // If there is a refresh pending, bug out early and tell the binder thread to try again
4895 // after the refresh.
4896 if (mRefreshPending) {
4897 ATRACE_NAME("Skipping screenshot for now");
4898 std::unique_lock<std::mutex> captureLock(captureMutex);
4899 captureResult = std::make_optional<status_t>(EAGAIN);
4900 captureCondition.notify_one();
4901 return;
4902 }
4903
4904 status_t result = NO_ERROR;
4905 int fd = -1;
4906 {
4907 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004908 renderArea.render([&]() {
4909 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4910 useIdentityTransform, forSystem, &fd);
4911 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004912 }
4913
4914 {
4915 std::unique_lock<std::mutex> captureLock(captureMutex);
4916 syncFd = fd;
4917 captureResult = std::make_optional<status_t>(result);
4918 captureCondition.notify_one();
4919 }
4920 });
4921
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004922 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004923 if (result == NO_ERROR) {
4924 captureCondition.wait(captureLock, [&]() { return captureResult; });
4925 while (*captureResult == EAGAIN) {
4926 captureResult.reset();
4927 result = postMessageAsync(message);
4928 if (result != NO_ERROR) {
4929 return result;
4930 }
4931 captureCondition.wait(captureLock, [&]() { return captureResult; });
4932 }
4933 result = *captureResult;
4934 }
4935
4936 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004937 sync_wait(syncFd, -1);
4938 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004939 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004940
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004941 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004942}
4943
chaviwa76b2712017-09-20 12:02:26 -07004944void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4945 TraverseLayersFunction traverseLayers, bool yswap,
4946 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004947 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004948
Lloyd Pique144e1162017-12-20 16:44:52 -08004949 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004950
4951 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004952 const auto raWidth = renderArea.getWidth();
4953 const auto raHeight = renderArea.getHeight();
4954
4955 const auto reqWidth = renderArea.getReqWidth();
4956 const auto reqHeight = renderArea.getReqHeight();
4957 Rect sourceCrop = renderArea.getSourceCrop();
4958
Iris Chang7501ed62018-04-30 14:45:42 +08004959 bool filtering = false;
4960 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4961 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4962 static_cast<int32_t>(reqHeight) != raWidth;
4963 } else {
4964 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4965 static_cast<int32_t>(reqHeight) != raHeight;
4966 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004967
Dan Stozac1879002014-05-22 15:59:05 -07004968 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004969 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004970 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004971 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004972 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4973 Transform tr;
4974 uint32_t flags = 0x00;
4975 switch (mPrimaryDisplayOrientation) {
4976 case DisplayState::eOrientation90:
4977 flags = Transform::ROT_90;
4978 break;
4979 case DisplayState::eOrientation180:
4980 flags = Transform::ROT_180;
4981 break;
4982 case DisplayState::eOrientation270:
4983 flags = Transform::ROT_270;
4984 break;
4985 }
4986 tr.set(flags, raWidth, raHeight);
4987 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004988 }
4989
4990 // ensure that sourceCrop is inside screen
4991 if (sourceCrop.left < 0) {
4992 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4993 }
chaviwa76b2712017-09-20 12:02:26 -07004994 if (sourceCrop.right > raWidth) {
4995 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004996 }
4997 if (sourceCrop.top < 0) {
4998 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4999 }
chaviwa76b2712017-09-20 12:02:26 -07005000 if (sourceCrop.bottom > raHeight) {
5001 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005002 }
5003
Chia-I Wu36574d92018-05-16 10:54:36 -07005004 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5005 engine.setOutputDataSpace(Dataspace::SRGB);
5006 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005007
Mathias Agopian180f10d2013-04-10 22:55:41 -07005008 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005009 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005010
Iris Chang7501ed62018-04-30 14:45:42 +08005011 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5012 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5013 // convert hw orientation into flag presentation
5014 // here inverse transform needed
5015 uint8_t hw_rot_90 = 0x00;
5016 uint8_t hw_flip_hv = 0x00;
5017 switch (mPrimaryDisplayOrientation) {
5018 case DisplayState::eOrientation90:
5019 hw_rot_90 = Transform::ROT_90;
5020 hw_flip_hv = Transform::ROT_180;
5021 break;
5022 case DisplayState::eOrientation180:
5023 hw_flip_hv = Transform::ROT_180;
5024 break;
5025 case DisplayState::eOrientation270:
5026 hw_rot_90 = Transform::ROT_90;
5027 break;
5028 }
5029
5030 // transform flags operation
5031 // 1) flip H V if both have ROT_90 flag
5032 // 2) XOR these flags
5033 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5034 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5035 if (rotation_rot_90 & hw_rot_90) {
5036 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5037 }
5038 rotation = static_cast<Transform::orientation_flags>
5039 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5040 }
5041
Mathias Agopian180f10d2013-04-10 22:55:41 -07005042 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005043 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005044 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005045 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005046
chaviw50da5042018-04-09 13:49:37 -07005047 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005048 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005049 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005050
chaviwa76b2712017-09-20 12:02:26 -07005051 traverseLayers([&](Layer* layer) {
5052 if (filtering) layer->setFiltering(true);
5053 layer->draw(renderArea, useIdentityTransform);
5054 if (filtering) layer->setFiltering(false);
5055 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005056}
5057
chaviwa76b2712017-09-20 12:02:26 -07005058status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5059 TraverseLayersFunction traverseLayers,
5060 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005061 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005062 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005063 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005064 ATRACE_CALL();
5065
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005066 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005067
5068 traverseLayers([&](Layer* layer) {
5069 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5070 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005071
Robert Carr03480e22018-01-04 16:02:06 -08005072 // We allow the system server to take screenshots of secure layers for
5073 // use in situations like the Screen-rotation animation and place
5074 // the impetus on WindowManager to not persist them.
5075 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005076 ALOGW("FB is protected: PERMISSION_DENIED");
5077 return PERMISSION_DENIED;
5078 }
5079
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005080 // this binds the given EGLImage as a framebuffer for the
5081 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005082 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005083 if (bufferBond.getStatus() != NO_ERROR) {
5084 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005085 return INVALID_OPERATION;
5086 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005087
Dan Stozaabcda352017-06-01 14:37:39 -07005088 // this will in fact render into our dequeued buffer
5089 // via an FBO, which means we didn't have to create
5090 // an EGLSurface and therefore we're not
5091 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005092 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005093
Dan Stozaabcda352017-06-01 14:37:39 -07005094 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005095 getRenderEngine().finish();
5096 *outSyncFd = -1;
5097
chaviwa76b2712017-09-20 12:02:26 -07005098 const auto reqWidth = renderArea.getReqWidth();
5099 const auto reqHeight = renderArea.getReqHeight();
5100
Dan Stozaabcda352017-06-01 14:37:39 -07005101 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5102 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005103 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005104 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005105 } else {
5106 base::unique_fd syncFd = getRenderEngine().flush();
5107 if (syncFd < 0) {
5108 getRenderEngine().finish();
5109 }
5110 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005111 }
5112
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005113 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005114}
5115
Mathias Agopiand5556842013-09-19 17:08:37 -07005116void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005117 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005118 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005119 for (size_t y = 0; y < h; y++) {
5120 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5121 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005122 if (p[x] != 0xFF000000) return;
5123 }
5124 }
chaviwa76b2712017-09-20 12:02:26 -07005125 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005126
Robert Carr2047fae2016-11-28 14:09:09 -08005127 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005128 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005129 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005130 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5131 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5132 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5133 static_cast<float>(state.color.a));
5134 i++;
5135 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005136 }
5137}
5138
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005139// ---------------------------------------------------------------------------
5140
Dan Stoza412903f2017-04-27 13:42:17 -07005141void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5142 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005143}
5144
Dan Stoza412903f2017-04-27 13:42:17 -07005145void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5146 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005147}
5148
chaviwa76b2712017-09-20 12:02:26 -07005149void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5150 int32_t maxLayerZ,
5151 const LayerVector::Visitor& visitor) {
5152 // We loop through the first level of layers without traversing,
5153 // as we need to interpret min/max layer Z in the top level Z space.
5154 for (const auto& layer : mDrawingState.layersSortedByZ) {
5155 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5156 continue;
5157 }
5158 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005159 // relative layers are traversed in Layer::traverseInZOrder
5160 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005161 continue;
5162 }
5163 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005164 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5165 return;
5166 }
chaviwa76b2712017-09-20 12:02:26 -07005167 if (!layer->isVisible()) {
5168 return;
5169 }
5170 visitor(layer);
5171 });
5172 }
5173}
5174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005175}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005176
5177
5178#if defined(__gl_h_)
5179#error "don't include gl/gl.h in this file"
5180#endif
5181
5182#if defined(__gl2_h_)
5183#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005184#endif