blob: eae607f54964771c892d8433ea6f2088be19332d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080091#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
92#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090093#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094
chaviw1d044282017-09-27 12:19:28 -070095#include <layerproto/LayerProtoParser.h>
96
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097#define DISPLAY_COUNT 1
98
Mathias Agopianfee2b462013-07-03 12:34:01 -070099/*
100 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
101 * black pixels.
102 */
103#define DEBUG_SCREENSHOTS false
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700109using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700110using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700111using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700112using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
Steven Thomasb02664d2017-07-26 18:48:28 -0700114namespace {
115class ConditionalLock {
116public:
117 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
118 if (lock) {
119 mMutex.lock();
120 }
121 }
122 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
123private:
124 Mutex& mMutex;
125 bool mLocked;
126};
127} // namespace anonymous
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129// ---------------------------------------------------------------------------
130
Mathias Agopian99b49842011-06-27 16:05:52 -0700131const String16 sHardwareTest("android.permission.HARDWARE_TEST");
132const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
133const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
134const String16 sDump("android.permission.DUMP");
135
136// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800137int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
138int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700139int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700140bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800141uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800142bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800143bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800144int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800145// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600146bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700147
Kalle Raitaa099a242017-01-11 11:17:29 -0800148
149std::string getHwcServiceName() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.hwc_service_name", value, "default");
152 ALOGI("Using HWComposer service: '%s'", value);
153 return std::string(value);
154}
155
156bool useTrebleTestingOverride() {
157 char value[PROPERTY_VALUE_MAX] = {};
158 property_get("debug.sf.treble_testing_override", value, "false");
159 ALOGI("Treble testing override: '%s'", value);
160 return std::string(value) == "true";
161}
162
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800163std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
164 switch(displayColorSetting) {
165 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700166 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800167 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800169 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700170 return std::string("Enhanced");
171 default:
172 return std::string("Unknown ") +
173 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800174 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175}
176
Lloyd Pique09594832018-01-22 17:48:03 -0800177NativeWindowSurface::~NativeWindowSurface() = default;
178
179namespace impl {
180
181class NativeWindowSurface final : public android::NativeWindowSurface {
182public:
183 static std::unique_ptr<android::NativeWindowSurface> create(
184 const sp<IGraphicBufferProducer>& producer) {
185 return std::make_unique<NativeWindowSurface>(producer);
186 }
187
188 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
189 : surface(new Surface(producer, false)) {}
190
191 ~NativeWindowSurface() override = default;
192
193private:
194 sp<ANativeWindow> getNativeWindow() const override { return surface; }
195
196 void preallocateBuffers() override { surface->allocateBuffers(); }
197
198 sp<Surface> surface;
199};
200
201} // namespace impl
202
David Sodmanbc815282017-11-05 18:57:52 -0800203SurfaceFlingerBE::SurfaceFlingerBE()
204 : mHwcServiceName(getHwcServiceName()),
205 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800206 mFrameBuckets(),
207 mTotalTime(0),
208 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800209 mComposerSequenceId(0) {
210}
211
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800212SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800213 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700215 mTransactionPending(false),
216 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700217 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700218 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700219 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800221 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800223 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800224 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700226 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700227 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700228 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700229 mDebugInSwapBuffers(0),
230 mLastSwapBufferTime(0),
231 mDebugInTransaction(0),
232 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700233 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700234 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000235 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700236 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700237 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800238 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800239 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700240 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800241 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800242 mCreateBufferQueue(&BufferQueue::createBufferQueue),
243 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800244
245SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800246 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800247
248 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
249 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
250
251 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
252 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
253
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800254 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
255 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700257 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
259
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700260 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
262
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800263 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
265
Steven Thomas050b2c82017-03-06 11:45:16 -0800266 // Vr flinger is only enabled on Daydream ready devices.
267 useVrFlinger = getBool< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::useVrFlinger>(false);
269
Fabien Sanglard1971b632017-03-10 14:50:03 -0800270 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
272
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273 hasWideColorDisplay =
274 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
275
Iris Chang7501ed62018-04-30 14:45:42 +0800276 V1_1::DisplayOrientation primaryDisplayOrientation =
277 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
278 V1_1::DisplayOrientation::ORIENTATION_0);
279
280 switch (primaryDisplayOrientation) {
281 case V1_1::DisplayOrientation::ORIENTATION_90:
282 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
283 break;
284 case V1_1::DisplayOrientation::ORIENTATION_180:
285 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
286 break;
287 case V1_1::DisplayOrientation::ORIENTATION_270:
288 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
289 break;
290 default:
291 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
292 break;
293 }
294 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
295
David Sodman99974d22017-11-28 12:04:33 -0800296 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700297
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298 // debugging stuff...
299 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700300
Mathias Agopianb4b17302013-03-20 18:36:41 -0700301 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700302 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700303
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 property_get("debug.sf.showupdates", value, "0");
305 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700306
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307 property_get("debug.sf.ddms", value, "0");
308 mDebugDDMS = atoi(value);
309 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700310 if (!startDdmConnection()) {
311 // start failed, and DDMS debugging not enabled
312 mDebugDDMS = 0;
313 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700314 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700315 ALOGI_IF(mDebugRegion, "showupdates enabled");
316 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700317
318 property_get("debug.sf.disable_backpressure", value, "0");
319 mPropagateBackpressure = !atoi(value);
320 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700321
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800322 property_get("debug.sf.enable_hwc_vds", value, "0");
323 mUseHwcVirtualDisplays = atoi(value);
324 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800325
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800326 property_get("ro.sf.disable_triple_buffer", value, "1");
327 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800328 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700329
Yiwei Zhang243b3782018-05-15 17:40:04 -0700330 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700331 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
332 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
333
Dan Stoza2713c302018-03-28 17:07:36 -0700334 property_get("debug.sf.early_phase_offset_ns", value, "0");
335 const int earlyWakeupOffsetOffsetNs = atoi(value);
336 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
337 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
338 sfVsyncPhaseOffsetNs);
339
Romain Guy11d63f42017-07-20 12:47:14 -0700340 // We should be reading 'persist.sys.sf.color_saturation' here
341 // but since /data may be encrypted, we need to wait until after vold
342 // comes online to attempt to read the property. The property is
343 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800344
345 if (useTrebleTestingOverride()) {
346 // Without the override SurfaceFlinger cannot connect to HIDL
347 // services that are not listed in the manifests. Considered
348 // deriving the setting from the set service name, but it
349 // would be brittle if the name that's not 'default' is used
350 // for production purposes later on.
351 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355void SurfaceFlinger::onFirstRef()
356{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800357 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800358}
359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360SurfaceFlinger::~SurfaceFlinger()
361{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362}
363
Dan Stozac7014012014-02-14 15:03:43 -0800364void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800365{
366 // the window manager died on us. prepare its eulogy.
367
Andy McFadden13a082e2012-08-24 10:16:42 -0700368 // restore initial conditions (default device unblank, etc)
369 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800370
371 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800373}
374
Robert Carr1db73f62016-12-21 12:58:51 -0800375static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700376 status_t err = client->initCheck();
377 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800378 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379 }
Robert Carr1db73f62016-12-21 12:58:51 -0800380 return nullptr;
381}
382
383sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
384 return initClient(new Client(this));
385}
386
387sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
388 const sp<IGraphicBufferProducer>& gbp) {
389 if (authenticateSurfaceTexture(gbp) == false) {
390 return nullptr;
391 }
392 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
393 if (layer == nullptr) {
394 return nullptr;
395 }
396
397 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700400sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
401 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402{
403 class DisplayToken : public BBinder {
404 sp<SurfaceFlinger> flinger;
405 virtual ~DisplayToken() {
406 // no more references, this display must be terminated
407 Mutex::Autolock _l(flinger->mStateLock);
408 flinger->mCurrentState.displays.removeItem(this);
409 flinger->setTransactionFlags(eDisplayTransactionNeeded);
410 }
411 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700412 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 : flinger(flinger) {
414 }
415 };
416
417 sp<BBinder> token = new DisplayToken(this);
418
419 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700420 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700421 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700422 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800423 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700424 return token;
425}
426
Jesse Hall6c913be2013-08-08 12:15:49 -0700427void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
428 Mutex::Autolock _l(mStateLock);
429
430 ssize_t idx = mCurrentState.displays.indexOfKey(display);
431 if (idx < 0) {
432 ALOGW("destroyDisplay: invalid display token");
433 return;
434 }
435
436 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
437 if (!info.isVirtualDisplay()) {
438 ALOGE("destroyDisplay called for non-virtual display");
439 return;
440 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800441 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 mCurrentState.displays.removeItemsAt(idx);
443 setTransactionFlags(eDisplayTransactionNeeded);
444}
445
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700447 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800449 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450 }
Jesse Hall692c7232012-11-08 15:41:56 -0800451 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452}
453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454void SurfaceFlinger::bootFinished()
455{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700456 if (mStartPropertySetThread->join() != NO_ERROR) {
457 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800458 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800459 const nsecs_t now = systemTime();
460 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000461 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700462
463 // wait patiently for the window manager death
464 const String16 name("window");
465 sp<IBinder> window(defaultServiceManager()->getService(name));
466 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700467 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700468 }
469
Steven Thomas050b2c82017-03-06 11:45:16 -0800470 if (mVrFlinger) {
471 mVrFlinger->OnBootFinished();
472 }
473
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700474 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700475 // formerly we would just kill the process, but we now ask it to exit so it
476 // can choose where to stop the animation.
477 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700478
479 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
480 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
481 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700482
Thierry Strudel2924d012017-08-14 15:19:37 -0700483 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700484 readPersistentProperties();
485 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700486 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487}
488
Mathias Agopian3f844832013-08-07 21:24:32 -0700489void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700490 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800491 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700492 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800494 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
495 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700496 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700497 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700498 return true;
499 }
500 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700501 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700502}
503
Lloyd Piquee83f9312018-02-01 12:53:17 -0800504class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700506 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000507 const char* name) :
508 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700509 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700510 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000511 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
512 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700513 mDispSync(dispSync),
514 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 mVsyncMutex(),
516 mPhaseOffset(phaseOffset),
517 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700518
Lloyd Piquee83f9312018-02-01 12:53:17 -0800519 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520
Lloyd Piquee83f9312018-02-01 12:53:17 -0800521 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error registering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 } else {
532 status_t err = mDispSync->removeEventListener(
533 static_cast<DispSync::Callback*>(this));
534 if (err != NO_ERROR) {
535 ALOGE("error unregistering vsync callback: %s (%d)",
536 strerror(-err), err);
537 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700538 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 }
542
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700544 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545 mCallback = callback;
546 }
547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549 Mutex::Autolock lock(mVsyncMutex);
550
551 // Normalize phaseOffset to [0, period)
552 auto period = mDispSync->getPeriod();
553 phaseOffset %= period;
554 if (phaseOffset < 0) {
555 // If we're here, then phaseOffset is in (-period, 0). After this
556 // operation, it will be in (0, period)
557 phaseOffset += period;
558 }
559 mPhaseOffset = phaseOffset;
560
561 // If we're not enabled, we don't need to mess with the listeners
562 if (!mEnabled) {
563 return;
564 }
565
Dan Stoza2713c302018-03-28 17:07:36 -0700566 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
567 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700569 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 strerror(-err), err);
571 }
572 }
573
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574private:
575 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 callback = mCallback;
580
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700581 if (mTraceVsync) {
582 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700583 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700584 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585 }
586
Peiyong Lin566a3b42018-01-09 18:22:43 -0800587 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 callback->onVSyncEvent(when);
589 }
590 }
591
Tim Murray4a4e4a22016-04-19 16:29:23 +0000592 const char* const mName;
593
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 int mValue;
595
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700596 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700597 const String8 mVsyncOnLabel;
598 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700599
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700601
602 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604
605 Mutex mVsyncMutex; // Protects the following
606 nsecs_t mPhaseOffset;
607 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608};
609
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800612 InjectVSyncSource() = default;
613 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614
Lloyd Piquee83f9312018-02-01 12:53:17 -0800615 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700616 std::lock_guard<std::mutex> lock(mCallbackMutex);
617 mCallback = callback;
618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700621 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700622 if (mCallback) {
623 mCallback->onVSyncEvent(when);
624 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625 }
626
Lloyd Piquee83f9312018-02-01 12:53:17 -0800627 void setVSyncEnabled(bool) override {}
628 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700629
630private:
631 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800632 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700633};
634
Wei Wangf9b05ee2017-07-19 20:59:39 -0700635// Do not call property_set on main thread which will be blocked by init
636// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700638 ALOGI( "SurfaceFlinger's main thread ready to run. "
639 "Initializing graphics H/W...");
640
Thierry Strudel2924d012017-08-14 15:19:37 -0700641 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900642
Steven Thomasb02664d2017-07-26 18:48:28 -0700643 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800644
Steven Thomasb02664d2017-07-26 18:48:28 -0700645 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800646 mEventThreadSource =
647 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
648 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800649 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
650 [this]() { resyncWithRateLimit(); },
651 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800652 "appEventThread");
653 mSfEventThreadSource =
654 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
655 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800656
Lloyd Pique24b0a482018-03-09 18:52:26 -0800657 mSFEventThread =
658 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
659 [this]() { resyncWithRateLimit(); },
660 [this](nsecs_t timestamp) {
661 mInterceptor->saveVSyncEvent(timestamp);
662 },
663 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800664 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700665 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800668 getBE().mRenderEngine =
669 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
670 hasWideColorDisplay
671 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
672 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800673 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700674
675 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
676 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800677 getBE().mHwc.reset(
678 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700679 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
682 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
683 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Lloyd Piquefcd86612017-12-14 17:15:36 -0800685 // make the default display GLContext current so that we can create textures
686 // when creating Layers (which may happens before we render something)
687 getDefaultDisplayDeviceLocked()->makeCurrent();
688
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 if (useVrFlinger) {
690 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700691 // This callback is called from the vr flinger dispatch thread. We
692 // need to call signalTransaction(), which requires holding
693 // mStateLock when we're not on the main thread. Acquiring
694 // mStateLock from the vr flinger dispatch thread might trigger a
695 // deadlock in surface flinger (see b/66916578), so post a message
696 // to be handled on the main thread instead.
697 sp<LambdaMessage> message = new LambdaMessage([=]() {
698 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
699 mVrFlingerRequestsDisplay = requestDisplay;
700 signalTransaction();
701 });
702 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 };
David Sodman105b7dc2017-11-04 20:28:14 -0700704 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
705 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800706 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 if (!mVrFlinger) {
708 ALOGE("Failed to start vrflinger");
709 }
710 }
711
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800712 mEventControlThread = std::make_unique<impl::EventControlThread>(
713 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700714
Mathias Agopian92a979a2012-08-02 18:32:23 -0700715 // initialize our drawing state
716 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700717
Andy McFadden13a082e2012-08-24 10:16:42 -0700718 // set initial conditions (e.g. unblank default device)
719 initializeDisplays();
720
David Sodmanbc815282017-11-05 18:57:52 -0800721 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700722
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 // Inform native graphics APIs whether the present timestamp is supported:
724 if (getHwComposer().hasCapability(
725 HWC2::Capability::PresentFenceIsNotReliable)) {
726 mStartPropertySetThread = new StartPropertySetThread(false);
727 } else {
728 mStartPropertySetThread = new StartPropertySetThread(true);
729 }
730
731 if (mStartPropertySetThread->Start() != NO_ERROR) {
732 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800733 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800734
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
736 Dataspace::SRGB_LINEAR);
737
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700739}
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 Mutex::Autolock _l(mStateLock);
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744 char value[PROPERTY_VALUE_MAX];
745
746 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800747 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100750
751 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700752 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800766 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800770 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Dan Stoza7f7da322014-05-02 15:26:25 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
809 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500814 if (!display.get())
815 return NAME_NOT_FOUND;
816
Jesse Hall692c7232012-11-08 15:41:56 -0800817 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700818 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800819 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700820 type = i;
821 break;
822 }
823 }
824
825 if (type < 0) {
826 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700827 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 // TODO: Not sure if display density should handled by SF any longer
830 class Density {
831 static int getDensityFromProperty(char const* propName) {
832 char property[PROPERTY_VALUE_MAX];
833 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800834 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 density = atoi(property);
836 }
837 return density;
838 }
839 public:
840 static int getEmuDensity() {
841 return getDensityFromProperty("qemu.sf.lcd_density"); }
842 static int getBuildDensity() {
843 return getDensityFromProperty("ro.sf.lcd_density"); }
844 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700847
Steven Thomas6d8110b2017-08-31 18:24:21 -0700848 ConditionalLock _l(mStateLock,
849 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 DisplayInfo info = DisplayInfo();
852
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 float xdpi = hwConfig->getDpiX();
854 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
856 if (type == DisplayDevice::DISPLAY_PRIMARY) {
857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700873 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800874 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882 info.w = hwConfig->getWidth();
883 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Iris Chang7501ed62018-04-30 14:45:42 +0800907 if (type == DisplayDevice::DISPLAY_PRIMARY &&
908 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800920 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
924 // FIXME for now we always return stats for the primary display
925 memset(stats, 0, sizeof(*stats));
926 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
928 return NO_ERROR;
929}
930
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800932 if (display == nullptr) {
933 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800934 return BAD_VALUE;
935 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700936
937 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800938 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700939 return device->getActiveConfig();
940 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941
Dan Stoza24a42e92015-03-09 10:04:11 -0700942 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700943}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700944
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
946 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
947 this);
948 int32_t type = hw->getDisplayType();
949 int currentMode = hw->getActiveConfig();
950
951 if (mode == currentMode) {
952 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
953 return;
954 }
955
956 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
957 ALOGW("Trying to set config for virtual display");
958 return;
959 }
960
961 hw->setActiveConfig(mode);
962 getHwComposer().setActiveConfig(type, mode);
963}
964
965status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
966 class MessageSetActiveConfig: public MessageBase {
967 SurfaceFlinger& mFlinger;
968 sp<IBinder> mDisplay;
969 int mMode;
970 public:
971 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
972 int mode) :
973 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
974 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700975 Vector<DisplayInfo> configs;
976 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700977 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700978 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700979 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700980 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700981 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800983 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700985 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
987 ALOGW("Attempt to set active config = %d for virtual display",
988 mMode);
989 } else {
990 mFlinger.setActiveConfigInternal(hw, mMode);
991 }
992 return true;
993 }
994 };
995 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
996 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700997 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700998}
Michael Wright28f24d02016-07-12 13:30:53 -0700999status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001001 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1002 return BAD_VALUE;
1003 }
1004
1005 if (!display.get()) {
1006 return NAME_NOT_FOUND;
1007 }
1008
1009 int32_t type = NAME_NOT_FOUND;
1010 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1011 if (display == mBuiltinDisplays[i]) {
1012 type = i;
1013 break;
1014 }
1015 }
1016
1017 if (type < 0) {
1018 return type;
1019 }
1020
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001022 {
1023 ConditionalLock _l(mStateLock,
1024 std::this_thread::get_id() != mMainThreadId);
1025 modes = getHwComposer().getColorModes(type);
1026 }
Michael Wright28f24d02016-07-12 13:30:53 -07001027 outColorModes->clear();
1028 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1029
1030 return NO_ERROR;
1031}
1032
Peiyong Lina52f0292018-03-14 17:26:31 -07001033ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001034 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001035 if (device != nullptr) {
1036 return device->getActiveColorMode();
1037 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001038 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001039}
1040
1041void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001042 ColorMode mode, Dataspace dataSpace,
1043 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001044 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001046 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001047 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001048
Peiyong Lin38e9a562018-04-10 16:24:20 -07001049 if (mode == currentMode && dataSpace == currentDataSpace &&
1050 renderIntent == currentRenderIntent) {
1051 return;
1052 }
1053
1054 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1055 ALOGW("Trying to set config for virtual display");
1056 return;
1057 }
1058
1059 hw->setActiveColorMode(mode);
1060 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001061 hw->setActiveRenderIntent(renderIntent);
1062 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1063
1064 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1065 decodeColorMode(mode).c_str(), mode,
1066 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1067 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001068}
1069
1070
1071status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001073 class MessageSetActiveColorMode: public MessageBase {
1074 SurfaceFlinger& mFlinger;
1075 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 public:
1078 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001080 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1081 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001083 mFlinger.getDisplayColorModes(mDisplay, &modes);
1084 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return true;
1089 }
1090 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1091 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001092 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1093 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001094 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001095 ALOGW("Attempt to set active color mode %s %d for virtual display",
1096 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001097 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001098 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1099 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
1101 return true;
1102 }
1103 };
1104 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1105 postMessageSync(msg);
1106 return NO_ERROR;
1107}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001108
Svetoslavd85084b2014-03-20 10:28:31 -07001109status_t SurfaceFlinger::clearAnimationFrameStats() {
1110 Mutex::Autolock _l(mStateLock);
1111 mAnimFrameTracker.clearStats();
1112 return NO_ERROR;
1113}
1114
1115status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1116 Mutex::Autolock _l(mStateLock);
1117 mAnimFrameTracker.getStats(outStats);
1118 return NO_ERROR;
1119}
1120
Dan Stozac4f471e2016-03-24 09:31:08 -07001121status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1122 HdrCapabilities* outCapabilities) const {
1123 Mutex::Autolock _l(mStateLock);
1124
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001125 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001126 if (displayDevice == nullptr) {
1127 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1128 return BAD_VALUE;
1129 }
1130
Peiyong Linfb069302018-04-25 14:34:31 -07001131 // At this point the DisplayDeivce should already be set up,
1132 // meaning the luminance information is already queried from
1133 // hardware composer and stored properly.
1134 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1135 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1136 capabilities.getDesiredMaxLuminance(),
1137 capabilities.getDesiredMaxAverageLuminance(),
1138 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001139
1140 return NO_ERROR;
1141}
1142
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1145 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 if (mInjectVSyncs == enable) {
1148 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150
1151 if (enable) {
1152 ALOGV("VSync Injections enabled");
1153 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001154 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001155 mInjectorEventThread = std::make_unique<
1156 impl::EventThread>(mVSyncInjector.get(),
1157 [this]() { resyncWithRateLimit(); },
1158 impl::EventThread::InterceptVSyncsCallback(),
1159 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001161 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 } else {
1163 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001164 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 }
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 });
1169 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001170 return NO_ERROR;
1171}
1172
1173status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
1175
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 if (!mInjectVSyncs) {
1177 ALOGE("VSync Injections not enabled");
1178 return BAD_VALUE;
1179 }
1180 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1181 ALOGV("Injecting VSync inside SurfaceFlinger");
1182 mVSyncInjector->onInjectSyncEvent(when);
1183 }
1184 return NO_ERROR;
1185}
1186
Lloyd Pique755e3192018-01-31 16:46:15 -08001187status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1188 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001189 IPCThreadState* ipc = IPCThreadState::self();
1190 const int pid = ipc->getCallingPid();
1191 const int uid = ipc->getCallingUid();
1192 if ((uid != AID_SHELL) &&
1193 !PermissionCache::checkPermission(sDump, pid, uid)) {
1194 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1195 return PERMISSION_DENIED;
1196 }
1197
1198 // Try to acquire a lock for 1s, fail gracefully
1199 const status_t err = mStateLock.timedLock(s2ns(1));
1200 const bool locked = (err == NO_ERROR);
1201 if (!locked) {
1202 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1203 return TIMED_OUT;
1204 }
1205
1206 outLayers->clear();
1207 mCurrentState.traverseInZOrder([&](Layer* layer) {
1208 outLayers->push_back(layer->getLayerDebugInfo());
1209 });
1210
1211 mStateLock.unlock();
1212 return NO_ERROR;
1213}
1214
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001215// ----------------------------------------------------------------------------
1216
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001217sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1218 ISurfaceComposer::VsyncSource vsyncSource) {
1219 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1220 return mSFEventThread->createEventConnection();
1221 } else {
1222 return mEventThread->createEventConnection();
1223 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001224}
1225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001226// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227
1228void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001237 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001238}
1239
1240void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001241 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001242 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001243}
1244
1245status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001246 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001247 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001248}
1249
1250status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001251 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001252 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253 if (res == NO_ERROR) {
1254 msg->wait();
1255 }
1256 return res;
1257}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001258
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001260 do {
1261 waitForEvent();
1262 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263}
1264
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265void SurfaceFlinger::enableHardwareVsync() {
1266 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001269 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1270 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001272 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273}
1274
Jesse Hall948fe0c2013-10-14 12:56:09 -07001275void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276 Mutex::Autolock _l(mHWVsyncLock);
1277
Jesse Hall948fe0c2013-10-14 12:56:09 -07001278 if (makeAvailable) {
1279 mHWVsyncAvailable = true;
1280 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001281 // Hardware vsync is not currently available, so abort the resync
1282 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001283 return;
1284 }
1285
David Sodman105b7dc2017-11-04 20:28:14 -07001286 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001287 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288
1289 mPrimaryDispSync.reset();
1290 mPrimaryDispSync.setPeriod(period);
1291
1292 if (!mPrimaryHWVsyncEnabled) {
1293 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1295 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryHWVsyncEnabled = true;
1297 }
1298}
1299
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 Mutex::Autolock _l(mHWVsyncLock);
1302 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1304 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 mPrimaryDispSync.endResync();
1306 mPrimaryHWVsyncEnabled = false;
1307 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308 if (makeUnavailable) {
1309 mHWVsyncAvailable = false;
1310 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311}
1312
Tim Murray4a4e4a22016-04-19 16:29:23 +00001313void SurfaceFlinger::resyncWithRateLimit() {
1314 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001315
1316 // No explicit locking is needed here since EventThread holds a lock while calling this method
1317 static nsecs_t sLastResyncAttempted = 0;
1318 const nsecs_t now = systemTime();
1319 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001320 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001321 }
Dan Stoza57164302017-05-08 14:03:54 -07001322 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001323}
1324
Steven Thomasb02664d2017-07-26 18:48:28 -07001325void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1326 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001327 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001329 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 return;
1331 }
1332
1333 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001334 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001335 return;
1336 }
1337
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 { // Scope for the lock
1341 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001343 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001345 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001346
1347 if (needsHwVsync) {
1348 enableHardwareVsync();
1349 } else {
1350 disableHardwareVsync(false);
1351 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001352}
1353
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001354void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001355 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1356 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001357}
1358
Lloyd Pique715a2c12017-12-14 17:18:08 -08001359void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1360 HWC2::Connection connection) {
1361 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1362 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001363
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 // Ignore events that do not have the right sequenceId.
1365 if (sequenceId != getBE().mComposerSequenceId) {
1366 return;
1367 }
1368
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 // Only lock if we're not on the main thread. This function is normally
1370 // called on a hwbinder thread, but for the primary display it's called on
1371 // the main thread with the state lock already held, so don't attempt to
1372 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374
Lloyd Pique715a2c12017-12-14 17:18:08 -08001375 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001376
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001377 if (std::this_thread::get_id() == mMainThreadId) {
1378 // Process all pending hot plug events immediately if we are on the main thread.
1379 processDisplayHotplugEventsLocked();
1380 }
1381
Lloyd Piqueba04e622017-12-14 17:11:26 -08001382 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001383}
1384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385void SurfaceFlinger::onRefreshReceived(int sequenceId,
1386 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001388 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001391 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001392}
1393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001395 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001397 getHwComposer().setVsyncEnabled(disp,
1398 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001399}
1400
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001402void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 // Clear the drawing state so that the logic inside of
1405 // handleTransactionLocked will fire. It will determine the delta between
1406 // mCurrentState and mDrawingState and re-apply all changes when we make the
1407 // transition.
1408 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001409 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410 mDisplays.clear();
1411}
1412
Steven Thomas050b2c82017-03-06 11:45:16 -08001413void SurfaceFlinger::updateVrFlinger() {
1414 if (!mVrFlinger)
1415 return;
1416 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 return;
1419 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420
David Sodman105b7dc2017-11-04 20:28:14 -07001421 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 ALOGE("Vr flinger is only supported for remote hardware composer"
1423 " service connections. Ignoring request to transition to vr"
1424 " flinger.");
1425 mVrFlingerRequestsDisplay = false;
1426 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 int currentDisplayPowerMode = getDisplayDeviceLocked(
1432 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001439 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001440 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1441 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001442 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
David Sodman105b7dc2017-11-04 20:28:14 -07001444 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1445 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001446
1447 if (vrFlingerRequestsDisplay) {
1448 mVrFlinger->GrantDisplayOwnership();
1449 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
1453 mVisibleRegionsDirty = true;
1454 invalidateHwcGeometry();
1455
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1458 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1459 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001462 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 const nsecs_t period = activeConfig->getVsyncPeriod();
1464 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Use phase of 0 since phase is not known.
1467 // Use latency of 0, which will snap to the ideal latency.
1468 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001469
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 android_atomic_or(1, &mRepaintEverything);
1471 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472}
1473
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001475 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001476 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001478 bool frameMissed = !mHadClientComposition &&
1479 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480 (mPreviousPresentFence->getSignalTime() ==
1481 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001482 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001483 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001484 mTimeStats.incrementMissedFrames();
1485 if (mPropagateBackpressure) {
1486 signalLayerUpdate();
1487 break;
1488 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001489 }
Dan Stoza50182882016-07-08 12:02:20 -07001490
Steven Thomas050b2c82017-03-06 11:45:16 -08001491 // Now that we're going to make it to the handleMessageTransaction()
1492 // call below it's safe to call updateVrFlinger(), which will
1493 // potentially trigger a display handoff.
1494 updateVrFlinger();
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 bool refreshNeeded = handleMessageTransaction();
1497 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001498 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001500 // Signal a refresh if a transaction modified the window state,
1501 // a new buffer was latched, or if HWC has requested a full
1502 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 signalRefresh();
1504 }
1505 break;
1506 }
1507 case MessageQueue::REFRESH: {
1508 handleMessageRefresh();
1509 break;
1510 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 }
1512}
1513
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001515 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001517 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526}
1527
1528void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001530
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = false;
1532
Pablo Ceballos40845df2016-01-25 17:41:15 -08001533 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001534
Brian Andersond6927fb2016-07-23 23:37:30 -07001535 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536 rebuildLayerStacks();
1537 setUpHWComposer();
1538 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001539 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001540 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001541 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001543
David Sodman105b7dc2017-11-04 20:28:14 -07001544 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001545
1546 mHadClientComposition = false;
1547 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1548 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1549 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001550 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001551 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001552 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001553
Dan Stoza9e56aa02015-11-02 13:00:03 -08001554 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001556
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557void SurfaceFlinger::doDebugFlashRegions()
1558{
1559 // is debugging enabled
1560 if (CC_LIKELY(!mDebugRegion))
1561 return;
1562
1563 const bool repaintEverything = mRepaintEverything;
1564 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1565 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001566 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 // transform the dirty region into this screen's coordinate space
1568 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1569 if (!dirtyRegion.isEmpty()) {
1570 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001571 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572
1573 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001575 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001576 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1577
Mathias Agopianda27af92012-09-13 18:17:13 -07001578 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579 }
1580 }
1581 }
1582
1583 postFramebuffer();
1584
1585 if (mDebugRegion > 1) {
1586 usleep(mDebugRegion * 1000);
1587 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001588
Dan Stoza9e56aa02015-11-02 13:00:03 -08001589 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001590 auto& displayDevice = mDisplays[displayId];
1591 if (!displayDevice->isDisplayOn()) {
1592 continue;
1593 }
1594
David Sodman105b7dc2017-11-04 20:28:14 -07001595 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1596 ALOGE_IF(result != NO_ERROR,
1597 "prepareFrame for display %zd failed:"
1598 " %d (%s)",
1599 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001600 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601}
1602
Adrian Roos1e1a1282017-11-01 19:05:31 +01001603void SurfaceFlinger::doTracing(const char* where) {
1604 ATRACE_CALL();
1605 ATRACE_NAME(where);
1606 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001607 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001608 }
1609}
1610
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001611void SurfaceFlinger::logLayerStats() {
1612 ATRACE_CALL();
1613 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1614 int32_t hwcId = -1;
1615 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1616 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1617 if (displayDevice->isPrimary()) {
1618 hwcId = displayDevice->getHwcDisplayId();
1619 break;
1620 }
1621 }
1622 if (hwcId < 0) {
1623 ALOGE("LayerStats: Hmmm, no primary display?");
1624 return;
1625 }
1626 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1627 }
1628}
1629
Brian Andersond6927fb2016-07-23 23:37:30 -07001630void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001632 ATRACE_CALL();
1633 ALOGV("preComposition");
1634
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001636 mDrawingState.traverseInZOrder([&](Layer* layer) {
1637 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 needExtraInvalidate = true;
1639 }
Robert Carr2047fae2016-11-28 14:09:09 -08001640 });
1641
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642 if (needExtraInvalidate) {
1643 signalLayerUpdate();
1644 }
1645}
1646
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647void SurfaceFlinger::updateCompositorTiming(
1648 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1649 std::shared_ptr<FenceTime>& presentFenceTime) {
1650 // Update queue of past composite+present times and determine the
1651 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001652 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001654 while (!getBE().mCompositePresentTimes.empty()) {
1655 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 // Cached values should have been updated before calling this method,
1657 // which helps avoid duplicate syscalls.
1658 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1659 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1660 break;
1661 }
1662 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001663 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 }
1665
1666 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001667 while (getBE().mCompositePresentTimes.size() > 16) {
1668 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 }
1670
Brian Andersond0010582017-03-07 13:20:31 -08001671 setCompositorTimingSnapped(
1672 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1673}
1674
1675void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1676 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 // Integer division and modulo round toward 0 not -inf, so we need to
1678 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001679 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1681 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1682
Brian Andersond0010582017-03-07 13:20:31 -08001683 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1684 if (idealLatency <= 0) {
1685 idealLatency = vsyncInterval;
1686 }
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 // Snap the latency to a value that removes scheduling jitter from the
1689 // composition and present times, which often have >1ms of jitter.
1690 // Reducing jitter is important if an app attempts to extrapolate
1691 // something (such as user input) to an accurate diasplay time.
1692 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1693 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001694 nsecs_t bias = vsyncInterval / 2;
1695 int64_t extraVsyncs =
1696 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1697 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1698 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001699
David Sodman99974d22017-11-28 12:04:33 -08001700 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1701 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1702 getBE().mCompositorTiming.interval = vsyncInterval;
1703 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704}
1705
1706void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 ATRACE_CALL();
1709 ALOGV("postComposition");
1710
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001712 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001714 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001715 }
1716
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 // |mStateLock| not needed as we are on the main thread
1718 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001722 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 glCompositionDoneFenceTime =
1724 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 } else {
1727 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1728 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729
David Sodman73beded2017-11-15 11:56:06 -08001730 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001731 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001732 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001734
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1736 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1737
1738 // We use the refreshStartTime which might be sampled a little later than
1739 // when we started doing work for this frame, but that should be okay
1740 // since updateCompositorTiming has snapping logic.
1741 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001742 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001743 CompositorTiming compositorTiming;
1744 {
David Sodman99974d22017-11-28 12:04:33 -08001745 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1746 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001747 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748
Robert Carr2047fae2016-11-28 14:09:09 -08001749 mDrawingState.traverseInZOrder([&](Layer* layer) {
1750 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001751 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001752 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001753 recordBufferingStats(layer->getName().string(),
1754 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001755 }
Robert Carr2047fae2016-11-28 14:09:09 -08001756 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001757
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001758 if (presentFenceTime->isValid()) {
1759 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001760 enableHardwareVsync();
1761 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001762 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001763 }
1764 }
1765
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001766 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001767 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001768 enableHardwareVsync();
1769 }
1770 }
1771
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001772 if (mAnimCompositionPending) {
1773 mAnimCompositionPending = false;
1774
Brian Anderson4e606e32017-03-16 15:34:57 -07001775 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001777 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001778 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001779 // The HWC doesn't support present fences, so use the refresh
1780 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001781 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001782 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001783 mAnimFrameTracker.setActualPresentTime(presentTime);
1784 }
1785 mAnimFrameTracker.advanceFrame();
1786 }
Dan Stozab90cf072015-03-05 11:05:59 -08001787
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001788 mTimeStats.incrementTotalFrames();
1789 if (mHadClientComposition) {
1790 mTimeStats.incrementClientCompositionFrames();
1791 }
1792
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001793 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1794 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001795 return;
1796 }
1797
1798 nsecs_t currentTime = systemTime();
1799 if (mHasPoweredOff) {
1800 mHasPoweredOff = false;
1801 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001802 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001804 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1805 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001810 }
David Sodman4a36e932017-11-07 14:29:47 -08001811 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812}
1813
1814void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("rebuildLayerStacks");
1817
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001820 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 mVisibleRegionsDirty = false;
1822 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823
Jeff Sharkey76488112017-02-27 14:15:18 -07001824 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1825 Region opaqueRegion;
1826 Region dirtyRegion;
1827 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001828 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1830 const Transform& tr(displayDevice->getTransform());
1831 const Rect bounds(displayDevice->getBounds());
1832 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001833 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001836 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001837 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1838 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 Region drawRegion(tr.transform(
1840 layer->visibleNonTransparentRegion));
1841 drawRegion.andSelf(bounds);
1842 if (!drawRegion.isEmpty()) {
1843 layersSortedByZ.add(layer);
1844 } else {
1845 // Clear out the HWC layer if this layer was
1846 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001847 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001848 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001850 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001851 // WM changes displayDevice->layerStack upon sleep/awake.
1852 // Here we make sure we delete the HWC layers even if
1853 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001854 hwcLayerDestroyed = layer->destroyHwcLayer(
1855 displayDevice->getHwcDisplayId());
1856 }
1857
1858 // If a layer is not going to get a release fence because
1859 // it is invisible, but it is also going to release its
1860 // old buffer, add it to the list of layers needing
1861 // fences.
1862 if (hwcLayerDestroyed) {
1863 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1864 mLayersWithQueuedFrames.cend(), layer);
1865 if (found != mLayersWithQueuedFrames.cend()) {
1866 layersNeedingFences.add(layer);
1867 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 });
1870 }
1871 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001872 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 displayDevice->undefinedRegion.set(bounds);
1874 displayDevice->undefinedRegion.subtractSelf(
1875 tr.transform(opaqueRegion));
1876 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001877 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001880
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001881// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001883// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001885// The returned HDR data space is one of
1886// - Dataspace::UNKNOWN
1887// - Dataspace::BT2020_HLG
1888// - Dataspace::BT2020_PQ
1889Dataspace SurfaceFlinger::getBestDataspace(
1890 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1891 Dataspace bestDataSpace = Dataspace::SRGB;
1892 *outHdrDataSpace = Dataspace::UNKNOWN;
1893
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001895 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 case Dataspace::V0_SCRGB:
1897 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001898 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001899 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001900 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901 case Dataspace::BT2020_PQ:
1902 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001903 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001905 case Dataspace::BT2020_HLG:
1906 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001907 // When there's mixed PQ content and HLG content, we set the HDR
1908 // data space to be BT2020_PQ and convert HLG to PQ.
1909 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1910 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001911 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 break;
1913 default:
1914 break;
1915 }
Romain Guy54f154a2017-10-24 21:40:32 +01001916 }
1917
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001918 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001919}
1920
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001923 ColorMode* outMode, Dataspace* outDataSpace,
1924 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1926 *outMode = ColorMode::NATIVE;
1927 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001928 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001930 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001931
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001932 Dataspace hdrDataSpace;
1933 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1934
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001935 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001936 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001937 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001938 if (isHdr) {
1939 bestDataSpace = hdrDataSpace;
1940 }
1941
Chia-I Wu0d711262018-05-21 15:19:35 -07001942 RenderIntent intent;
1943 switch (mDisplayColorSetting) {
1944 case DisplayColorSetting::MANAGED:
1945 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001946 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001947 break;
1948 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001949 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001950 break;
1951 default: // vendor display color setting
1952 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1953 break;
1954 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001955
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001956 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001957}
1958
Mathias Agopiancd60f992012-08-16 16:28:27 -07001959void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 ATRACE_CALL();
1961 ALOGV("setUpHWComposer");
1962
Jesse Hall028dc8f2013-08-20 16:35:32 -07001963 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001964 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001965 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1966 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1967
1968 // If nothing has changed (!dirty), don't recompose.
1969 // If something changed, but we don't currently have any visible layers,
1970 // and didn't when we last did a composition, then skip it this time.
1971 // The second rule does two things:
1972 // - When all layers are removed from a display, we'll emit one black
1973 // frame, then nothing more until we get new layers.
1974 // - When a display is created with a private layer stack, we won't
1975 // emit any black frames until a layer is added to the layer stack.
1976 bool mustRecompose = dirty && !(empty && wasEmpty);
1977
1978 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1979 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1980 mustRecompose ? "doing" : "skipping",
1981 dirty ? "+" : "-",
1982 empty ? "+" : "-",
1983 wasEmpty ? "+" : "-");
1984
Dan Stoza71433162014-02-04 16:22:36 -08001985 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001986
1987 if (mustRecompose) {
1988 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1989 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001990 }
1991
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 // build the h/w work list
1993 if (CC_UNLIKELY(mGeometryInvalid)) {
1994 mGeometryInvalid = false;
1995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1996 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1997 const auto hwcId = displayDevice->getHwcDisplayId();
1998 if (hwcId >= 0) {
1999 const Vector<sp<Layer>>& currentLayers(
2000 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002001 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002002 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002004 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002007 }
2008 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002009
Robert Carrae060832016-11-28 10:51:00 -08002010 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002011 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002013 }
2014 }
2015 }
2016 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 }
Riley Andrews03414a12014-07-01 14:22:59 -07002018
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 // Set the per-frame data
2020 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2021 auto& displayDevice = mDisplays[displayId];
2022 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002023
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 if (hwcId < 0) {
2025 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002026 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002027 if (mDrawingState.colorMatrixChanged) {
2028 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2029 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002030 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2031 "display %zd: %d", displayId, result);
2032 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002034 if (layer->isHdrY410()) {
2035 layer->forceClientComposition(hwcId);
2036 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2037 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002038 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002039 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002040 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2041 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002042 !displayDevice->hasHLGSupport()) {
2043 layer->forceClientComposition(hwcId);
2044 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002045
chaviwc9232ed2017-11-14 15:31:15 -08002046 if (layer->getForceClientComposition(hwcId)) {
2047 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2048 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2049 continue;
2050 }
2051
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 layer->setPerFrameData(displayDevice);
2053 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002054
2055 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 ColorMode colorMode;
2057 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002058 RenderIntent renderIntent;
2059 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2060 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002061 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 }
2063
Chia-I Wu28f320b2018-05-03 11:02:56 -07002064 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002065
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002067 auto& displayDevice = mDisplays[displayId];
2068 if (!displayDevice->isDisplayOn()) {
2069 continue;
2070 }
2071
David Sodman105b7dc2017-11-04 20:28:14 -07002072 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2074 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002075 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002076}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002077
Mathias Agopiancd60f992012-08-16 16:28:27 -07002078void SurfaceFlinger::doComposition() {
2079 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 ALOGV("doComposition");
2081
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002082 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002083 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002084 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002085 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086 // transform the dirty region into this screen's coordinate space
2087 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002088
2089 // repaint the framebuffer (if needed)
2090 doDisplayComposition(hw, dirtyRegion);
2091
Mathias Agopiancd60f992012-08-16 16:28:27 -07002092 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002093 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002094 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002095 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002096 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097}
2098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099void SurfaceFlinger::postFramebuffer()
2100{
Mathias Agopian841cde52012-03-01 15:44:37 -08002101 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002103
Mathias Agopiana44b0412011-10-16 18:46:35 -07002104 const nsecs_t now = systemTime();
2105 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002106
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2108 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002109 if (!displayDevice->isDisplayOn()) {
2110 continue;
2111 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 const auto hwcId = displayDevice->getHwcDisplayId();
2113 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002114 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002115 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002116 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002117 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002118 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002119 // The layer buffer from the previous frame (if any) is released
2120 // by HWC only when the release fence from this frame (if any) is
2121 // signaled. Always get the release fence from HWC first.
2122 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002123 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002124
2125 // If the layer was client composited in the previous frame, we
2126 // need to merge with the previous client target acquire fence.
2127 // Since we do not track that, always merge with the current
2128 // client target acquire fence when it is available, even though
2129 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002131 releaseFence = Fence::merge("LayerRelease", releaseFence,
2132 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002133 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002134
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 layer->onLayerDisplayed(releaseFence);
2136 }
Chia-I Wu83806892017-11-16 10:50:20 -08002137
2138 // We've got a list of layers needing fences, that are disjoint with
2139 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2140 // supply them with the present fence.
2141 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002142 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002143 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2144 layer->onLayerDisplayed(presentFence);
2145 }
2146 }
2147
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002149 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002150 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002151 }
2152
Mathias Agopiana44b0412011-10-16 18:46:35 -07002153 mLastSwapBufferTime = systemTime() - now;
2154 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002155
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002156 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002157 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2158 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2159 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2160 logFrameStats();
2161 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163}
2164
Mathias Agopian87baae12012-07-31 12:38:26 -07002165void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166{
Mathias Agopian841cde52012-03-01 15:44:37 -08002167 ATRACE_CALL();
2168
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002169 // here we keep a copy of the drawing state (that is the state that's
2170 // going to be overwritten by handleTransactionLocked()) outside of
2171 // mStateLock so that the side-effects of the State assignment
2172 // don't happen with mStateLock held (which can cause deadlocks).
2173 State drawingState(mDrawingState);
2174
Mathias Agopianca4d3602011-05-19 15:38:14 -07002175 Mutex::Autolock _l(mStateLock);
2176 const nsecs_t now = systemTime();
2177 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178
Mathias Agopianca4d3602011-05-19 15:38:14 -07002179 // Here we're guaranteed that some transaction flags are set
2180 // so we can call handleTransactionLocked() unconditionally.
2181 // We call getTransactionFlags(), which will also clear the flags,
2182 // with mStateLock held to guarantee that mCurrentState won't change
2183 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002184
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002185 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002186 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002187 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002188
Mathias Agopianca4d3602011-05-19 15:38:14 -07002189 mLastTransactionTime = systemTime() - now;
2190 mDebugInTransaction = 0;
2191 invalidateHwcGeometry();
2192 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002193}
2194
Lloyd Pique715a2c12017-12-14 17:18:08 -08002195DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002196 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002197 // Figure out whether the event is for the primary display or an
2198 // external display by matching the Hwc display id against one for a
2199 // connected display. If we did not find a match, we then check what
2200 // displays are not already connected to determine the type. If we don't
2201 // have a connected primary display, we assume the new display is meant to
2202 // be the primary display, and then if we don't have an external display,
2203 // we assume it is that.
2204 const auto primaryDisplayId =
2205 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2206 const auto externalDisplayId =
2207 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2208 if (primaryDisplayId && primaryDisplayId == display) {
2209 return DisplayDevice::DISPLAY_PRIMARY;
2210 } else if (externalDisplayId && externalDisplayId == display) {
2211 return DisplayDevice::DISPLAY_EXTERNAL;
2212 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2213 return DisplayDevice::DISPLAY_PRIMARY;
2214 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2215 return DisplayDevice::DISPLAY_EXTERNAL;
2216 }
2217
2218 return DisplayDevice::DISPLAY_ID_INVALID;
2219}
2220
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2222 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002223 auto displayType = determineDisplayType(event.display, event.connection);
2224 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2225 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2226 continue;
2227 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002228
2229 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2230 ALOGE("External displays are not supported by the vr hardware composer.");
2231 continue;
2232 }
2233
Lloyd Pique715a2c12017-12-14 17:18:08 -08002234 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002235
2236 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002237 if (!mBuiltinDisplays[displayType].get()) {
2238 ALOGV("Creating built in display %d", displayType);
2239 mBuiltinDisplays[displayType] = new BBinder();
2240 // All non-virtual displays are currently considered secure.
2241 DisplayDeviceState info(displayType, true);
2242 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2243 "Built-in Screen" : "External Screen";
2244 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002245 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002246 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002247 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002248 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002249
Lloyd Piquefcd86612017-12-14 17:15:36 -08002250 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2251 if (idx >= 0) {
2252 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002253 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002254 mCurrentState.displays.removeItemsAt(idx);
2255 }
2256 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002257 }
2258
2259 processDisplayChangesLocked();
2260 }
2261
2262 mPendingHotplugEvents.clear();
2263}
2264
Lloyd Pique09594832018-01-22 17:48:03 -08002265sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2266 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2267 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002269 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002270
Lloyd Pique09594832018-01-22 17:48:03 -08002271 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002273 for (ColorMode colorMode : modes) {
2274 switch (colorMode) {
2275 case ColorMode::DISPLAY_P3:
2276 case ColorMode::ADOBE_RGB:
2277 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002279 break;
2280 default:
2281 break;
2282 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283
2284 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2285 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002286 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002287 }
2288 }
2289
Peiyong Lin62665892018-04-16 11:07:44 -07002290 HdrCapabilities hdrCapabilities;
2291 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002292
2293 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2294 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2295
2296 /*
2297 * Create our display's surface
2298 */
2299 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2300 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2301 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2302 renderSurface->setNativeWindow(nativeWindow.get());
2303 const int displayWidth = renderSurface->queryWidth();
2304 const int displayHeight = renderSurface->queryHeight();
2305
2306 // Make sure that composition can never be stalled by a virtual display
2307 // consumer that isn't processing buffers fast enough. We have to do this
2308 // in two places:
2309 // * Here, in case the display is composed entirely by HWC.
2310 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2311 // window's swap interval in eglMakeCurrent, so they'll override the
2312 // interval we set here.
2313 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2314 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2315 }
2316
2317 // virtual displays are always considered enabled
2318 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2319 : HWC_POWER_MODE_OFF;
2320
2321 sp<DisplayDevice> hw =
2322 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2323 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002324 hasWideColorGamut, hdrCapabilities,
2325 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002326 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002327
2328 if (maxFrameBufferAcquiredBuffers >= 3) {
2329 nativeWindowSurface->preallocateBuffers();
2330 }
2331
2332 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2334 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002335 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002336 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002337 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002338 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2339 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002340 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2341 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2342 }
Lloyd Pique09594832018-01-22 17:48:03 -08002343 hw->setLayerStack(state.layerStack);
2344 hw->setProjection(state.orientation, state.viewport, state.frame);
2345 hw->setDisplayName(state.displayName);
2346
2347 return hw;
2348}
2349
Lloyd Pique347200f2017-12-14 17:00:15 -08002350void SurfaceFlinger::processDisplayChangesLocked() {
2351 // here we take advantage of Vector's copy-on-write semantics to
2352 // improve performance by skipping the transaction entirely when
2353 // know that the lists are identical
2354 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2355 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2356 if (!curr.isIdenticalTo(draw)) {
2357 mVisibleRegionsDirty = true;
2358 const size_t cc = curr.size();
2359 size_t dc = draw.size();
2360
2361 // find the displays that were removed
2362 // (ie: in drawing state but not in current state)
2363 // also handle displays that changed
2364 // (ie: displays that are in both lists)
2365 for (size_t i = 0; i < dc;) {
2366 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2367 if (j < 0) {
2368 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002369 // Call makeCurrent() on the primary display so we can
2370 // be sure that nothing associated with this display
2371 // is current.
2372 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2373 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2374 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2375 if (hw != nullptr) hw->disconnect(getHwComposer());
2376 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2377 mEventThread->onHotplugReceived(draw[i].type, false);
2378 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 } else {
2380 // this display is in both lists. see if something changed.
2381 const DisplayDeviceState& state(curr[j]);
2382 const wp<IBinder>& display(curr.keyAt(j));
2383 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2384 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2385 if (state_binder != draw_binder) {
2386 // changing the surface is like destroying and
2387 // recreating the DisplayDevice, so we just remove it
2388 // from the drawing state, so that it get re-added
2389 // below.
2390 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2391 if (hw != nullptr) hw->disconnect(getHwComposer());
2392 mDisplays.removeItem(display);
2393 mDrawingState.displays.removeItemsAt(i);
2394 dc--;
2395 // at this point we must loop to the next item
2396 continue;
2397 }
2398
2399 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2400 if (disp != nullptr) {
2401 if (state.layerStack != draw[i].layerStack) {
2402 disp->setLayerStack(state.layerStack);
2403 }
2404 if ((state.orientation != draw[i].orientation) ||
2405 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2406 disp->setProjection(state.orientation, state.viewport, state.frame);
2407 }
2408 if (state.width != draw[i].width || state.height != draw[i].height) {
2409 disp->setDisplaySize(state.width, state.height);
2410 }
2411 }
2412 }
2413 ++i;
2414 }
2415
2416 // find displays that were added
2417 // (ie: in current state but not in drawing state)
2418 for (size_t i = 0; i < cc; i++) {
2419 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2420 const DisplayDeviceState& state(curr[i]);
2421
2422 sp<DisplaySurface> dispSurface;
2423 sp<IGraphicBufferProducer> producer;
2424 sp<IGraphicBufferProducer> bqProducer;
2425 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002426 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002427
2428 int32_t hwcId = -1;
2429 if (state.isVirtualDisplay()) {
2430 // Virtual displays without a surface are dormant:
2431 // they have external state (layer stack, projection,
2432 // etc.) but no internal state (i.e. a DisplayDevice).
2433 if (state.surface != nullptr) {
2434 // Allow VR composer to use virtual displays.
2435 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2436 int width = 0;
2437 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2438 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2439 int height = 0;
2440 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2441 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2442 int intFormat = 0;
2443 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2444 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002445 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002446
2447 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2448 }
2449
2450 // TODO: Plumb requested format back up to consumer
2451
2452 sp<VirtualDisplaySurface> vds =
2453 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2454 bqProducer, bqConsumer,
2455 state.displayName);
2456
2457 dispSurface = vds;
2458 producer = vds;
2459 }
2460 } else {
2461 ALOGE_IF(state.surface != nullptr,
2462 "adding a supported display, but rendering "
2463 "surface is provided (%p), ignoring it",
2464 state.surface.get());
2465
2466 hwcId = state.type;
2467 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2468 producer = bqProducer;
2469 }
2470
2471 const wp<IBinder>& display(curr.keyAt(i));
2472 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002473 mDisplays.add(display,
2474 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2475 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002476 if (!state.isVirtualDisplay()) {
2477 mEventThread->onHotplugReceived(state.type, true);
2478 }
2479 }
2480 }
2481 }
2482 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483
2484 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002485}
2486
Mathias Agopian87baae12012-07-31 12:38:26 -07002487void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002488{
Dan Stoza7dde5992015-05-22 09:51:44 -07002489 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002490 mCurrentState.traverseInZOrder([](Layer* layer) {
2491 layer->notifyAvailableFrames();
2492 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002493
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 /*
2495 * Traversal of the children
2496 * (perform the transaction for each of them if needed)
2497 */
2498
Mathias Agopian3559b072012-08-15 13:46:03 -07002499 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002500 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002502 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503
2504 const uint32_t flags = layer->doTransaction(0);
2505 if (flags & Layer::eVisibleRegion)
2506 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002507 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 }
2509
2510 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002511 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 */
2513
Mathias Agopiane57f2922012-08-09 16:29:12 -07002514 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002516 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002517 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002519 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002520 // The transform hint might have changed for some layers
2521 // (either because a display has changed, or because a layer
2522 // as changed).
2523 //
2524 // Walk through all the layers in currentLayers,
2525 // and update their transform hint.
2526 //
2527 // If a layer is visible only on a single display, then that
2528 // display is used to calculate the hint, otherwise we use the
2529 // default display.
2530 //
2531 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2532 // the hint is set before we acquire a buffer from the surface texture.
2533 //
2534 // NOTE: layer transactions have taken place already, so we use their
2535 // drawing state. However, SurfaceFlinger's own transaction has not
2536 // happened yet, so we must use the current state layer list
2537 // (soon to become the drawing state list).
2538 //
2539 sp<const DisplayDevice> disp;
2540 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002541 bool first = true;
2542 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002543 // NOTE: we rely on the fact that layers are sorted by
2544 // layerStack first (so we don't have to traverse the list
2545 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002546 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002547 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002548 currentlayerStack = layerStack;
2549 // figure out if this layerstack is mirrored
2550 // (more than one display) if so, pick the default display,
2551 // if not, pick the only display it's on.
2552 disp.clear();
2553 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2554 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002555 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002556 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002557 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002558 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002559 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002560 break;
2561 }
2562 }
2563 }
2564 }
Chet Haase91d25932013-04-11 15:24:55 -07002565
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002566 if (disp == nullptr) {
2567 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2568 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002569
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002570 // could be null when this layer is using a layerStack
2571 // that is not visible on any display. Also can occur at
2572 // screen off/on times.
2573 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002574 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002575
2576 // disp can be null if there is no display available at all to get
2577 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002578 if (disp != nullptr) {
2579 layer->updateTransformHint(disp);
2580 }
Robert Carr2047fae2016-11-28 14:09:09 -08002581
2582 first = false;
2583 });
Mathias Agopian84300952012-11-21 16:02:13 -08002584 }
2585
2586
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 /*
2588 * Perform our own transaction if needed
2589 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590
2591 if (mLayersAdded) {
2592 mLayersAdded = false;
2593 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 mVisibleRegionsDirty = true;
2595 }
2596
2597 // some layers might have been removed, so
2598 // we need to update the regions they're exposing.
2599 if (mLayersRemoved) {
2600 mLayersRemoved = false;
2601 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002602 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002603 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002604 // this layer is not visible anymore
2605 // TODO: we could traverse the tree from front to back and
2606 // compute the actual visible region
2607 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 Region visibleReg;
2609 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002610 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002611 }
Robert Carr2047fae2016-11-28 14:09:09 -08002612 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 }
2614
2615 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002616
2617 updateCursorAsync();
2618}
2619
2620void SurfaceFlinger::updateCursorAsync()
2621{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2623 auto& displayDevice = mDisplays[displayId];
2624 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002625 continue;
2626 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627
2628 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2629 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002630 }
2631 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002632}
2633
2634void SurfaceFlinger::commitTransaction()
2635{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002636 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 for (const auto& l : mLayersPendingRemoval) {
2639 recordBufferingStats(l->getName().string(),
2640 l->getOccupancyHistory(true));
2641 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 }
2643 mLayersPendingRemoval.clear();
2644 }
2645
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002646 // If this transaction is part of a window animation then the next frame
2647 // we composite should be considered an animation as well.
2648 mAnimCompositionPending = mAnimTransactionPending;
2649
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002651 // clear the "changed" flags in current state
2652 mCurrentState.colorMatrixChanged = false;
2653
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 mDrawingState.traverseInZOrder([](Layer* layer) {
2655 layer->commitChildList();
2656 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002657 mTransactionPending = false;
2658 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002659 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660}
2661
Chia-I Wuab0c3192017-08-01 11:29:00 -07002662void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002663 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664{
Mathias Agopian841cde52012-03-01 15:44:37 -08002665 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002667
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 Region aboveOpaqueLayers;
2669 Region aboveCoveredLayers;
2670 Region dirty;
2671
Mathias Agopian87baae12012-07-31 12:38:26 -07002672 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673
Robert Carr2047fae2016-11-28 14:09:09 -08002674 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002676 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677
Jesse Hall01e29052013-02-19 16:13:35 -08002678 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002679 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002680 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002681
Mathias Agopianab028732010-03-16 16:41:46 -07002682 /*
2683 * opaqueRegion: area of a surface that is fully opaque.
2684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002686
2687 /*
2688 * visibleRegion: area of a surface that is visible on screen
2689 * and not fully transparent. This is essentially the layer's
2690 * footprint minus the opaque regions above it.
2691 * Areas covered by a translucent surface are considered visible.
2692 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002694
2695 /*
2696 * coveredRegion: area of a surface that is covered by all
2697 * visible regions above it (which includes the translucent areas).
2698 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002700
Jesse Halla8026d22012-09-25 13:25:04 -07002701 /*
2702 * transparentRegion: area of a surface that is hinted to be completely
2703 * transparent. This is only used to tell when the layer has no visible
2704 * non-transparent regions and can be removed from the layer list. It
2705 * does not affect the visibleRegion of this layer or any layers
2706 * beneath it. The hint may not be correct if apps don't respect the
2707 * SurfaceView restrictions (which, sadly, some don't).
2708 */
2709 Region transparentRegion;
2710
Mathias Agopianab028732010-03-16 16:41:46 -07002711
2712 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002713 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002714 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002717 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002718 if (!visibleRegion.isEmpty()) {
2719 // Remove the transparent area from the visible region
2720 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002721 if (tr.preserveRects()) {
2722 // transform the transparent region
2723 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002725 // transformation too complex, can't do the
2726 // transparent region optimization.
2727 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 }
Mathias Agopianab028732010-03-16 16:41:46 -07002729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730
Mathias Agopianab028732010-03-16 16:41:46 -07002731 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002733 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002734 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2735 // the opaque region is the layer's footprint
2736 opaqueRegion = visibleRegion;
2737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 }
2739 }
2740
Robert Carre5f4f692018-01-12 13:12:28 -08002741 if (visibleRegion.isEmpty()) {
2742 layer->clearVisibilityRegions();
2743 return;
2744 }
2745
Mathias Agopianab028732010-03-16 16:41:46 -07002746 // Clip the covered region to the visible region
2747 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2748
2749 // Update aboveCoveredLayers for next (lower) layer
2750 aboveCoveredLayers.orSelf(visibleRegion);
2751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 // subtract the opaque region covered by the layers above us
2753 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754
2755 // compute this layer's dirty region
2756 if (layer->contentDirty) {
2757 // we need to invalidate the whole region
2758 dirty = visibleRegion;
2759 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002760 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 layer->contentDirty = false;
2762 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002763 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002764 * the exposed region consists of two components:
2765 * 1) what's VISIBLE now and was COVERED before
2766 * 2) what's EXPOSED now less what was EXPOSED before
2767 *
2768 * note that (1) is conservative, we start with the whole
2769 * visible region but only keep what used to be covered by
2770 * something -- which mean it may have been exposed.
2771 *
2772 * (2) handles areas that were not covered by anything but got
2773 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002774 */
Mathias Agopianab028732010-03-16 16:41:46 -07002775 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002776 const Region oldVisibleRegion = layer->visibleRegion;
2777 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002778 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2779 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 }
2781 dirty.subtractSelf(aboveOpaqueLayers);
2782
2783 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002784 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785
Mathias Agopianab028732010-03-16 16:41:46 -07002786 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002788
Jesse Halla8026d22012-09-25 13:25:04 -07002789 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 layer->setVisibleRegion(visibleRegion);
2791 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002792 layer->setVisibleNonTransparentRegion(
2793 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002794 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795
Mathias Agopian87baae12012-07-31 12:38:26 -07002796 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797}
2798
Chia-I Wuab0c3192017-08-01 11:29:00 -07002799void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002800 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002801 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002802 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002803 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002804 }
2805 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002806}
2807
Dan Stoza6b9454d2014-11-07 16:00:59 -08002808bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 ALOGV("handlePageFlip");
2811
Brian Andersond6927fb2016-07-23 23:37:30 -07002812 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813
Mathias Agopian4fec8732012-06-29 14:12:52 -07002814 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002816 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002817
2818 // Store the set of layers that need updates. This set must not change as
2819 // buffers are being latched, as this could result in a deadlock.
2820 // Example: Two producers share the same command stream and:
2821 // 1.) Layer 0 is latched
2822 // 2.) Layer 0 gets a new frame
2823 // 2.) Layer 1 gets a new frame
2824 // 3.) Layer 1 is latched.
2825 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2826 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002827 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002828 if (layer->hasQueuedFrame()) {
2829 frameQueued = true;
2830 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002832 } else {
2833 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002834 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002835 } else {
2836 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002837 }
Robert Carr2047fae2016-11-28 14:09:09 -08002838 });
2839
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002841 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002842 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002843 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002844 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002845 newDataLatched = true;
2846 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002848
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002849 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002850
2851 // If we will need to wake up at some time in the future to deal with a
2852 // queued frame that shouldn't be displayed during this vsync period, wake
2853 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002854 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855 signalLayerUpdate();
2856 }
2857
2858 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002859 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860}
2861
Mathias Agopianad456f92011-01-13 17:53:01 -08002862void SurfaceFlinger::invalidateHwcGeometry()
2863{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002865}
2866
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002867
Fabien Sanglard830b8472016-11-30 16:35:58 -08002868void SurfaceFlinger::doDisplayComposition(
2869 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002870 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871{
Dan Stoza71433162014-02-04 16:22:36 -08002872 // We only need to actually compose the display if:
2873 // 1) It is being handled by hardware composer, which may need this to
2874 // keep its virtual display state machine in sync, or
2875 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002876 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002877 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002879 return;
2880 }
2881
Dan Stoza9e56aa02015-11-02 13:00:03 -08002882 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002883 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002884
2885 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002886 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887}
2888
Chia-I Wub02087d2017-11-09 10:19:54 -08002889bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002890{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002891 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002892
Chia-I Wub02087d2017-11-09 10:19:54 -08002893 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002894 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002895 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002896 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002897 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002898
Chia-I Wu8e50e692018-05-04 10:12:37 -07002899 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002900 bool needsLegacyColorMatrix = false;
2901 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002902
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 if (hasClientComposition) {
2904 ALOGV("hasClientComposition");
2905
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002906 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002907 if (displayDevice->hasWideColorGamut()) {
2908 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002909 }
2910 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002911 getBE().mRenderEngine->setDisplayMaxLuminance(
2912 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002913
Chia-I Wu8e50e692018-05-04 10:12:37 -07002914 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2915 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2916 HWC2::Capability::SkipClientColorTransform);
2917
2918 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2919 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002920 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002921 }
2922
Chia-I Wubbb44462018-05-21 15:33:27 -07002923 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002924 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002925 outputDataspace != Dataspace::UNKNOWN &&
2926 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002927
Chia-I Wu7f402902017-11-09 12:51:10 -08002928 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002929 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002931 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002932
2933 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002934 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002935 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2936 }
2937 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002938 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002939
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002940 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002942 // when using overlays, we assume a fully transparent framebuffer
2943 // NOTE: we could reduce how much we need to clear, for instance
2944 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002945 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002946 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002947 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002948 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002949 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002950 // we're left with the letterbox region
2951 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002953
2954 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002956
Mathias Agopianb9494d52012-04-18 02:28:45 -07002957 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002958 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002959 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002961 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002962 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002965 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002966 // scissor on the main display. It should never be needed
2967 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 const Rect& bounds(displayDevice->getBounds());
2969 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002970 if (scissor != bounds) {
2971 // scissor doesn't match the screen's dimensions, so we
2972 // need to clear everything outside of it and enable
2973 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002974
Mathias Agopianf45c5102012-10-24 16:29:17 -07002975 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002977 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002978 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002979 }
2980 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002981 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002982
Mathias Agopian85d751c2012-08-29 16:59:24 -07002983 /*
2984 * and then, render the layers targeted at the framebuffer
2985 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002986
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 ALOGV("Rendering client layers");
2988 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002989 bool firstLayer = true;
2990 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2991 const Region clip(bounds.intersect(
2992 displayTransform.transform(layer->visibleRegion)));
2993 ALOGV("Layer: %s", layer->getName().string());
2994 ALOGV(" Composition type: %s",
2995 to_string(layer->getCompositionType(hwcId)).c_str());
2996 if (!clip.isEmpty()) {
2997 switch (layer->getCompositionType(hwcId)) {
2998 case HWC2::Composition::Cursor:
2999 case HWC2::Composition::Device:
3000 case HWC2::Composition::Sideband:
3001 case HWC2::Composition::SolidColor: {
3002 const Layer::State& state(layer->getDrawingState());
3003 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3004 layer->isOpaque(state) && (state.color.a == 1.0f)
3005 && hasClientComposition) {
3006 // never clear the very first layer since we're
3007 // guaranteed the FB is already cleared
3008 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003009 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003010 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003011 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003012 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003014 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3015 if (!legacyColorMatrixApplied) {
3016 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3017 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003018 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003019 } else if (legacyColorMatrixApplied) {
3020 getRenderEngine().setSaturationMatrix(mat4());
3021 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003022 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003023
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003024 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003025 break;
3026 }
3027 default:
3028 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003029 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003030 } else {
3031 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003032 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003033 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003034 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003035
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003036 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003037 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003038 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003039 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3040 getRenderEngine().setSaturationMatrix(mat4());
3041 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003042
Mathias Agopianf45c5102012-10-24 16:29:17 -07003043 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003044 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003045 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046}
3047
Fabien Sanglard830b8472016-11-30 16:35:58 -08003048void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3049 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003050 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003051 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052}
3053
Dan Stoza7d89d062015-04-30 13:29:25 -07003054status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003055 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003056 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 const sp<Layer>& lbc,
3058 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003059{
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 // add this layer to the current state list
3061 {
3062 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003064 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3065 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003066 return NO_MEMORY;
3067 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068 if (parent == nullptr) {
3069 mCurrentState.layersSortedByZ.add(lbc);
3070 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003071 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003072 ALOGE("addClientLayer called with a removed parent");
3073 return NAME_NOT_FOUND;
3074 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003075 parent->addChild(lbc);
3076 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003077
Yiwei Zhang243b3782018-05-15 17:40:04 -07003078 if (gbc != nullptr) {
3079 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3080 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3081 mMaxGraphicBufferProducerListSize,
3082 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3083 mGraphicBufferProducerList.size(),
3084 mMaxGraphicBufferProducerListSize, mNumLayers);
3085 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mLayersAdded = true;
3087 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003088 }
3089
Mathias Agopian96f08192010-06-02 23:28:45 -07003090 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003091 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003092
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003094}
3095
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003097 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003098 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3099}
Robert Carr7f9b8992017-03-10 11:08:39 -08003100
chaviwca27f252018-02-06 16:46:39 -08003101status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3102 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003103 if (layer->isPendingRemoval()) {
3104 return NO_ERROR;
3105 }
3106
Robert Carr1f0a16a2016-10-24 16:27:39 -07003107 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003108 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003109 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003110 if (topLevelOnly) {
3111 return NO_ERROR;
3112 }
3113
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114 sp<Layer> ancestor = p;
3115 while (ancestor->getParent() != nullptr) {
3116 ancestor = ancestor->getParent();
3117 }
3118 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3119 ALOGE("removeLayer called with a layer whose parent has been removed");
3120 return NAME_NOT_FOUND;
3121 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003122
3123 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003124 } else {
3125 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003126 }
3127
Robert Carr136e2f62017-02-08 17:54:29 -08003128 // As a matter of normal operation, the LayerCleaner will produce a second
3129 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3130 // so we will succeed in promoting it, but it's already been removed
3131 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3132 // otherwise something has gone wrong and we are leaking the layer.
3133 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3135 layer->getName().string(),
3136 (p != nullptr) ? p->getName().string() : "no-parent");
3137 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003138 } else if (index < 0) {
3139 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003140 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141
Chia-I Wuc6657022017-08-15 11:18:17 -07003142 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 mLayersPendingRemoval.add(layer);
3144 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003145 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003146 setTransactionFlags(eTransactionNeeded);
3147 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148}
3149
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003150uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003151 return android_atomic_release_load(&mTransactionFlags);
3152}
3153
Mathias Agopian3f844832013-08-07 21:24:32 -07003154uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3156}
3157
Mathias Agopian3f844832013-08-07 21:24:32 -07003158uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003159 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3160}
3161
3162uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3163 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003165 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003167 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 return old;
3170}
3171
chaviwca27f252018-02-06 16:46:39 -08003172bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3173 for (const ComposerState& state : states) {
3174 // Here we need to check that the interface we're given is indeed
3175 // one of our own. A malicious client could give us a nullptr
3176 // IInterface, or one of its own or even one of our own but a
3177 // different type. All these situations would cause us to crash.
3178 if (state.client == nullptr) {
3179 return true;
3180 }
3181
3182 sp<IBinder> binder = IInterface::asBinder(state.client);
3183 if (binder == nullptr) {
3184 return true;
3185 }
3186
3187 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3188 return true;
3189 }
3190 }
3191 return false;
3192}
3193
Mathias Agopian8b33f032012-07-24 20:43:54 -07003194void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003195 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003196 const Vector<DisplayState>& displays,
3197 uint32_t flags)
3198{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003199 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003200 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003201 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003202
chaviwca27f252018-02-06 16:46:39 -08003203 if (containsAnyInvalidClientState(states)) {
3204 return;
3205 }
3206
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 if (flags & eAnimation) {
3208 // For window updates that are part of an animation we must wait for
3209 // previous animation "frames" to be handled.
3210 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003214 // caller after a few seconds.
3215 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3216 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003217 mAnimTransactionPending = false;
3218 break;
3219 }
3220 }
3221 }
3222
chaviwca27f252018-02-06 16:46:39 -08003223 for (const DisplayState& display : displays) {
3224 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003225 }
3226
chaviwca27f252018-02-06 16:46:39 -08003227 for (const ComposerState& state : states) {
3228 transactionFlags |= setClientStateLocked(state);
3229 }
3230
3231 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3232 // as destroyed should only occur after setting all other states. This is to allow for a
3233 // child re-parent to happen before marking its original parent as destroyed (which would
3234 // then mark the child as destroyed).
3235 for (const ComposerState& state : states) {
3236 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003237 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003238
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003239 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3240 // anyway. This can be used as a flush mechanism for previous async transactions.
3241 // Empty animation transaction can be used to simulate back-pressure, so also force a
3242 // transaction for empty animation transactions.
3243 if (transactionFlags == 0 &&
3244 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003245 transactionFlags = eTransactionNeeded;
3246 }
3247
Mathias Agopian386aa982011-11-07 21:58:03 -08003248 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003249 if (mInterceptor->isEnabled()) {
3250 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003251 }
Irvel468051e2016-06-13 16:44:44 -07003252
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003254 const auto start = (flags & eEarlyWakeup)
3255 ? VSyncModulator::TransactionStart::EARLY
3256 : VSyncModulator::TransactionStart::NORMAL;
3257 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003258
3259 // if this is a synchronous transaction, wait for it to take effect
3260 // before returning.
3261 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003263 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003264 if (flags & eAnimation) {
3265 mAnimTransactionPending = true;
3266 }
3267 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3269 if (CC_UNLIKELY(err != NO_ERROR)) {
3270 // just in case something goes wrong in SF, return to the
3271 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003272 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3273 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003274 break;
3275 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
3278}
3279
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3281{
Jesse Hall9a143922012-10-04 16:29:19 -07003282 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3283 if (dpyIdx < 0)
3284 return 0;
3285
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003287 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003288 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 const uint32_t what = s.what;
3290 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003291 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 disp.surface = s.surface;
3293 flags |= eDisplayTransactionNeeded;
3294 }
3295 }
3296 if (what & DisplayState::eLayerStackChanged) {
3297 if (disp.layerStack != s.layerStack) {
3298 disp.layerStack = s.layerStack;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003302 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003303 if (disp.orientation != s.orientation) {
3304 disp.orientation = s.orientation;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 if (disp.frame != s.frame) {
3308 disp.frame = s.frame;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 if (disp.viewport != s.viewport) {
3312 disp.viewport = s.viewport;
3313 flags |= eDisplayTransactionNeeded;
3314 }
3315 }
Michael Lentine47e45402014-07-18 15:34:25 -07003316 if (what & DisplayState::eDisplaySizeChanged) {
3317 if (disp.width != s.width) {
3318 disp.width = s.width;
3319 flags |= eDisplayTransactionNeeded;
3320 }
3321 if (disp.height != s.height) {
3322 disp.height = s.height;
3323 flags |= eDisplayTransactionNeeded;
3324 }
3325 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003326 }
3327 return flags;
3328}
3329
Robert Carrd4ae7f32018-06-07 16:10:57 -07003330bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3331 IPCThreadState* ipc = IPCThreadState::self();
3332 const int pid = ipc->getCallingPid();
3333 const int uid = ipc->getCallingUid();
3334
3335 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3336 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3337 return false;
3338 }
3339 return true;
3340}
3341
chaviwca27f252018-02-06 16:46:39 -08003342uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3343 const layer_state_t& s = composerState.state;
3344 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3345
Mathias Agopian13127d82013-03-05 17:47:11 -08003346 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003347 if (layer == nullptr) {
3348 return 0;
3349 }
3350
3351 if (layer->isPendingRemoval()) {
3352 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3353 return 0;
3354 }
3355
3356 uint32_t flags = 0;
3357
3358 const uint32_t what = s.what;
3359 bool geometryAppliesWithResize =
3360 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003361
3362 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3363 // pending state will also be deferred.
3364 if (what & layer_state_t::eDeferTransaction) {
3365 layer->pushPendingState();
3366 }
3367
chaviw8b3871a2017-11-01 17:41:01 -07003368 if (what & layer_state_t::ePositionChanged) {
3369 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3370 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 }
3373 if (what & layer_state_t::eLayerChanged) {
3374 // NOTE: index needs to be calculated before we update the state
3375 const auto& p = layer->getParent();
3376 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003377 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003378 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003379 mCurrentState.layersSortedByZ.removeAt(idx);
3380 mCurrentState.layersSortedByZ.add(layer);
3381 // we need traversal (state changed)
3382 // AND transaction (list changed)
3383 flags |= eTransactionNeeded|eTraversalNeeded;
3384 }
chaviw8b3871a2017-11-01 17:41:01 -07003385 } else {
3386 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003387 flags |= eTransactionNeeded|eTraversalNeeded;
3388 }
3389 }
chaviw8b3871a2017-11-01 17:41:01 -07003390 }
3391 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003392 // NOTE: index needs to be calculated before we update the state
3393 const auto& p = layer->getParent();
3394 if (p == nullptr) {
3395 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3396 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3397 mCurrentState.layersSortedByZ.removeAt(idx);
3398 mCurrentState.layersSortedByZ.add(layer);
3399 // we need traversal (state changed)
3400 // AND transaction (list changed)
3401 flags |= eTransactionNeeded|eTraversalNeeded;
3402 }
3403 } else {
3404 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3405 flags |= eTransactionNeeded|eTraversalNeeded;
3406 }
chaviw8b3871a2017-11-01 17:41:01 -07003407 }
3408 }
3409 if (what & layer_state_t::eSizeChanged) {
3410 if (layer->setSize(s.w, s.h)) {
3411 flags |= eTraversalNeeded;
3412 }
3413 }
3414 if (what & layer_state_t::eAlphaChanged) {
3415 if (layer->setAlpha(s.alpha))
3416 flags |= eTraversalNeeded;
3417 }
3418 if (what & layer_state_t::eColorChanged) {
3419 if (layer->setColor(s.color))
3420 flags |= eTraversalNeeded;
3421 }
3422 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003423 // TODO: b/109894387
3424 //
3425 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3426 // rotation. To see the problem observe that if we have a square parent, and a child
3427 // of the same size, then we rotate the child 45 degrees around it's center, the child
3428 // must now be cropped to a non rectangular 8 sided region.
3429 //
3430 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3431 // private API, and the WindowManager only uses rotation in one case, which is on a top
3432 // level layer in which cropping is not an issue.
3433 //
3434 // However given that abuse of rotation matrices could lead to surfaces extending outside
3435 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3436 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3437 // transformations.
3438 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003439 flags |= eTraversalNeeded;
3440 }
3441 if (what & layer_state_t::eTransparentRegionChanged) {
3442 if (layer->setTransparentRegionHint(s.transparentRegion))
3443 flags |= eTraversalNeeded;
3444 }
3445 if (what & layer_state_t::eFlagsChanged) {
3446 if (layer->setFlags(s.flags, s.mask))
3447 flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eCropChanged) {
3450 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3451 flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eFinalCropChanged) {
3454 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3455 flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eLayerStackChanged) {
3458 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3459 // We only allow setting layer stacks for top level layers,
3460 // everything else inherits layer stack from its parent.
3461 if (layer->hasParent()) {
3462 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3463 layer->getName().string());
3464 } else if (idx < 0) {
3465 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3466 "that also does not appear in the top level layer list. Something"
3467 " has gone wrong.", layer->getName().string());
3468 } else if (layer->setLayerStack(s.layerStack)) {
3469 mCurrentState.layersSortedByZ.removeAt(idx);
3470 mCurrentState.layersSortedByZ.add(layer);
3471 // we need traversal (state changed)
3472 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003473 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003474 }
3475 }
3476 if (what & layer_state_t::eDeferTransaction) {
3477 if (s.barrierHandle != nullptr) {
3478 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3479 } else if (s.barrierGbp != nullptr) {
3480 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3481 if (authenticateSurfaceTextureLocked(gbp)) {
3482 const auto& otherLayer =
3483 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3484 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3485 } else {
3486 ALOGE("Attempt to defer transaction to to an"
3487 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003488 }
3489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 // We don't trigger a traversal here because if no other state is
3491 // changed, we don't want this to cause any more work
3492 }
3493 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003494 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003495 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003496 if (!hadParent) {
3497 mCurrentState.layersSortedByZ.remove(layer);
3498 }
chaviw8b3871a2017-11-01 17:41:01 -07003499 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003500 }
chaviw8b3871a2017-11-01 17:41:01 -07003501 }
3502 if (what & layer_state_t::eReparentChildren) {
3503 if (layer->reparentChildren(s.reparentHandle)) {
3504 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003505 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003506 }
chaviw8b3871a2017-11-01 17:41:01 -07003507 if (what & layer_state_t::eDetachChildren) {
3508 layer->detachChildren();
3509 }
3510 if (what & layer_state_t::eOverrideScalingModeChanged) {
3511 layer->setOverrideScalingMode(s.overrideScalingMode);
3512 // We don't trigger a traversal here because if no other state is
3513 // changed, we don't want this to cause any more work
3514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003515 return flags;
3516}
3517
chaviwca27f252018-02-06 16:46:39 -08003518void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3519 const layer_state_t& state = composerState.state;
3520 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3521
3522 sp<Layer> layer(client->getLayerUser(state.surface));
3523 if (layer == nullptr) {
3524 return;
3525 }
3526
3527 if (layer->isPendingRemoval()) {
3528 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3529 return;
3530 }
3531
3532 if (state.what & layer_state_t::eDestroySurface) {
3533 removeLayerLocked(mStateLock, layer);
3534 }
3535}
3536
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003538 const String8& name,
3539 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003540 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003541 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003542 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003544 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003545 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003546 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003547 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003548 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003549
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003550 status_t result = NO_ERROR;
3551
3552 sp<Layer> layer;
3553
Cody Northropbc755282017-03-31 12:00:08 -06003554 String8 uniqueName = getUniqueLayerName(name);
3555
Mathias Agopian3165cc22012-08-08 19:42:09 -07003556 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3557 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003558 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003559 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003560 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003561
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 break;
chaviw13fdc492017-06-27 12:40:18 -07003563 case ISurfaceComposerClient::eFXSurfaceColor:
3564 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003565 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003566 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003567 break;
3568 default:
3569 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 break;
3571 }
3572
Dan Stoza7d89d062015-04-30 13:29:25 -07003573 if (result != NO_ERROR) {
3574 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003576
Chia-I Wuab0c3192017-08-01 11:29:00 -07003577 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3578 // TODO b/64227542
3579 if (windowType == 441731) {
3580 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3581 layer->setPrimaryDisplayOnly();
3582 }
3583
Albert Chaulk479c60c2017-01-27 14:21:34 -05003584 layer->setInfo(windowType, ownerUid);
3585
Robert Carr1f0a16a2016-10-24 16:27:39 -07003586 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003587 if (result != NO_ERROR) {
3588 return result;
3589 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003590 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003591
3592 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594}
3595
Cody Northropbc755282017-03-31 12:00:08 -06003596String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3597{
3598 bool matchFound = true;
3599 uint32_t dupeCounter = 0;
3600
3601 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3602 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3603
3604 // Loop over layers until we're sure there is no matching name
3605 while (matchFound) {
3606 matchFound = false;
3607 mDrawingState.traverseInZOrder([&](Layer* layer) {
3608 if (layer->getName() == uniqueName) {
3609 matchFound = true;
3610 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3611 }
3612 });
3613 }
3614
3615 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3616
3617 return uniqueName;
3618}
3619
David Sodman0c69cad2017-08-21 12:12:51 -07003620status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3622 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623{
3624 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003625 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626 case PIXEL_FORMAT_TRANSPARENT:
3627 case PIXEL_FORMAT_TRANSLUCENT:
3628 format = PIXEL_FORMAT_RGBA_8888;
3629 break;
3630 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003631 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632 break;
3633 }
3634
David Sodman0c69cad2017-08-21 12:12:51 -07003635 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3636 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003637 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003638 *handle = layer->getHandle();
3639 *gbp = layer->getProducer();
3640 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003642
David Sodman0c69cad2017-08-21 12:12:51 -07003643 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645}
3646
chaviw13fdc492017-06-27 12:40:18 -07003647status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003649 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650{
chaviw13fdc492017-06-27 12:40:18 -07003651 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003653 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003654}
3655
Mathias Agopianac9fa422013-02-11 16:40:36 -08003656status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657{
Robert Carr9524cb32017-02-13 11:32:32 -08003658 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003659 status_t err = NO_ERROR;
3660 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003661 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003662 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003663 err = removeLayer(l);
3664 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3665 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003666 }
3667 return err;
3668}
3669
Mathias Agopian13127d82013-03-05 17:47:11 -08003670status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003671{
Mathias Agopian67106042013-03-14 19:18:13 -07003672 // called by ~LayerCleaner() when all references to the IBinder (handle)
3673 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003674 sp<Layer> l = layer.promote();
3675 if (l == nullptr) {
3676 // The layer has already been removed, carry on
3677 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003678 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003679 // If we have a parent, then we can continue to live as long as it does.
3680 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681}
3682
Mathias Agopianb60314a2012-04-10 22:09:54 -07003683// ---------------------------------------------------------------------------
3684
Andy McFadden13a082e2012-08-24 10:16:42 -07003685void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003686 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003687 Vector<ComposerState> state;
3688 Vector<DisplayState> displays;
3689 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003690 d.what = DisplayState::eDisplayProjectionChanged |
3691 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003692 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003693 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003694 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003695 d.frame.makeInvalid();
3696 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003697 d.width = 0;
3698 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003699 displays.add(d);
3700 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003701 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3702 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003703
David Sodman105b7dc2017-11-04 20:28:14 -07003704 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003705 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003706 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003707
Brian Andersond0010582017-03-07 13:20:31 -08003708 // Use phase of 0 since phase is not known.
3709 // Use latency of 0, which will snap to the ideal latency.
3710 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003711}
3712
3713void SurfaceFlinger::initializeDisplays() {
3714 class MessageScreenInitialized : public MessageBase {
3715 SurfaceFlinger* flinger;
3716 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003717 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003718 virtual bool handler() {
3719 flinger->onInitializeDisplays();
3720 return true;
3721 }
3722 };
3723 sp<MessageBase> msg = new MessageScreenInitialized(this);
3724 postMessageAsync(msg); // we may be called from main thread, use async message
3725}
3726
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003727void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003728 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3730 this);
3731 int32_t type = hw->getDisplayType();
3732 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003735 return;
3736 }
3737
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 hw->setPowerMode(mode);
3739 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3740 ALOGW("Trying to set power mode for virtual display");
3741 return;
3742 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003743
Lloyd Pique4d234852018-01-22 17:21:36 -08003744 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003745 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003746 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3747 if (idx < 0) {
3748 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3749 return;
3750 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003751 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003752 }
3753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003755 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003757 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3758 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 // FIXME: eventthread only knows about the main display right now
3760 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003761 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003762 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003765 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003766 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003767
3768 struct sched_param param = {0};
3769 param.sched_priority = 1;
3770 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3771 ALOGW("Couldn't set SCHED_FIFO on display on");
3772 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003774 // Turn off the display
3775 struct sched_param param = {0};
3776 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3777 ALOGW("Couldn't set SCHED_OTHER on display off");
3778 }
3779
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003780 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3781 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003782 disableHardwareVsync(true); // also cancels any in-progress resync
3783
Mathias Agopiancde87a32012-09-13 14:09:01 -07003784 // FIXME: eventthread only knows about the main display right now
3785 mEventThread->onScreenReleased();
3786 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 getHwComposer().setPowerMode(type, mode);
3789 mVisibleRegionsDirty = true;
3790 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003791 } else if (mode == HWC_POWER_MODE_DOZE ||
3792 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003793 // Update display while dozing
3794 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003795 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3796 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003797 // FIXME: eventthread only knows about the main display right now
3798 mEventThread->onScreenAcquired();
3799 resyncToHardwareVsync(true);
3800 }
3801 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3802 // Leave display going to doze
3803 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3804 disableHardwareVsync(true); // also cancels any in-progress resync
3805 // FIXME: eventthread only knows about the main display right now
3806 mEventThread->onScreenReleased();
3807 }
3808 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003809 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003810 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003811 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003812 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003813 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003814}
3815
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003816void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3817 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003818 SurfaceFlinger& mFlinger;
3819 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003820 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003821 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003822 MessageSetPowerMode(SurfaceFlinger& flinger,
3823 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3824 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003825 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003826 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003827 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003828 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003829 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003830 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003831 ALOGW("Attempt to set power mode = %d for virtual display",
3832 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003833 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003834 mFlinger.setPowerModeInternal(
3835 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003836 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003837 return true;
3838 }
3839 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003840 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003841 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003842}
3843
3844// ---------------------------------------------------------------------------
3845
Lloyd Pique755e3192018-01-31 16:46:15 -08003846status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3847 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003849
Mathias Agopianbd115332013-04-18 16:41:04 -07003850 IPCThreadState* ipc = IPCThreadState::self();
3851 const int pid = ipc->getCallingPid();
3852 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003853
Mathias Agopianbd115332013-04-18 16:41:04 -07003854 if ((uid != AID_SHELL) &&
3855 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003856 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003857 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003859 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003860 // (this would indicate SF is stuck, but we want to be able to
3861 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003862 status_t err = mStateLock.timedLock(s2ns(1));
3863 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003864 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003865 result.appendFormat(
3866 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3867 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003868 }
3869
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 bool dumpAll = true;
3871 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003873
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003874 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003875 if ((index < numArgs) &&
3876 (args[index] == String16("--list"))) {
3877 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003878 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003879 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003880 }
3881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003884 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003885 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003886 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003887 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--latency-clear"))) {
3891 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003892 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003893 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003894 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--dispsync"))) {
3898 index++;
3899 mPrimaryDispSync.dump(result);
3900 dumpAll = false;
3901 }
Dan Stozab90cf072015-03-05 11:05:59 -08003902
3903 if ((index < numArgs) &&
3904 (args[index] == String16("--static-screen"))) {
3905 index++;
3906 dumpStaticScreenStats(result);
3907 dumpAll = false;
3908 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003909
3910 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003911 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003912 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003913 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003914 dumpAll = false;
3915 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003916
3917 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3918 index++;
3919 dumpWideColorInfo(result);
3920 dumpAll = false;
3921 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003922
3923 if ((index < numArgs) &&
3924 (args[index] == String16("--enable-layer-stats"))) {
3925 index++;
3926 mLayerStats.enable();
3927 dumpAll = false;
3928 }
3929
3930 if ((index < numArgs) &&
3931 (args[index] == String16("--disable-layer-stats"))) {
3932 index++;
3933 mLayerStats.disable();
3934 dumpAll = false;
3935 }
3936
3937 if ((index < numArgs) &&
3938 (args[index] == String16("--clear-layer-stats"))) {
3939 index++;
3940 mLayerStats.clear();
3941 dumpAll = false;
3942 }
3943
3944 if ((index < numArgs) &&
3945 (args[index] == String16("--dump-layer-stats"))) {
3946 index++;
3947 mLayerStats.dump(result);
3948 dumpAll = false;
3949 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003950
3951 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3952 index++;
3953 mTimeStats.parseArgs(asProto, args, index, result);
3954 dumpAll = false;
3955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003957
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003959 if (asProto) {
3960 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3961 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3962 } else {
3963 dumpAllLocked(args, index, result);
3964 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003965 }
3966
Mathias Agopian9795c422009-08-26 16:36:26 -07003967 if (locked) {
3968 mStateLock.unlock();
3969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003970 }
3971 write(fd, result.string(), result.size());
3972 return NO_ERROR;
3973}
3974
Dan Stozac7014012014-02-14 15:03:43 -08003975void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3976 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003977{
Robert Carr2047fae2016-11-28 14:09:09 -08003978 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003979 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003980 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981}
3982
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003983void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003984 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003985{
3986 String8 name;
3987 if (index < args.size()) {
3988 name = String8(args[index]);
3989 index++;
3990 }
3991
David Sodman105b7dc2017-11-04 20:28:14 -07003992 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003993 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003994 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003995
3996 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003997 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003998 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003999 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004000 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004001 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004002 }
Robert Carr2047fae2016-11-28 14:09:09 -08004003 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004004 }
4005}
4006
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004008 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009{
4010 String8 name;
4011 if (index < args.size()) {
4012 name = String8(args[index]);
4013 index++;
4014 }
4015
Robert Carr2047fae2016-11-28 14:09:09 -08004016 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004018 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019 }
Robert Carr2047fae2016-11-28 14:09:09 -08004020 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004021
Svetoslavd85084b2014-03-20 10:28:31 -07004022 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023}
4024
Jamie Gennis6547ff42013-07-16 20:12:42 -07004025// This should only be called from the main thread. Otherwise it would need
4026// the lock and should use mCurrentState rather than mDrawingState.
4027void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004028 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004029 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004030 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004031
4032 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4033}
4034
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004035void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004036{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004037 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004038
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004039 if (isLayerTripleBufferingDisabled())
4040 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004041
4042 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004043 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004044 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004045 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004046 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4047 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004048 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004049}
4050
Dan Stozab90cf072015-03-05 11:05:59 -08004051void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4052{
4053 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004054 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4055 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004056 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004057 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004058 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4059 b + 1, bucketTimeSec, percent);
4060 }
David Sodman4a36e932017-11-07 14:29:47 -08004061 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004062 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004063 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004064 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004065 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004066}
4067
Dan Stozae77c7662016-05-13 11:37:28 -07004068void SurfaceFlinger::recordBufferingStats(const char* layerName,
4069 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004070 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4071 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004072 for (const auto& segment : history) {
4073 if (!segment.usedThirdBuffer) {
4074 stats.twoBufferTime += segment.totalTime;
4075 }
4076 if (segment.occupancyAverage < 1.0f) {
4077 stats.doubleBufferedTime += segment.totalTime;
4078 } else if (segment.occupancyAverage < 2.0f) {
4079 stats.tripleBufferedTime += segment.totalTime;
4080 }
4081 ++stats.numSegments;
4082 stats.totalTime += segment.totalTime;
4083 }
4084}
4085
Brian Andersond6927fb2016-07-23 23:37:30 -07004086void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4087 result.appendFormat("Layer frame timestamps:\n");
4088
4089 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4090 const size_t count = currentLayers.size();
4091 for (size_t i=0 ; i<count ; i++) {
4092 currentLayers[i]->dumpFrameEvents(result);
4093 }
4094}
4095
Dan Stozae77c7662016-05-13 11:37:28 -07004096void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4097 result.append("Buffering stats:\n");
4098 result.append(" [Layer name] <Active time> <Two buffer> "
4099 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004100 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004101 typedef std::tuple<std::string, float, float, float> BufferTuple;
4102 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004103 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004104 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004105 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004106 if (stats.numSegments == 0) {
4107 continue;
4108 }
4109 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4110 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4111 stats.totalTime;
4112 float doubleBufferRatio = static_cast<float>(
4113 stats.doubleBufferedTime) / stats.totalTime;
4114 float tripleBufferRatio = static_cast<float>(
4115 stats.tripleBufferedTime) / stats.totalTime;
4116 sorted.insert({activeTime, {name, twoBufferRatio,
4117 doubleBufferRatio, tripleBufferRatio}});
4118 }
4119 for (const auto& sortedPair : sorted) {
4120 float activeTime = sortedPair.first;
4121 const BufferTuple& values = sortedPair.second;
4122 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4123 std::get<0>(values).c_str(), activeTime,
4124 std::get<1>(values), std::get<2>(values),
4125 std::get<3>(values));
4126 }
4127 result.append("\n");
4128}
4129
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004130void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4131 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004132 result.appendFormat("DisplayColorSetting: %s\n",
4133 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004134
4135 // TODO: print out if wide-color mode is active or not
4136
4137 for (size_t d = 0; d < mDisplays.size(); d++) {
4138 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4139 int32_t hwcId = displayDevice->getHwcDisplayId();
4140 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4141 continue;
4142 }
4143
4144 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004145 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004146 for (auto&& mode : modes) {
4147 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4148 }
4149
Peiyong Lina52f0292018-03-14 17:26:31 -07004150 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004151 result.appendFormat(" Current color mode: %s (%d)\n",
4152 decodeColorMode(currentMode).c_str(), currentMode);
4153 }
4154 result.append("\n");
4155}
4156
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004157LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004158 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004159 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4160 const State& state = useDrawing ? mDrawingState : mCurrentState;
4161 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004162 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004163 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004164 });
4165
4166 return layersProto;
4167}
4168
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004169LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4170 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004171 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004172
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004173 SizeProto* resolution = layersProto.mutable_resolution();
4174 resolution->set_w(displayDevice->getWidth());
4175 resolution->set_h(displayDevice->getHeight());
4176
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004177 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4178 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4179 layersProto.set_global_transform(
4180 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4181
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004182 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004183 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004184 LayerProto* layerProto = layersProto.add_layers();
4185 layer->writeToProto(layerProto, hwcId);
4186 }
4187 });
4188
4189 return layersProto;
4190}
4191
Mathias Agopian74d211a2013-04-22 16:55:35 +02004192void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4193 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004194{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004195 bool colorize = false;
4196 if (index < args.size()
4197 && (args[index] == String16("--color"))) {
4198 colorize = true;
4199 index++;
4200 }
4201
4202 Colorizer colorizer(colorize);
4203
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004204 // figure out if we're stuck somewhere
4205 const nsecs_t now = systemTime();
4206 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4207 const nsecs_t inTransaction(mDebugInTransaction);
4208 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4209 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4210
4211 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004212 * Dump library configuration.
4213 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214
4215 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004216 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004217 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004218 appendSfConfigString(result);
4219 appendUiConfigString(result);
4220 appendGuiConfigString(result);
4221 result.append("\n");
4222
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004223 result.append("\nWide-Color information:\n");
4224 dumpWideColorInfo(result);
4225
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004227 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004229 result.append(SyncFeatures::getInstance().toString());
4230 result.append("\n");
4231
David Sodman105b7dc2017-11-04 20:28:14 -07004232 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004233
Andy McFadden41d67d72014-04-25 16:58:34 -07004234 colorizer.bold(result);
4235 result.append("DispSync configuration: ");
4236 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004237 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4238 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4239 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004240 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004241 result.append("\n");
4242
Dan Stozab90cf072015-03-05 11:05:59 -08004243 // Dump static screen stats
4244 result.append("\n");
4245 dumpStaticScreenStats(result);
4246 result.append("\n");
4247
Dan Stozae77c7662016-05-13 11:37:28 -07004248 dumpBufferingStats(result);
4249
Andy McFadden4803b742012-09-24 19:07:20 -07004250 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 * Dump the visible layer list
4252 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004254 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004255 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4256 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004258
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004259 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004260 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004261 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004262 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263
4264 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004265 * Dump Display state
4266 */
4267
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004269 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004270 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004271 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4272 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004273 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004274 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004275 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004276
4277 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 * Dump SurfaceFlinger global state
4279 */
4280
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004281 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004282 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
Mathias Agopian888c8222012-08-04 21:10:38 -07004285 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004286 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004287
David Sodmanbc815282017-11-05 18:57:52 -08004288 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004289
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004290 if (hw) {
4291 hw->undefinedRegion.dump(result, "undefinedRegion");
4292 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4293 hw->getOrientation(), hw->isDisplayOn());
4294 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004295 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004296 " last eglSwapBuffers() time: %f us\n"
4297 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004298 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299 " refresh-rate : %f fps\n"
4300 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004301 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004302 " gpu_to_cpu_unsupported : %d\n"
4303 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304 mLastSwapBufferTime/1000.0,
4305 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004306 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004307 1e9 / activeConfig->getVsyncPeriod(),
4308 activeConfig->getDpiX(),
4309 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004310 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004311
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314
Mathias Agopian74d211a2013-04-22 16:55:35 +02004315 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004316 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317
4318 /*
4319 * VSYNC state
4320 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004321 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004322 result.append("\n");
4323
4324 /*
4325 * HWC layer minidump
4326 */
4327 for (size_t d = 0; d < mDisplays.size(); d++) {
4328 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4329 int32_t hwcId = displayDevice->getHwcDisplayId();
4330 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4331 continue;
4332 }
4333
4334 result.appendFormat("Display %d HWC layers:\n", hwcId);
4335 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004336 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004337 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004338 });
Dan Stozae22aec72016-08-01 13:20:59 -07004339 result.append("\n");
4340 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341
4342 /*
4343 * Dump HWComposer state
4344 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004346 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004347 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004348 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004349 result.appendFormat(" h/w composer %s\n",
4350 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004351 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
4353 /*
4354 * Dump gralloc state
4355 */
4356 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4357 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004358
4359 /*
4360 * Dump VrFlinger state if in use.
4361 */
4362 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4363 result.append("VrFlinger state:\n");
4364 result.append(mVrFlinger->Dump().c_str());
4365 result.append("\n");
4366 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367}
4368
Mathias Agopian13127d82013-03-05 17:47:11 -08004369const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004370SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004371 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004372 wp<IBinder> dpy;
4373 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4374 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4375 dpy = mDisplays.keyAt(i);
4376 break;
4377 }
4378 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004379 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004380 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4381 // Just use the primary display so we have something to return
4382 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4383 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004384 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004385}
4386
Keun young Park63f165f2012-08-31 10:53:36 -07004387bool SurfaceFlinger::startDdmConnection()
4388{
4389 void* libddmconnection_dso =
4390 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4391 if (!libddmconnection_dso) {
4392 return false;
4393 }
4394 void (*DdmConnection_start)(const char* name);
4395 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004396 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004397 if (!DdmConnection_start) {
4398 dlclose(libddmconnection_dso);
4399 return false;
4400 }
4401 (*DdmConnection_start)(getServiceName());
4402 return true;
4403}
4404
Chia-I Wu28f320b2018-05-03 11:02:56 -07004405void SurfaceFlinger::updateColorMatrixLocked() {
4406 mat4 colorMatrix;
4407 if (mGlobalSaturationFactor != 1.0f) {
4408 // Rec.709 luma coefficients
4409 float3 luminance{0.213f, 0.715f, 0.072f};
4410 luminance *= 1.0f - mGlobalSaturationFactor;
4411 mat4 saturationMatrix = mat4(
4412 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4413 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4414 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4415 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4416 );
4417 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4418 } else {
4419 colorMatrix = mClientColorMatrix * mDaltonizer();
4420 }
4421
4422 if (mCurrentState.colorMatrix != colorMatrix) {
4423 mCurrentState.colorMatrix = colorMatrix;
4424 mCurrentState.colorMatrixChanged = true;
4425 setTransactionFlags(eTransactionNeeded);
4426 }
4427}
4428
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004429status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 switch (code) {
4431 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004432 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004434 case CLEAR_ANIMATION_FRAME_STATS:
4435 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004436 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004437 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004438 case ENABLE_VSYNC_INJECTIONS:
4439 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 {
4441 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004442 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4443 IPCThreadState* ipc = IPCThreadState::self();
4444 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4445 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004446 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004448 break;
4449 }
Robert Carr1db73f62016-12-21 12:58:51 -08004450 /*
4451 * Calling setTransactionState is safe, because you need to have been
4452 * granted a reference to Client* and Handle* to do anything with it.
4453 *
4454 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4455 */
4456 case SET_TRANSACTION_STATE:
4457 case CREATE_SCOPED_CONNECTION:
4458 {
4459 return OK;
4460 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004461 case CAPTURE_SCREEN:
4462 {
4463 // codes that require permission check
4464 IPCThreadState* ipc = IPCThreadState::self();
4465 const int pid = ipc->getCallingPid();
4466 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004467 if ((uid != AID_GRAPHICS) &&
4468 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004469 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004470 return PERMISSION_DENIED;
4471 }
4472 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 }
chaviwa76b2712017-09-20 12:02:26 -07004474 case CAPTURE_LAYERS: {
4475 IPCThreadState* ipc = IPCThreadState::self();
4476 const int pid = ipc->getCallingPid();
4477 const int uid = ipc->getCallingUid();
4478 if ((uid != AID_GRAPHICS) &&
4479 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4480 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4481 return PERMISSION_DENIED;
4482 }
4483 break;
4484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004485 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004486 return OK;
4487}
4488
4489status_t SurfaceFlinger::onTransact(
4490 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4491{
4492 status_t credentialCheck = CheckTransactCodeCredentials(code);
4493 if (credentialCheck != OK) {
4494 return credentialCheck;
4495 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4498 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004499 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004500 IPCThreadState* ipc = IPCThreadState::self();
4501 const int uid = ipc->getCallingUid();
4502 if (CC_UNLIKELY(uid != AID_SYSTEM
4503 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004504 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004505 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004506 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004507 return PERMISSION_DENIED;
4508 }
4509 int n;
4510 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004511 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004512 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 return NO_ERROR;
4514 case 1002: // SHOW_UPDATES
4515 n = data.readInt32();
4516 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004517 invalidateHwcGeometry();
4518 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004521 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004522 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004524 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004525 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004526 setTransactionFlags(
4527 eTransactionNeeded|
4528 eDisplayTransactionNeeded|
4529 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004530 return NO_ERROR;
4531 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004532 case 1006:{ // send empty update
4533 signalRefresh();
4534 return NO_ERROR;
4535 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004536 case 1008: // toggle use of hw composer
4537 n = data.readInt32();
4538 mDebugDisableHWC = n ? 1 : 0;
4539 invalidateHwcGeometry();
4540 repaintEverything();
4541 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004542 case 1009: // toggle use of transform hint
4543 n = data.readInt32();
4544 mDebugDisableTransformHint = n ? 1 : 0;
4545 invalidateHwcGeometry();
4546 repaintEverything();
4547 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004549 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 reply->writeInt32(0);
4551 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004552 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004553 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004554 return NO_ERROR;
4555 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004556 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004557 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004558 return NO_ERROR;
4559 }
4560 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004561 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004562 // daltonize
4563 n = data.readInt32();
4564 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004565 case 1:
4566 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4567 break;
4568 case 2:
4569 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4570 break;
4571 case 3:
4572 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4573 break;
4574 default:
4575 mDaltonizer.setType(ColorBlindnessType::None);
4576 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004577 }
4578 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004579 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004580 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004581 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004582 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004583
4584 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004587 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004588 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004589 // apply a color matrix
4590 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004591 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004592 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004593 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004594 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004595 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004596 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004597 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004598 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004599 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004601
4602 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4603 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004604 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004605 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4606 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4607 }
4608
Chia-I Wu28f320b2018-05-03 11:02:56 -07004609 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 return NO_ERROR;
4611 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004612 // This is an experimental interface
4613 // Needs to be shifted to proper binder interface when we productize
4614 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004615 n = data.readInt32();
4616 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004617 return NO_ERROR;
4618 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004619 case 1017: {
4620 n = data.readInt32();
4621 mForceFullDamage = static_cast<bool>(n);
4622 return NO_ERROR;
4623 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004624 case 1018: { // Modify Choreographer's phase offset
4625 n = data.readInt32();
4626 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4627 return NO_ERROR;
4628 }
4629 case 1019: { // Modify SurfaceFlinger's phase offset
4630 n = data.readInt32();
4631 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4632 return NO_ERROR;
4633 }
Irvel468051e2016-06-13 16:44:44 -07004634 case 1020: { // Layer updates interceptor
4635 n = data.readInt32();
4636 if (n) {
4637 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004638 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004639 }
4640 else{
4641 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004642 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004643 }
4644 return NO_ERROR;
4645 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004646 case 1021: { // Disable HWC virtual displays
4647 n = data.readInt32();
4648 mUseHwcVirtualDisplays = !n;
4649 return NO_ERROR;
4650 }
Romain Guy0147a172017-06-01 13:53:56 -07004651 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004653 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004654
Chia-I Wu28f320b2018-05-03 11:02:56 -07004655 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004656 return NO_ERROR;
4657 }
Romain Guy54f154a2017-10-24 21:40:32 +01004658 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004659 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004660 invalidateHwcGeometry();
4661 repaintEverything();
4662 return NO_ERROR;
4663 }
4664 case 1024: { // Is wide color gamut rendering/color management supported?
4665 reply->writeBool(hasWideColorDisplay);
4666 return NO_ERROR;
4667 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004668 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004669 n = data.readInt32();
4670 if (n) {
4671 ALOGV("LayerTracing enabled");
4672 mTracing.enable();
4673 doTracing("tracing.enable");
4674 reply->writeInt32(NO_ERROR);
4675 } else {
4676 ALOGV("LayerTracing disabled");
4677 status_t err = mTracing.disable();
4678 reply->writeInt32(err);
4679 }
4680 return NO_ERROR;
4681 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004682 case 1026: { // Get layer tracing status
4683 reply->writeBool(mTracing.isEnabled());
4684 return NO_ERROR;
4685 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004686 // Is a DisplayColorSetting supported?
4687 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004688 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4689 if (!hw) {
4690 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004691 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004692
4693 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4694 switch (setting) {
4695 case DisplayColorSetting::MANAGED:
4696 reply->writeBool(hasWideColorDisplay);
4697 break;
4698 case DisplayColorSetting::UNMANAGED:
4699 reply->writeBool(true);
4700 break;
4701 case DisplayColorSetting::ENHANCED:
4702 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4703 break;
4704 default: // vendor display color setting
4705 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4706 break;
4707 }
4708 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 }
4711 }
4712 return err;
4713}
4714
Steven Thomas6d8110b2017-08-31 18:24:21 -07004715void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004716 android_atomic_or(1, &mRepaintEverything);
4717 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004718}
4719
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004720// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4721class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004722public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004723 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4724 ~WindowDisconnector() {
4725 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004726 }
4727
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004728private:
4729 ANativeWindow* mWindow;
4730 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004731};
4732
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004733status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4734 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4735 int32_t minLayerZ, int32_t maxLayerZ,
4736 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004737 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004738 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004739
chaviwa76b2712017-09-20 12:02:26 -07004740 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4741
4742 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004743 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4744
chaviwa76b2712017-09-20 12:02:26 -07004745 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4746
4747 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4748 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004749 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004750}
4751
4752status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004753 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004754 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004755 ATRACE_CALL();
4756
4757 class LayerRenderArea : public RenderArea {
4758 public:
Robert Carr578038f2018-03-09 12:25:24 -08004759 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4760 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004761 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004762 mLayer(layer),
4763 mCrop(crop),
4764 mFlinger(flinger),
4765 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004766 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004767 Rect getBounds() const override {
4768 const Layer::State& layerState(mLayer->getDrawingState());
4769 return Rect(layerState.active.w, layerState.active.h);
4770 }
4771 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4772 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4773 bool isSecure() const override { return false; }
4774 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004775 Rect getSourceCrop() const override {
4776 if (mCrop.isEmpty()) {
4777 return getBounds();
4778 } else {
4779 return mCrop;
4780 }
4781 }
Robert Carr578038f2018-03-09 12:25:24 -08004782 class ReparentForDrawing {
4783 public:
4784 const sp<Layer>& oldParent;
4785 const sp<Layer>& newParent;
4786
4787 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4788 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004789 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004790 }
Robert Carr15eae092018-03-23 13:43:53 -07004791 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004792 };
4793
4794 void render(std::function<void()> drawLayers) override {
4795 if (!mChildrenOnly) {
4796 mTransform = mLayer->getTransform().inverse();
4797 drawLayers();
4798 } else {
4799 Rect bounds = getBounds();
4800 screenshotParentLayer =
4801 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4802 bounds.getWidth(), bounds.getHeight(), 0);
4803
4804 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4805 drawLayers();
4806 }
4807 }
chaviwa76b2712017-09-20 12:02:26 -07004808
chaviwa76b2712017-09-20 12:02:26 -07004809 private:
chaviw7206d492017-11-10 16:16:12 -08004810 const sp<Layer> mLayer;
4811 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004812
4813 // In the "childrenOnly" case we reparent the children to a screenshot
4814 // layer which has no properties set and which does not draw.
4815 sp<ContainerLayer> screenshotParentLayer;
4816 Transform mTransform;
4817
4818 SurfaceFlinger* mFlinger;
4819 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004820 };
4821
4822 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4823 auto parent = layerHandle->owner.promote();
4824
chaviw7206d492017-11-10 16:16:12 -08004825 if (parent == nullptr || parent->isPendingRemoval()) {
4826 ALOGE("captureLayers called with a removed parent");
4827 return NAME_NOT_FOUND;
4828 }
4829
Robert Carr578038f2018-03-09 12:25:24 -08004830 const int uid = IPCThreadState::self()->getCallingUid();
4831 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4832 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4833 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4834 return PERMISSION_DENIED;
4835 }
4836
chaviw7206d492017-11-10 16:16:12 -08004837 Rect crop(sourceCrop);
4838 if (sourceCrop.width() <= 0) {
4839 crop.left = 0;
4840 crop.right = parent->getCurrentState().active.w;
4841 }
4842
4843 if (sourceCrop.height() <= 0) {
4844 crop.top = 0;
4845 crop.bottom = parent->getCurrentState().active.h;
4846 }
4847
4848 int32_t reqWidth = crop.width() * frameScale;
4849 int32_t reqHeight = crop.height() * frameScale;
4850
Robert Carr578038f2018-03-09 12:25:24 -08004851 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004852
Robert Carr578038f2018-03-09 12:25:24 -08004853 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004854 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4855 if (!layer->isVisible()) {
4856 return;
Robert Carr578038f2018-03-09 12:25:24 -08004857 } else if (childrenOnly && layer == parent.get()) {
4858 return;
chaviwa76b2712017-09-20 12:02:26 -07004859 }
4860 visitor(layer);
4861 });
4862 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004863 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004864}
4865
4866status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4867 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004868 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004869 bool useIdentityTransform) {
4870 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004871
Iris Chang7501ed62018-04-30 14:45:42 +08004872 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004873
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004874 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4875 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4876 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4877 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004878
4879 // This mutex protects syncFd and captureResult for communication of the return values from the
4880 // main thread back to this Binder thread
4881 std::mutex captureMutex;
4882 std::condition_variable captureCondition;
4883 std::unique_lock<std::mutex> captureLock(captureMutex);
4884 int syncFd = -1;
4885 std::optional<status_t> captureResult;
4886
Robert Carr03480e22018-01-04 16:02:06 -08004887 const int uid = IPCThreadState::self()->getCallingUid();
4888 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4889
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004890 sp<LambdaMessage> message = new LambdaMessage([&]() {
4891 // If there is a refresh pending, bug out early and tell the binder thread to try again
4892 // after the refresh.
4893 if (mRefreshPending) {
4894 ATRACE_NAME("Skipping screenshot for now");
4895 std::unique_lock<std::mutex> captureLock(captureMutex);
4896 captureResult = std::make_optional<status_t>(EAGAIN);
4897 captureCondition.notify_one();
4898 return;
4899 }
4900
4901 status_t result = NO_ERROR;
4902 int fd = -1;
4903 {
4904 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004905 renderArea.render([&]() {
4906 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4907 useIdentityTransform, forSystem, &fd);
4908 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004909 }
4910
4911 {
4912 std::unique_lock<std::mutex> captureLock(captureMutex);
4913 syncFd = fd;
4914 captureResult = std::make_optional<status_t>(result);
4915 captureCondition.notify_one();
4916 }
4917 });
4918
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004919 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004920 if (result == NO_ERROR) {
4921 captureCondition.wait(captureLock, [&]() { return captureResult; });
4922 while (*captureResult == EAGAIN) {
4923 captureResult.reset();
4924 result = postMessageAsync(message);
4925 if (result != NO_ERROR) {
4926 return result;
4927 }
4928 captureCondition.wait(captureLock, [&]() { return captureResult; });
4929 }
4930 result = *captureResult;
4931 }
4932
4933 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004934 sync_wait(syncFd, -1);
4935 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004936 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004937
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004938 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004939}
4940
chaviwa76b2712017-09-20 12:02:26 -07004941void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4942 TraverseLayersFunction traverseLayers, bool yswap,
4943 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004944 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004945
Lloyd Pique144e1162017-12-20 16:44:52 -08004946 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004947
4948 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004949 const auto raWidth = renderArea.getWidth();
4950 const auto raHeight = renderArea.getHeight();
4951
4952 const auto reqWidth = renderArea.getReqWidth();
4953 const auto reqHeight = renderArea.getReqHeight();
4954 Rect sourceCrop = renderArea.getSourceCrop();
4955
Iris Chang7501ed62018-04-30 14:45:42 +08004956 bool filtering = false;
4957 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4958 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4959 static_cast<int32_t>(reqHeight) != raWidth;
4960 } else {
4961 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4962 static_cast<int32_t>(reqHeight) != raHeight;
4963 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004964
Dan Stozac1879002014-05-22 15:59:05 -07004965 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004966 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004967 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004968 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004969 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4970 Transform tr;
4971 uint32_t flags = 0x00;
4972 switch (mPrimaryDisplayOrientation) {
4973 case DisplayState::eOrientation90:
4974 flags = Transform::ROT_90;
4975 break;
4976 case DisplayState::eOrientation180:
4977 flags = Transform::ROT_180;
4978 break;
4979 case DisplayState::eOrientation270:
4980 flags = Transform::ROT_270;
4981 break;
4982 }
4983 tr.set(flags, raWidth, raHeight);
4984 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07004985 }
4986
4987 // ensure that sourceCrop is inside screen
4988 if (sourceCrop.left < 0) {
4989 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4990 }
chaviwa76b2712017-09-20 12:02:26 -07004991 if (sourceCrop.right > raWidth) {
4992 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004993 }
4994 if (sourceCrop.top < 0) {
4995 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4996 }
chaviwa76b2712017-09-20 12:02:26 -07004997 if (sourceCrop.bottom > raHeight) {
4998 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004999 }
5000
Chia-I Wu36574d92018-05-16 10:54:36 -07005001 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5002 engine.setOutputDataSpace(Dataspace::SRGB);
5003 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005004
Mathias Agopian180f10d2013-04-10 22:55:41 -07005005 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005006 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005007
Iris Chang7501ed62018-04-30 14:45:42 +08005008 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5009 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5010 // convert hw orientation into flag presentation
5011 // here inverse transform needed
5012 uint8_t hw_rot_90 = 0x00;
5013 uint8_t hw_flip_hv = 0x00;
5014 switch (mPrimaryDisplayOrientation) {
5015 case DisplayState::eOrientation90:
5016 hw_rot_90 = Transform::ROT_90;
5017 hw_flip_hv = Transform::ROT_180;
5018 break;
5019 case DisplayState::eOrientation180:
5020 hw_flip_hv = Transform::ROT_180;
5021 break;
5022 case DisplayState::eOrientation270:
5023 hw_rot_90 = Transform::ROT_90;
5024 break;
5025 }
5026
5027 // transform flags operation
5028 // 1) flip H V if both have ROT_90 flag
5029 // 2) XOR these flags
5030 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5031 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5032 if (rotation_rot_90 & hw_rot_90) {
5033 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5034 }
5035 rotation = static_cast<Transform::orientation_flags>
5036 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5037 }
5038
Mathias Agopian180f10d2013-04-10 22:55:41 -07005039 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005040 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005041 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005042 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005043
chaviw50da5042018-04-09 13:49:37 -07005044 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005045 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005046 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005047
chaviwa76b2712017-09-20 12:02:26 -07005048 traverseLayers([&](Layer* layer) {
5049 if (filtering) layer->setFiltering(true);
5050 layer->draw(renderArea, useIdentityTransform);
5051 if (filtering) layer->setFiltering(false);
5052 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005053}
5054
chaviwa76b2712017-09-20 12:02:26 -07005055status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5056 TraverseLayersFunction traverseLayers,
5057 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005058 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005059 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005060 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005061 ATRACE_CALL();
5062
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005063 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005064
5065 traverseLayers([&](Layer* layer) {
5066 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5067 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005068
Robert Carr03480e22018-01-04 16:02:06 -08005069 // We allow the system server to take screenshots of secure layers for
5070 // use in situations like the Screen-rotation animation and place
5071 // the impetus on WindowManager to not persist them.
5072 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005073 ALOGW("FB is protected: PERMISSION_DENIED");
5074 return PERMISSION_DENIED;
5075 }
5076
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005077 // this binds the given EGLImage as a framebuffer for the
5078 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005079 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005080 if (bufferBond.getStatus() != NO_ERROR) {
5081 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005082 return INVALID_OPERATION;
5083 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005084
Dan Stozaabcda352017-06-01 14:37:39 -07005085 // this will in fact render into our dequeued buffer
5086 // via an FBO, which means we didn't have to create
5087 // an EGLSurface and therefore we're not
5088 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005089 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005090
Dan Stozaabcda352017-06-01 14:37:39 -07005091 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005092 getRenderEngine().finish();
5093 *outSyncFd = -1;
5094
chaviwa76b2712017-09-20 12:02:26 -07005095 const auto reqWidth = renderArea.getReqWidth();
5096 const auto reqHeight = renderArea.getReqHeight();
5097
Dan Stozaabcda352017-06-01 14:37:39 -07005098 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5099 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005100 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005101 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005102 } else {
5103 base::unique_fd syncFd = getRenderEngine().flush();
5104 if (syncFd < 0) {
5105 getRenderEngine().finish();
5106 }
5107 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005108 }
5109
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005110 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005111}
5112
Mathias Agopiand5556842013-09-19 17:08:37 -07005113void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005114 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005115 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005116 for (size_t y = 0; y < h; y++) {
5117 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5118 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005119 if (p[x] != 0xFF000000) return;
5120 }
5121 }
chaviwa76b2712017-09-20 12:02:26 -07005122 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005123
Robert Carr2047fae2016-11-28 14:09:09 -08005124 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005125 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005126 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005127 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5128 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5129 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5130 static_cast<float>(state.color.a));
5131 i++;
5132 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005133 }
5134}
5135
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005136// ---------------------------------------------------------------------------
5137
Dan Stoza412903f2017-04-27 13:42:17 -07005138void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5139 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005140}
5141
Dan Stoza412903f2017-04-27 13:42:17 -07005142void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5143 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005144}
5145
chaviwa76b2712017-09-20 12:02:26 -07005146void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5147 int32_t maxLayerZ,
5148 const LayerVector::Visitor& visitor) {
5149 // We loop through the first level of layers without traversing,
5150 // as we need to interpret min/max layer Z in the top level Z space.
5151 for (const auto& layer : mDrawingState.layersSortedByZ) {
5152 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5153 continue;
5154 }
5155 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005156 // relative layers are traversed in Layer::traverseInZOrder
5157 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005158 continue;
5159 }
5160 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005161 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5162 return;
5163 }
chaviwa76b2712017-09-20 12:02:26 -07005164 if (!layer->isVisible()) {
5165 return;
5166 }
5167 visitor(layer);
5168 });
5169 }
5170}
5171
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005172}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005173
5174
5175#if defined(__gl_h_)
5176#error "don't include gl/gl.h in this file"
5177#endif
5178
5179#if defined(__gl2_h_)
5180#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005181#endif