blob: 7a8737f930f23d9a91cad971bea42bc9274dd2b2 [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
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
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>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Jiyong Park00b15b82017-08-10 20:30:56 +0900101extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Thierry Strudel2924d012017-08-14 15:19:37 -0700420 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700421 readPersistentProperties();
422 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700423 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian3f844832013-08-07 21:24:32 -0700426void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700427 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 RenderEngine& engine;
429 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700430 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700431 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
432 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700433 }
434 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700435 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700436 return true;
437 }
438 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700439 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440}
441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442class DispSyncSource : public VSyncSource, private DispSync::Callback {
443public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* name) :
446 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000449 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
450 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 mDispSync(dispSync),
452 mCallbackMutex(),
453 mCallback(),
454 mVsyncMutex(),
455 mPhaseOffset(phaseOffset),
456 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 virtual ~DispSyncSource() {}
459
460 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700469 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 } else {
471 status_t err = mDispSync->removeEventListener(
472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error unregistering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700479 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 mCallback = callback;
485 }
486
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700487 virtual void setPhaseOffset(nsecs_t phaseOffset) {
488 Mutex::Autolock lock(mVsyncMutex);
489
490 // Normalize phaseOffset to [0, period)
491 auto period = mDispSync->getPeriod();
492 phaseOffset %= period;
493 if (phaseOffset < 0) {
494 // If we're here, then phaseOffset is in (-period, 0). After this
495 // operation, it will be in (0, period)
496 phaseOffset += period;
497 }
498 mPhaseOffset = phaseOffset;
499
500 // If we're not enabled, we don't need to mess with the listeners
501 if (!mEnabled) {
502 return;
503 }
504
505 // Remove the listener with the old offset
506 status_t err = mDispSync->removeEventListener(
507 static_cast<DispSync::Callback*>(this));
508 if (err != NO_ERROR) {
509 ALOGE("error unregistering vsync callback: %s (%d)",
510 strerror(-err), err);
511 }
512
513 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
520 }
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522private:
523 virtual void onDispSyncEvent(nsecs_t when) {
524 sp<VSyncSource::Callback> callback;
525 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 callback = mCallback;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 if (mTraceVsync) {
530 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
535 if (callback != NULL) {
536 callback->onVSyncEvent(when);
537 }
538 }
539
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 const char* const mName;
541
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 int mValue;
543
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700544 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700545 const String8 mVsyncOnLabel;
546 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700548 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700549
550 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700551 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700552
553 Mutex mVsyncMutex; // Protects the following
554 nsecs_t mPhaseOffset;
555 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556};
557
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558class InjectVSyncSource : public VSyncSource {
559public:
560 InjectVSyncSource() {}
561
562 virtual ~InjectVSyncSource() {}
563
564 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
565 std::lock_guard<std::mutex> lock(mCallbackMutex);
566 mCallback = callback;
567 }
568
569 virtual void onInjectSyncEvent(nsecs_t when) {
570 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu6200eac2017-10-05 14:24:41 -0700571 if (mCallback != nullptr) {
572 mCallback->onVSyncEvent(when);
573 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700574 }
575
576 virtual void setVSyncEnabled(bool) {}
577 virtual void setPhaseOffset(nsecs_t) {}
578
579private:
580 std::mutex mCallbackMutex; // Protects the following
581 sp<VSyncSource::Callback> mCallback;
582};
583
Wei Wangf9b05ee2017-07-19 20:59:39 -0700584// Do not call property_set on main thread which will be blocked by init
585// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700587 ALOGI( "SurfaceFlinger's main thread ready to run. "
588 "Initializing graphics H/W...");
589
Thierry Strudel2924d012017-08-14 15:19:37 -0700590 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 // initialize EGL for the default display
595 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
596 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // start the EventThread
599 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
600 vsyncPhaseOffsetNs, true, "app");
601 mEventThread = new EventThread(vsyncSrc, *this, false);
602 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
603 sfVsyncPhaseOffsetNs, true, "sf");
604 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
605 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
608 struct sched_param param = {0};
609 param.sched_priority = 2;
610 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
611 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
612 }
613 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
614 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615 }
616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // Get a RenderEngine for the given display / config (can't fail)
618 mRenderEngine = RenderEngine::create(mEGLDisplay,
619 HAL_PIXEL_FORMAT_RGBA_8888,
620 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // retrieve the EGL context that was selected/created
623 mEGLContext = mRenderEngine->getEGLContext();
624
625 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
626 "couldn't create EGLContext");
627
628 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
629 "Starting with vr flinger active is not currently supported.");
630 mHwc.reset(new HWComposer(mHwcServiceName));
631 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 if (useVrFlinger) {
634 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 // This callback is called from the vr flinger dispatch thread. We
636 // need to call signalTransaction(), which requires holding
637 // mStateLock when we're not on the main thread. Acquiring
638 // mStateLock from the vr flinger dispatch thread might trigger a
639 // deadlock in surface flinger (see b/66916578), so post a message
640 // to be handled on the main thread instead.
641 sp<LambdaMessage> message = new LambdaMessage([=]() {
642 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
643 mVrFlingerRequestsDisplay = requestDisplay;
644 signalTransaction();
645 });
646 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 };
648 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
649 vrFlingerRequestDisplayCallback);
650 if (!mVrFlinger) {
651 ALOGE("Failed to start vrflinger");
652 }
653 }
654
Jamie Gennisd1700752013-10-14 12:22:52 -0700655 mEventControlThread = new EventControlThread(this);
656 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
657
Mathias Agopian92a979a2012-08-02 18:32:23 -0700658 // initialize our drawing state
659 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700660
Andy McFadden13a082e2012-08-24 10:16:42 -0700661 // set initial conditions (e.g. unblank default device)
662 initializeDisplays();
663
Dan Stoza4e637772016-07-28 13:31:51 -0700664 mRenderEngine->primeCache();
665
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 // Inform native graphics APIs whether the present timestamp is supported:
667 if (getHwComposer().hasCapability(
668 HWC2::Capability::PresentFenceIsNotReliable)) {
669 mStartPropertySetThread = new StartPropertySetThread(false);
670 } else {
671 mStartPropertySetThread = new StartPropertySetThread(true);
672 }
673
674 if (mStartPropertySetThread->Start() != NO_ERROR) {
675 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800676 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800677
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700679}
680
Romain Guy11d63f42017-07-20 12:47:14 -0700681void SurfaceFlinger::readPersistentProperties() {
682 char value[PROPERTY_VALUE_MAX];
683
684 property_get("persist.sys.sf.color_saturation", value, "1.0");
685 mSaturation = atof(value);
686 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100687
688 property_get("persist.sys.sf.native_mode", value, "0");
689 mForceNativeColorMode = atoi(value) == 1;
690 if (mForceNativeColorMode) {
691 ALOGV("Forcing native color mode");
692 }
Romain Guy11d63f42017-07-20 12:47:14 -0700693}
694
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800696 // Start boot animation service by setting a property mailbox
697 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800699 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 if (mStartPropertySetThread->join() != NO_ERROR) {
701 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703}
704
Mathias Agopian875d8e12013-06-07 15:35:48 -0700705size_t SurfaceFlinger::getMaxTextureSize() const {
706 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxViewportDims() const {
710 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800714
Jamie Gennis582270d2011-08-17 18:19:00 -0700715bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800717 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800718 return authenticateSurfaceTextureLocked(bufferProducer);
719}
720
721bool SurfaceFlinger::authenticateSurfaceTextureLocked(
722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800723 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700724 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800725}
726
Brian Anderson6b376712017-04-04 10:51:39 -0700727status_t SurfaceFlinger::getSupportedFrameTimestamps(
728 std::vector<FrameEvent>* outSupported) const {
729 *outSupported = {
730 FrameEvent::REQUESTED_PRESENT,
731 FrameEvent::ACQUIRE,
732 FrameEvent::LATCH,
733 FrameEvent::FIRST_REFRESH_START,
734 FrameEvent::LAST_REFRESH_START,
735 FrameEvent::GPU_COMPOSITION_DONE,
736 FrameEvent::DEQUEUE_READY,
737 FrameEvent::RELEASE,
738 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700739 ConditionalLock _l(mStateLock,
740 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700741 if (!getHwComposer().hasCapability(
742 HWC2::Capability::PresentFenceIsNotReliable)) {
743 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
744 }
745 return NO_ERROR;
746}
747
Dan Stoza7f7da322014-05-02 15:26:25 -0700748status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
749 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700750 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 return BAD_VALUE;
752 }
753
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500754 if (!display.get())
755 return NAME_NOT_FOUND;
756
Jesse Hall692c7232012-11-08 15:41:56 -0800757 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700758 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800759 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700760 type = i;
761 break;
762 }
763 }
764
765 if (type < 0) {
766 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700767 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700768
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 // TODO: Not sure if display density should handled by SF any longer
770 class Density {
771 static int getDensityFromProperty(char const* propName) {
772 char property[PROPERTY_VALUE_MAX];
773 int density = 0;
774 if (property_get(propName, property, NULL) > 0) {
775 density = atoi(property);
776 }
777 return density;
778 }
779 public:
780 static int getEmuDensity() {
781 return getDensityFromProperty("qemu.sf.lcd_density"); }
782 static int getBuildDensity() {
783 return getDensityFromProperty("ro.sf.lcd_density"); }
784 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700785
Dan Stoza7f7da322014-05-02 15:26:25 -0700786 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700787
Steven Thomas6d8110b2017-08-31 18:24:21 -0700788 ConditionalLock _l(mStateLock,
789 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 DisplayInfo info = DisplayInfo();
792
Dan Stoza9e56aa02015-11-02 13:00:03 -0800793 float xdpi = hwConfig->getDpiX();
794 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700795
796 if (type == DisplayDevice::DISPLAY_PRIMARY) {
797 // The density of the device is provided by a build property
798 float density = Density::getBuildDensity() / 160.0f;
799 if (density == 0) {
800 // the build doesn't provide a density -- this is wrong!
801 // use xdpi instead
802 ALOGE("ro.sf.lcd_density must be defined as a build property");
803 density = xdpi / 160.0f;
804 }
805 if (Density::getEmuDensity()) {
806 // if "qemu.sf.lcd_density" is specified, it overrides everything
807 xdpi = ydpi = density = Density::getEmuDensity();
808 density /= 160.0f;
809 }
810 info.density = density;
811
812 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700813 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000814 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 } else {
816 // TODO: where should this value come from?
817 static const int TV_DENSITY = 213;
818 info.density = TV_DENSITY / 160.0f;
819 info.orientation = 0;
820 }
821
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822 info.w = hwConfig->getWidth();
823 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 info.xdpi = xdpi;
825 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900827 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828
Andy McFadden91b2ca82014-06-13 14:04:23 -0700829 // This is how far in advance a buffer must be queued for
830 // presentation at a given time. If you want a buffer to appear
831 // on the screen at time N, you must submit the buffer before
832 // (N - presentationDeadline).
833 //
834 // Normally it's one full refresh period (to give SF a chance to
835 // latch the buffer), but this can be reduced by configuring a
836 // DispSync offset. Any additional delays introduced by the hardware
837 // composer or panel must be accounted for here.
838 //
839 // We add an additional 1ms to allow for processing time and
840 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800842 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 // All non-virtual displays are currently considered secure.
845 info.secure = true;
846
Michael Wright28f24d02016-07-12 13:30:53 -0700847 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 }
849
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 return NO_ERROR;
851}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700852
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800853status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700854 DisplayStatInfo* stats) {
855 if (stats == NULL) {
856 return BAD_VALUE;
857 }
858
859 // FIXME for now we always return stats for the primary display
860 memset(stats, 0, sizeof(*stats));
861 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
862 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
863 return NO_ERROR;
864}
865
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700866int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800867 if (display == NULL) {
868 ALOGE("%s : display is NULL", __func__);
869 return BAD_VALUE;
870 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700871
872 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700873 if (device != NULL) {
874 return device->getActiveConfig();
875 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700876
Dan Stoza24a42e92015-03-09 10:04:11 -0700877 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700878}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700879
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
881 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
882 this);
883 int32_t type = hw->getDisplayType();
884 int currentMode = hw->getActiveConfig();
885
886 if (mode == currentMode) {
887 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
888 return;
889 }
890
891 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
892 ALOGW("Trying to set config for virtual display");
893 return;
894 }
895
896 hw->setActiveConfig(mode);
897 getHwComposer().setActiveConfig(type, mode);
898}
899
900status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
901 class MessageSetActiveConfig: public MessageBase {
902 SurfaceFlinger& mFlinger;
903 sp<IBinder> mDisplay;
904 int mMode;
905 public:
906 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
907 int mode) :
908 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
909 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700910 Vector<DisplayInfo> configs;
911 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700912 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700913 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700914 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700915 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700916 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
918 if (hw == NULL) {
919 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700920 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700921 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
922 ALOGW("Attempt to set active config = %d for virtual display",
923 mMode);
924 } else {
925 mFlinger.setActiveConfigInternal(hw, mMode);
926 }
927 return true;
928 }
929 };
930 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
931 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700932 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700933}
Michael Wright28f24d02016-07-12 13:30:53 -0700934status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
935 Vector<android_color_mode_t>* outColorModes) {
936 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
937 return BAD_VALUE;
938 }
939
940 if (!display.get()) {
941 return NAME_NOT_FOUND;
942 }
943
944 int32_t type = NAME_NOT_FOUND;
945 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
946 if (display == mBuiltinDisplays[i]) {
947 type = i;
948 break;
949 }
950 }
951
952 if (type < 0) {
953 return type;
954 }
955
Steven Thomas6d8110b2017-08-31 18:24:21 -0700956 std::vector<android_color_mode_t> modes;
957 {
958 ConditionalLock _l(mStateLock,
959 std::this_thread::get_id() != mMainThreadId);
960 modes = getHwComposer().getColorModes(type);
961 }
Michael Wright28f24d02016-07-12 13:30:53 -0700962 outColorModes->clear();
963 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
964
965 return NO_ERROR;
966}
967
968android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700969 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700970 if (device != nullptr) {
971 return device->getActiveColorMode();
972 }
973 return static_cast<android_color_mode_t>(BAD_VALUE);
974}
975
976void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
977 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 int32_t type = hw->getDisplayType();
979 android_color_mode_t currentMode = hw->getActiveColorMode();
980
981 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 return;
983 }
984
985 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
986 ALOGW("Trying to set config for virtual display");
987 return;
988 }
989
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600990 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
991 hw->getDisplayType());
992
Michael Wright28f24d02016-07-12 13:30:53 -0700993 hw->setActiveColorMode(mode);
994 getHwComposer().setActiveColorMode(type, mode);
995}
996
997
998status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
999 android_color_mode_t colorMode) {
1000 class MessageSetActiveColorMode: public MessageBase {
1001 SurfaceFlinger& mFlinger;
1002 sp<IBinder> mDisplay;
1003 android_color_mode_t mMode;
1004 public:
1005 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1006 android_color_mode_t mode) :
1007 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1008 virtual bool handler() {
1009 Vector<android_color_mode_t> modes;
1010 mFlinger.getDisplayColorModes(mDisplay, &modes);
1011 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1012 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001013 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1014 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001015 return true;
1016 }
1017 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1018 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001019 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1020 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001021 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001022 ALOGW("Attempt to set active color mode %s %d for virtual display",
1023 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001024 } else {
1025 mFlinger.setActiveColorModeInternal(hw, mMode);
1026 }
1027 return true;
1028 }
1029 };
1030 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1031 postMessageSync(msg);
1032 return NO_ERROR;
1033}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001034
Svetoslavd85084b2014-03-20 10:28:31 -07001035status_t SurfaceFlinger::clearAnimationFrameStats() {
1036 Mutex::Autolock _l(mStateLock);
1037 mAnimFrameTracker.clearStats();
1038 return NO_ERROR;
1039}
1040
1041status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1042 Mutex::Autolock _l(mStateLock);
1043 mAnimFrameTracker.getStats(outStats);
1044 return NO_ERROR;
1045}
1046
Dan Stozac4f471e2016-03-24 09:31:08 -07001047status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1048 HdrCapabilities* outCapabilities) const {
1049 Mutex::Autolock _l(mStateLock);
1050
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001051 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001052 if (displayDevice == nullptr) {
1053 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1054 return BAD_VALUE;
1055 }
1056
1057 std::unique_ptr<HdrCapabilities> capabilities =
1058 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1059 if (capabilities) {
1060 std::swap(*outCapabilities, *capabilities);
1061 } else {
1062 return BAD_VALUE;
1063 }
1064
1065 return NO_ERROR;
1066}
1067
Chia-I Wu6200eac2017-10-05 14:24:41 -07001068void SurfaceFlinger::enableVSyncInjectionsInternal(bool enable) {
1069 Mutex::Autolock _l(mStateLock);
1070
1071 if (mInjectVSyncs == enable) {
1072 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 }
1074
1075 if (enable) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 ALOGV("VSync Injections enabled");
1077 if (mVSyncInjector.get() == nullptr) {
1078 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001079 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001080 }
1081 mEventQueue.setEventThread(mInjectorEventThread);
1082 } else {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 ALOGV("VSync Injections disabled");
1084 mEventQueue.setEventThread(mSFEventThread);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 }
Chia-I Wu6200eac2017-10-05 14:24:41 -07001086
1087 mInjectVSyncs = enable;
1088}
1089
1090status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1091 class MessageEnableVSyncInjections : public MessageBase {
1092 SurfaceFlinger* mFlinger;
1093 bool mEnable;
1094 public:
1095 MessageEnableVSyncInjections(SurfaceFlinger* flinger, bool enable)
1096 : mFlinger(flinger), mEnable(enable) { }
1097 virtual bool handler() {
1098 mFlinger->enableVSyncInjectionsInternal(mEnable);
1099 return true;
1100 }
1101 };
1102 sp<MessageBase> msg = new MessageEnableVSyncInjections(this, enable);
1103 postMessageSync(msg);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001104 return NO_ERROR;
1105}
1106
1107status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu6200eac2017-10-05 14:24:41 -07001108 Mutex::Autolock _l(mStateLock);
1109
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001110 if (!mInjectVSyncs) {
1111 ALOGE("VSync Injections not enabled");
1112 return BAD_VALUE;
1113 }
1114 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1115 ALOGV("Injecting VSync inside SurfaceFlinger");
1116 mVSyncInjector->onInjectSyncEvent(when);
1117 }
1118 return NO_ERROR;
1119}
1120
Kalle Raitaa099a242017-01-11 11:17:29 -08001121status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1122 IPCThreadState* ipc = IPCThreadState::self();
1123 const int pid = ipc->getCallingPid();
1124 const int uid = ipc->getCallingUid();
1125 if ((uid != AID_SHELL) &&
1126 !PermissionCache::checkPermission(sDump, pid, uid)) {
1127 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1128 return PERMISSION_DENIED;
1129 }
1130
1131 // Try to acquire a lock for 1s, fail gracefully
1132 const status_t err = mStateLock.timedLock(s2ns(1));
1133 const bool locked = (err == NO_ERROR);
1134 if (!locked) {
1135 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1136 return TIMED_OUT;
1137 }
1138
1139 outLayers->clear();
1140 mCurrentState.traverseInZOrder([&](Layer* layer) {
1141 outLayers->push_back(layer->getLayerDebugInfo());
1142 });
1143
1144 mStateLock.unlock();
1145 return NO_ERROR;
1146}
1147
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001148// ----------------------------------------------------------------------------
1149
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001150sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1151 ISurfaceComposer::VsyncSource vsyncSource) {
1152 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1153 return mSFEventThread->createEventConnection();
1154 } else {
1155 return mEventThread->createEventConnection();
1156 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001157}
1158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160
1161void SurfaceFlinger::waitForEvent() {
1162 mEventQueue.waitMessage();
1163}
1164
1165void SurfaceFlinger::signalTransaction() {
1166 mEventQueue.invalidate();
1167}
1168
1169void SurfaceFlinger::signalLayerUpdate() {
1170 mEventQueue.invalidate();
1171}
1172
1173void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001174 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001175 mEventQueue.refresh();
1176}
1177
1178status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001179 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180 return mEventQueue.postMessage(msg, reltime);
1181}
1182
1183status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001184 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001185 status_t res = mEventQueue.postMessage(msg, reltime);
1186 if (res == NO_ERROR) {
1187 msg->wait();
1188 }
1189 return res;
1190}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001191
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001192void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001193 do {
1194 waitForEvent();
1195 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001196}
1197
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198void SurfaceFlinger::enableHardwareVsync() {
1199 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1203 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001205 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206}
1207
Jesse Hall948fe0c2013-10-14 12:56:09 -07001208void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 Mutex::Autolock _l(mHWVsyncLock);
1210
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211 if (makeAvailable) {
1212 mHWVsyncAvailable = true;
1213 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001214 // Hardware vsync is not currently available, so abort the resync
1215 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216 return;
1217 }
1218
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1220 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
1222 mPrimaryDispSync.reset();
1223 mPrimaryDispSync.setPeriod(period);
1224
1225 if (!mPrimaryHWVsyncEnabled) {
1226 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001227 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1228 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229 mPrimaryHWVsyncEnabled = true;
1230 }
1231}
1232
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234 Mutex::Autolock _l(mHWVsyncLock);
1235 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001236 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1237 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238 mPrimaryDispSync.endResync();
1239 mPrimaryHWVsyncEnabled = false;
1240 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001241 if (makeUnavailable) {
1242 mHWVsyncAvailable = false;
1243 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244}
1245
Tim Murray4a4e4a22016-04-19 16:29:23 +00001246void SurfaceFlinger::resyncWithRateLimit() {
1247 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001248
1249 // No explicit locking is needed here since EventThread holds a lock while calling this method
1250 static nsecs_t sLastResyncAttempted = 0;
1251 const nsecs_t now = systemTime();
1252 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001253 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001254 }
Dan Stoza57164302017-05-08 14:03:54 -07001255 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001256}
1257
Steven Thomasb02664d2017-07-26 18:48:28 -07001258void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1259 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001260 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001261 // Ignore any vsyncs from a previous hardware composer.
1262 if (sequenceId != mComposerSequenceId) {
1263 return;
1264 }
1265
1266 int32_t type;
1267 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001268 return;
1269 }
1270
Jamie Gennisd1700752013-10-14 12:22:52 -07001271 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272
Jamie Gennisd1700752013-10-14 12:22:52 -07001273 { // Scope for the lock
1274 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001278 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001279
1280 if (needsHwVsync) {
1281 enableHardwareVsync();
1282 } else {
1283 disableHardwareVsync(false);
1284 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001285}
1286
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001287void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001288 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001289 *compositorTiming = mCompositorTiming;
1290}
1291
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001293 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001294 wp<IBinder> token = mBuiltinDisplays[type];
1295
1296 // All non-virtual displays are currently considered secure.
1297 const bool isSecure = true;
1298
1299 sp<IGraphicBufferProducer> producer;
1300 sp<IGraphicBufferConsumer> consumer;
1301 BufferQueue::createBufferQueue(&producer, &consumer);
1302
1303 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1304
1305 bool hasWideColorModes = false;
1306 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1307 for (android_color_mode_t colorMode : modes) {
1308 switch (colorMode) {
1309 case HAL_COLOR_MODE_DISPLAY_P3:
1310 case HAL_COLOR_MODE_ADOBE_RGB:
1311 case HAL_COLOR_MODE_DCI_P3:
1312 hasWideColorModes = true;
1313 break;
1314 default:
1315 break;
1316 }
1317 }
Romain Guy54f154a2017-10-24 21:40:32 +01001318 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1320 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001321 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001323 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001324 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001325 defaultColorMode = HAL_COLOR_MODE_SRGB;
1326 }
1327 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001328 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329
1330 // Add the primary display token to mDrawingState so we don't try to
1331 // recreate the DisplayDevice for the primary display.
1332 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1333
1334 // make the GLContext current so that we can create textures when creating
1335 // Layers (which may happens before we render something)
1336 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337}
1338
Steven Thomasb02664d2017-07-26 18:48:28 -07001339void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1340 hwc2_display_t display, HWC2::Connection connection,
1341 bool primaryDisplay) {
1342 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1343 sequenceId, display,
1344 connection == HWC2::Connection::Connected ?
1345 "connected" : "disconnected",
1346 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 // Only lock if we're not on the main thread. This function is normally
1349 // called on a hwbinder thread, but for the primary display it's called on
1350 // the main thread with the state lock already held, so don't attempt to
1351 // acquire it here.
1352 ConditionalLock lock(mStateLock,
1353 std::this_thread::get_id() != mMainThreadId);
1354
1355 if (primaryDisplay) {
1356 mHwc->onHotplug(display, connection);
1357 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1358 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 if (sequenceId != mComposerSequenceId) {
1363 return;
1364 }
1365 if (mHwc->isUsingVrComposer()) {
1366 ALOGE("External displays are not supported by the vr hardware composer.");
1367 return;
1368 }
1369 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001373 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001374 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1375 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001376 }
1377 setTransactionFlags(eDisplayTransactionNeeded);
1378
Andy McFadden9e9689c2012-10-10 18:17:51 -07001379 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001380 }
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId,
1384 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001385 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 if (sequenceId != mComposerSequenceId) {
1387 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001389 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001390}
1391
Dan Stoza9e56aa02015-11-02 13:00:03 -08001392void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001393 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395 getHwComposer().setVsyncEnabled(disp,
1396 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001397}
1398
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001400void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 // Clear the drawing state so that the logic inside of
1403 // handleTransactionLocked will fire. It will determine the delta between
1404 // mCurrentState and mDrawingState and re-apply all changes when we make the
1405 // transition.
1406 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408 mDisplays.clear();
1409}
1410
Steven Thomas050b2c82017-03-06 11:45:16 -08001411void SurfaceFlinger::updateVrFlinger() {
1412 if (!mVrFlinger)
1413 return;
1414 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1415 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 return;
1417 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1420 ALOGE("Vr flinger is only supported for remote hardware composer"
1421 " service connections. Ignoring request to transition to vr"
1422 " flinger.");
1423 mVrFlingerRequestsDisplay = false;
1424 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001427 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 int currentDisplayPowerMode = getDisplayDeviceLocked(
1430 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 resetDisplayState();
1437 mHwc.reset(); // Delete the current instance before creating the new one
1438 mHwc.reset(new HWComposer(
1439 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1440 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1443 "Switched to non-remote hardware composer");
1444
1445 if (vrFlingerRequestsDisplay) {
1446 mVrFlinger->GrantDisplayOwnership();
1447 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
1451 mVisibleRegionsDirty = true;
1452 invalidateHwcGeometry();
1453
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1456 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1457 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 // Reset the timing values to account for the period of the swapped in HWC
1460 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1461 const nsecs_t period = activeConfig->getVsyncPeriod();
1462 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Use phase of 0 since phase is not known.
1465 // Use latency of 0, which will snap to the ideal latency.
1466 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001467
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001468 android_atomic_or(1, &mRepaintEverything);
1469 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470}
1471
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001473 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001474 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001476 bool frameMissed = !mHadClientComposition &&
1477 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478 (mPreviousPresentFence->getSignalTime() ==
1479 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001480 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001481 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001482 signalLayerUpdate();
1483 break;
1484 }
1485
Steven Thomas050b2c82017-03-06 11:45:16 -08001486 // Now that we're going to make it to the handleMessageTransaction()
1487 // call below it's safe to call updateVrFlinger(), which will
1488 // potentially trigger a display handoff.
1489 updateVrFlinger();
1490
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 bool refreshNeeded = handleMessageTransaction();
1492 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001493 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001494 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001495 // Signal a refresh if a transaction modified the window state,
1496 // a new buffer was latched, or if HWC has requested a full
1497 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 signalRefresh();
1499 }
1500 break;
1501 }
1502 case MessageQueue::REFRESH: {
1503 handleMessageRefresh();
1504 break;
1505 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506 }
1507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001510 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001512 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516}
1517
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
1523void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001525
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001526 mRefreshPending = false;
1527
Pablo Ceballos40845df2016-01-25 17:41:15 -08001528 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001529
Brian Andersond6927fb2016-07-23 23:37:30 -07001530 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531 rebuildLayerStacks();
1532 setUpHWComposer();
1533 doDebugFlashRegions();
1534 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001537 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538
1539 mHadClientComposition = false;
1540 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1541 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1542 mHadClientComposition = mHadClientComposition ||
1543 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1544 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001545
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549void SurfaceFlinger::doDebugFlashRegions()
1550{
1551 // is debugging enabled
1552 if (CC_LIKELY(!mDebugRegion))
1553 return;
1554
1555 const bool repaintEverything = mRepaintEverything;
1556 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1557 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001558 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 // transform the dirty region into this screen's coordinate space
1560 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1561 if (!dirtyRegion.isEmpty()) {
1562 // redraw the whole screen
1563 doComposeSurfaces(hw, Region(hw->bounds()));
1564
1565 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001567 RenderEngine& engine(getRenderEngine());
1568 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1569
Mathias Agopianda27af92012-09-13 18:17:13 -07001570 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 }
1572 }
1573 }
1574
1575 postFramebuffer();
1576
1577 if (mDebugRegion > 1) {
1578 usleep(mDebugRegion * 1000);
1579 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001580
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001582 auto& displayDevice = mDisplays[displayId];
1583 if (!displayDevice->isDisplayOn()) {
1584 continue;
1585 }
1586
1587 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001588 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1589 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001590 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591}
1592
Brian Andersond6927fb2016-07-23 23:37:30 -07001593void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 ATRACE_CALL();
1596 ALOGV("preComposition");
1597
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001599 mDrawingState.traverseInZOrder([&](Layer* layer) {
1600 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601 needExtraInvalidate = true;
1602 }
Robert Carr2047fae2016-11-28 14:09:09 -08001603 });
1604
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 if (needExtraInvalidate) {
1606 signalLayerUpdate();
1607 }
1608}
1609
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610void SurfaceFlinger::updateCompositorTiming(
1611 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1612 std::shared_ptr<FenceTime>& presentFenceTime) {
1613 // Update queue of past composite+present times and determine the
1614 // most recently known composite to present latency.
1615 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1616 nsecs_t compositeToPresentLatency = -1;
1617 while (!mCompositePresentTimes.empty()) {
1618 CompositePresentTime& cpt = mCompositePresentTimes.front();
1619 // Cached values should have been updated before calling this method,
1620 // which helps avoid duplicate syscalls.
1621 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1622 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1623 break;
1624 }
1625 compositeToPresentLatency = displayTime - cpt.composite;
1626 mCompositePresentTimes.pop();
1627 }
1628
1629 // Don't let mCompositePresentTimes grow unbounded, just in case.
1630 while (mCompositePresentTimes.size() > 16) {
1631 mCompositePresentTimes.pop();
1632 }
1633
Brian Andersond0010582017-03-07 13:20:31 -08001634 setCompositorTimingSnapped(
1635 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1636}
1637
1638void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1639 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Integer division and modulo round toward 0 not -inf, so we need to
1641 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001642 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1644 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1645
Brian Andersond0010582017-03-07 13:20:31 -08001646 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1647 if (idealLatency <= 0) {
1648 idealLatency = vsyncInterval;
1649 }
1650
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 // Snap the latency to a value that removes scheduling jitter from the
1652 // composition and present times, which often have >1ms of jitter.
1653 // Reducing jitter is important if an app attempts to extrapolate
1654 // something (such as user input) to an accurate diasplay time.
1655 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1656 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001657 nsecs_t bias = vsyncInterval / 2;
1658 int64_t extraVsyncs =
1659 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1660 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1661 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662
Brian Andersond0010582017-03-07 13:20:31 -08001663 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1665 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001666 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667}
1668
1669void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 ATRACE_CALL();
1672 ALOGV("postComposition");
1673
Brian Anderson3546a3f2016-07-14 11:51:14 -07001674 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001675 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001676 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001677 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001678 }
1679
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680 // |mStateLock| not needed as we are on the main thread
1681 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001682
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001683 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001684 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1685 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1686 glCompositionDoneFenceTime =
1687 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1688 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1689 } else {
1690 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1691 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001692
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001693 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1695 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1696 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1699 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1700
1701 // We use the refreshStartTime which might be sampled a little later than
1702 // when we started doing work for this frame, but that should be okay
1703 // since updateCompositorTiming has snapping logic.
1704 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001706 CompositorTiming compositorTiming;
1707 {
1708 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1709 compositorTiming = mCompositorTiming;
1710 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711
Robert Carr2047fae2016-11-28 14:09:09 -08001712 mDrawingState.traverseInZOrder([&](Layer* layer) {
1713 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001714 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001715 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001716 recordBufferingStats(layer->getName().string(),
1717 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001718 }
Robert Carr2047fae2016-11-28 14:09:09 -08001719 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001720
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001721 if (presentFenceTime->isValid()) {
1722 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001723 enableHardwareVsync();
1724 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001725 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001726 }
1727 }
1728
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001729 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001730 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001731 enableHardwareVsync();
1732 }
1733 }
1734
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 if (mAnimCompositionPending) {
1736 mAnimCompositionPending = false;
1737
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001739 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001740 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001741 } else {
1742 // The HWC doesn't support present fences, so use the refresh
1743 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 nsecs_t presentTime =
1745 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001746 mAnimFrameTracker.setActualPresentTime(presentTime);
1747 }
1748 mAnimFrameTracker.advanceFrame();
1749 }
Dan Stozab90cf072015-03-05 11:05:59 -08001750
1751 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1752 return;
1753 }
1754
1755 nsecs_t currentTime = systemTime();
1756 if (mHasPoweredOff) {
1757 mHasPoweredOff = false;
1758 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001759 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001760 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001761 if (numPeriods < NUM_BUCKETS - 1) {
1762 mFrameBuckets[numPeriods] += elapsedTime;
1763 } else {
1764 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1765 }
1766 mTotalTime += elapsedTime;
1767 }
1768 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769}
1770
1771void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 ATRACE_CALL();
1773 ALOGV("rebuildLayerStacks");
1774
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1777 ATRACE_CALL();
1778 mVisibleRegionsDirty = false;
1779 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001780
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1782 Region opaqueRegion;
1783 Region dirtyRegion;
1784 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001785 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001786 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1787 const Transform& tr(displayDevice->getTransform());
1788 const Rect bounds(displayDevice->getBounds());
1789 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001790 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001791
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001793 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001794 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1795 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001796 Region drawRegion(tr.transform(
1797 layer->visibleNonTransparentRegion));
1798 drawRegion.andSelf(bounds);
1799 if (!drawRegion.isEmpty()) {
1800 layersSortedByZ.add(layer);
1801 } else {
1802 // Clear out the HWC layer if this layer was
1803 // previously visible, but no longer is
Chia-I Wu92257612017-11-20 10:43:41 -08001804 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001805 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001806 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001807 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001808 // WM changes displayDevice->layerStack upon sleep/awake.
1809 // Here we make sure we delete the HWC layers even if
1810 // WM changed their layer stack.
Chia-I Wu92257612017-11-20 10:43:41 -08001811 hwcLayerDestroyed = layer->destroyHwcLayer(
1812 displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001813 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001814
1815 // If a layer is not going to get a release fence because
1816 // it is invisible, but it is also going to release its
1817 // old buffer, add it to the list of layers needing
1818 // fences.
1819 if (hwcLayerDestroyed) {
1820 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1821 mLayersWithQueuedFrames.cend(), layer);
1822 if (found != mLayersWithQueuedFrames.cend()) {
1823 layersNeedingFences.add(layer);
1824 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 });
1827 }
1828 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001829 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 displayDevice->undefinedRegion.set(bounds);
1831 displayDevice->undefinedRegion.subtractSelf(
1832 tr.transform(opaqueRegion));
1833 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001835 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001837
Romain Guy0147a172017-06-01 13:53:56 -07001838mat4 SurfaceFlinger::computeSaturationMatrix() const {
1839 if (mSaturation == 1.0f) {
1840 return mat4();
1841 }
1842
1843 // Rec.709 luma coefficients
1844 float3 luminance{0.213f, 0.715f, 0.072f};
1845 luminance *= 1.0f - mSaturation;
1846 return mat4(
1847 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1848 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1849 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1850 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1851 );
1852}
1853
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001854// pickColorMode translates a given dataspace into the best available color mode.
1855// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001856android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001857 if (mForceNativeColorMode) {
1858 return HAL_COLOR_MODE_NATIVE;
1859 }
1860
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001861 switch (dataSpace) {
1862 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1863 // system expects.
1864 case HAL_DATASPACE_UNKNOWN:
1865 case HAL_DATASPACE_SRGB:
1866 case HAL_DATASPACE_V0_SRGB:
1867 return HAL_COLOR_MODE_SRGB;
1868 break;
1869
1870 case HAL_DATASPACE_DISPLAY_P3:
1871 return HAL_COLOR_MODE_DISPLAY_P3;
1872 break;
1873
1874 default:
1875 // TODO (courtneygo): Do we want to assert an error here?
1876 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1877 dataSpace);
1878 return HAL_COLOR_MODE_SRGB;
1879 break;
1880 }
1881}
1882
Romain Guy0147a172017-06-01 13:53:56 -07001883android_dataspace SurfaceFlinger::bestTargetDataSpace(
1884 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001885 // Only support sRGB and Display-P3 right now.
1886 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1887 return HAL_DATASPACE_DISPLAY_P3;
1888 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001889 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1890 return HAL_DATASPACE_DISPLAY_P3;
1891 }
1892 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1893 return HAL_DATASPACE_DISPLAY_P3;
1894 }
1895
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896 return HAL_DATASPACE_V0_SRGB;
1897}
1898
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 ATRACE_CALL();
1901 ALOGV("setUpHWComposer");
1902
Jesse Hall028dc8f2013-08-20 16:35:32 -07001903 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001904 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1905 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1906 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1907
1908 // If nothing has changed (!dirty), don't recompose.
1909 // If something changed, but we don't currently have any visible layers,
1910 // and didn't when we last did a composition, then skip it this time.
1911 // The second rule does two things:
1912 // - When all layers are removed from a display, we'll emit one black
1913 // frame, then nothing more until we get new layers.
1914 // - When a display is created with a private layer stack, we won't
1915 // emit any black frames until a layer is added to the layer stack.
1916 bool mustRecompose = dirty && !(empty && wasEmpty);
1917
1918 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1919 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1920 mustRecompose ? "doing" : "skipping",
1921 dirty ? "+" : "-",
1922 empty ? "+" : "-",
1923 wasEmpty ? "+" : "-");
1924
Dan Stoza71433162014-02-04 16:22:36 -08001925 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001926
1927 if (mustRecompose) {
1928 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1929 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001930 }
1931
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 // build the h/w work list
1933 if (CC_UNLIKELY(mGeometryInvalid)) {
1934 mGeometryInvalid = false;
1935 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1936 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1937 const auto hwcId = displayDevice->getHwcDisplayId();
1938 if (hwcId >= 0) {
1939 const Vector<sp<Layer>>& currentLayers(
1940 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001941 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001942 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001944 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001947 }
1948 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001949
Robert Carrae060832016-11-28 10:51:00 -08001950 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001951 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001953 }
1954 }
1955 }
1956 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 }
Riley Andrews03414a12014-07-01 14:22:59 -07001958
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001959
Romain Guy0147a172017-06-01 13:53:56 -07001960 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001961
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 // Set the per-frame data
1963 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1964 auto& displayDevice = mDisplays[displayId];
1965 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001966
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 if (hwcId < 0) {
1968 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001969 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001970 if (colorMatrix != mPreviousColorMatrix) {
1971 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1972 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1973 "display %zd: %d", displayId, result);
1974 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1976 layer->setPerFrameData(displayDevice);
1977 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001978
1979 if (hasWideColorDisplay) {
1980 android_color_mode newColorMode;
1981 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1982
1983 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1984 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1985 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1986 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1987 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1988 }
1989 newColorMode = pickColorMode(newDataSpace);
1990
Thierry Strudel2924d012017-08-14 15:19:37 -07001991 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001992 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 }
1994
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001995 mPreviousColorMatrix = colorMatrix;
1996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001998 auto& displayDevice = mDisplays[displayId];
1999 if (!displayDevice->isDisplayOn()) {
2000 continue;
2001 }
2002
2003 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2005 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002006 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002008
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009void SurfaceFlinger::doComposition() {
2010 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ALOGV("doComposition");
2012
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002013 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002014 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002015 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002016 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 // transform the dirty region into this screen's coordinate space
2018 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002019
2020 // repaint the framebuffer (if needed)
2021 doDisplayComposition(hw, dirtyRegion);
2022
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 hw->dirtyRegion.clear();
2024 hw->flip(hw->swapRegion);
2025 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002026 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002027 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002028 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029}
2030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031void SurfaceFlinger::postFramebuffer()
2032{
Mathias Agopian841cde52012-03-01 15:44:37 -08002033 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002035
Mathias Agopiana44b0412011-10-16 18:46:35 -07002036 const nsecs_t now = systemTime();
2037 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002038
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2040 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002041 if (!displayDevice->isDisplayOn()) {
2042 continue;
2043 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 const auto hwcId = displayDevice->getHwcDisplayId();
2045 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002046 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002047 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002048 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07002049 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002051 // The layer buffer from the previous frame (if any) is released
2052 // by HWC only when the release fence from this frame (if any) is
2053 // signaled. Always get the release fence from HWC first.
2054 auto hwcLayer = layer->getHwcLayer(hwcId);
2055 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2056
2057 // If the layer was client composited in the previous frame, we
2058 // need to merge with the previous client target acquire fence.
2059 // Since we do not track that, always merge with the current
2060 // client target acquire fence when it is available, even though
2061 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002063 releaseFence = Fence::merge("LayerRelease", releaseFence,
2064 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002065 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 layer->onLayerDisplayed(releaseFence);
2068 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08002069
2070 // We've got a list of layers needing fences, that are disjoint with
2071 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2072 // supply them with the present fence.
2073 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2074 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2075 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2076 layer->onLayerDisplayed(presentFence);
2077 }
2078 }
2079
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 if (hwcId >= 0) {
2081 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002082 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002083 }
2084
Mathias Agopiana44b0412011-10-16 18:46:35 -07002085 mLastSwapBufferTime = systemTime() - now;
2086 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002087
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002088 // |mStateLock| not needed as we are on the main thread
2089 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002090 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2091 logFrameStats();
2092 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093}
2094
Mathias Agopian87baae12012-07-31 12:38:26 -07002095void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002096{
Mathias Agopian841cde52012-03-01 15:44:37 -08002097 ATRACE_CALL();
2098
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002099 // here we keep a copy of the drawing state (that is the state that's
2100 // going to be overwritten by handleTransactionLocked()) outside of
2101 // mStateLock so that the side-effects of the State assignment
2102 // don't happen with mStateLock held (which can cause deadlocks).
2103 State drawingState(mDrawingState);
2104
Mathias Agopianca4d3602011-05-19 15:38:14 -07002105 Mutex::Autolock _l(mStateLock);
2106 const nsecs_t now = systemTime();
2107 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108
Mathias Agopianca4d3602011-05-19 15:38:14 -07002109 // Here we're guaranteed that some transaction flags are set
2110 // so we can call handleTransactionLocked() unconditionally.
2111 // We call getTransactionFlags(), which will also clear the flags,
2112 // with mStateLock held to guarantee that mCurrentState won't change
2113 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002114
Mathias Agopiane57f2922012-08-09 16:29:12 -07002115 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002117
Mathias Agopianca4d3602011-05-19 15:38:14 -07002118 mLastTransactionTime = systemTime() - now;
2119 mDebugInTransaction = 0;
2120 invalidateHwcGeometry();
2121 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002122}
2123
Mathias Agopian87baae12012-07-31 12:38:26 -07002124void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002125{
Dan Stoza7dde5992015-05-22 09:51:44 -07002126 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002127 mCurrentState.traverseInZOrder([](Layer* layer) {
2128 layer->notifyAvailableFrames();
2129 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 /*
2132 * Traversal of the children
2133 * (perform the transaction for each of them if needed)
2134 */
2135
Mathias Agopian3559b072012-08-15 13:46:03 -07002136 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002137 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002139 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140
2141 const uint32_t flags = layer->doTransaction(0);
2142 if (flags & Layer::eVisibleRegion)
2143 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002144 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002145 }
2146
2147 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002148 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 */
2150
Mathias Agopiane57f2922012-08-09 16:29:12 -07002151 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002152 // here we take advantage of Vector's copy-on-write semantics to
2153 // improve performance by skipping the transaction entirely when
2154 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002155 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2156 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002157 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002158 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002159 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002160 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002161
2162 // find the displays that were removed
2163 // (ie: in drawing state but not in current state)
2164 // also handle displays that changed
2165 // (ie: displays that are in both lists)
2166 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2168 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002169 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002170 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002171 // Call makeCurrent() on the primary display so we can
2172 // be sure that nothing associated with this display
2173 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002174 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002175 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002176 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002177 if (hw != NULL)
2178 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002179 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002180 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002181 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002182 } else {
2183 ALOGW("trying to remove the main display");
2184 }
2185 } else {
2186 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002188 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002189 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2190 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002191 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002192 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002193 // recreating the DisplayDevice, so we just remove it
2194 // from the drawing state, so that it get re-added
2195 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002196 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002197 if (hw != NULL)
2198 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002199 mDisplays.removeItem(display);
2200 mDrawingState.displays.removeItemsAt(i);
2201 dc--; i--;
2202 // at this point we must loop to the next item
2203 continue;
2204 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002205
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002206 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002207 if (disp != NULL) {
2208 if (state.layerStack != draw[i].layerStack) {
2209 disp->setLayerStack(state.layerStack);
2210 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002211 if ((state.orientation != draw[i].orientation)
2212 || (state.viewport != draw[i].viewport)
2213 || (state.frame != draw[i].frame))
2214 {
2215 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002216 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002217 }
Michael Lentine47e45402014-07-18 15:34:25 -07002218 if (state.width != draw[i].width || state.height != draw[i].height) {
2219 disp->setDisplaySize(state.width, state.height);
2220 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002221 }
2222 }
2223 }
2224
2225 // find displays that were added
2226 // (ie: in current state but not in drawing state)
2227 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002228 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002229 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002230
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002231 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002232 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002233 sp<IGraphicBufferProducer> bqProducer;
2234 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002235 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002236
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002238 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002239 // Virtual displays without a surface are dormant:
2240 // they have external state (layer stack, projection,
2241 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002242 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002243
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002244 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002245 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002246 int width = 0;
2247 int status = state.surface->query(
2248 NATIVE_WINDOW_WIDTH, &width);
2249 ALOGE_IF(status != NO_ERROR,
2250 "Unable to query width (%d)", status);
2251 int height = 0;
2252 status = state.surface->query(
2253 NATIVE_WINDOW_HEIGHT, &height);
2254 ALOGE_IF(status != NO_ERROR,
2255 "Unable to query height (%d)", status);
2256 int intFormat = 0;
2257 status = state.surface->query(
2258 NATIVE_WINDOW_FORMAT, &intFormat);
2259 ALOGE_IF(status != NO_ERROR,
2260 "Unable to query format (%d)", status);
2261 auto format = static_cast<android_pixel_format_t>(
2262 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002263
Dan Stoza8cf150a2016-08-02 10:27:31 -07002264 mHwc->allocateVirtualDisplay(width, height, &format,
2265 &hwcId);
2266 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267
Dan Stoza5cf424b2016-05-20 14:02:39 -07002268 // TODO: Plumb requested format back up to consumer
2269
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 sp<VirtualDisplaySurface> vds =
2271 new VirtualDisplaySurface(*mHwc,
2272 hwcId, state.surface, bqProducer,
2273 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002274
2275 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002276 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002277 }
2278 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002279 ALOGE_IF(state.surface!=NULL,
2280 "adding a supported display, but rendering "
2281 "surface is provided (%p), ignoring it",
2282 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002283
2284 hwcId = state.type;
2285 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2286 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002287 }
2288
2289 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002290 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002291 sp<DisplayDevice> hw =
2292 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2293 dispSurface, producer,
2294 mRenderEngine->getEGLConfig(),
2295 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002296 hw->setLayerStack(state.layerStack);
2297 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002298 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002299 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002300 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002302 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002303 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002304 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002305 }
2306 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309
Mathias Agopian84300952012-11-21 16:02:13 -08002310 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2311 // The transform hint might have changed for some layers
2312 // (either because a display has changed, or because a layer
2313 // as changed).
2314 //
2315 // Walk through all the layers in currentLayers,
2316 // and update their transform hint.
2317 //
2318 // If a layer is visible only on a single display, then that
2319 // display is used to calculate the hint, otherwise we use the
2320 // default display.
2321 //
2322 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2323 // the hint is set before we acquire a buffer from the surface texture.
2324 //
2325 // NOTE: layer transactions have taken place already, so we use their
2326 // drawing state. However, SurfaceFlinger's own transaction has not
2327 // happened yet, so we must use the current state layer list
2328 // (soon to become the drawing state list).
2329 //
2330 sp<const DisplayDevice> disp;
2331 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002332 bool first = true;
2333 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002334 // NOTE: we rely on the fact that layers are sorted by
2335 // layerStack first (so we don't have to traverse the list
2336 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002337 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002338 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002339 currentlayerStack = layerStack;
2340 // figure out if this layerstack is mirrored
2341 // (more than one display) if so, pick the default display,
2342 // if not, pick the only display it's on.
2343 disp.clear();
2344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2345 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002346 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002347 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002348 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002349 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002350 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002351 break;
2352 }
2353 }
2354 }
2355 }
Chet Haase91d25932013-04-11 15:24:55 -07002356 if (disp == NULL) {
2357 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2358 // redraw after transform hint changes. See bug 8508397.
2359
2360 // could be null when this layer is using a layerStack
2361 // that is not visible on any display. Also can occur at
2362 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002363 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002364 }
Chet Haase91d25932013-04-11 15:24:55 -07002365 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002366
2367 first = false;
2368 });
Mathias Agopian84300952012-11-21 16:02:13 -08002369 }
2370
2371
Mathias Agopian3559b072012-08-15 13:46:03 -07002372 /*
2373 * Perform our own transaction if needed
2374 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002375
2376 if (mLayersAdded) {
2377 mLayersAdded = false;
2378 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002379 mVisibleRegionsDirty = true;
2380 }
2381
2382 // some layers might have been removed, so
2383 // we need to update the regions they're exposing.
2384 if (mLayersRemoved) {
2385 mLayersRemoved = false;
2386 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002387 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002388 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002389 // this layer is not visible anymore
2390 // TODO: we could traverse the tree from front to back and
2391 // compute the actual visible region
2392 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002393 Region visibleReg;
2394 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002395 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002396 }
Robert Carr2047fae2016-11-28 14:09:09 -08002397 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398 }
2399
2400 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002401
2402 updateCursorAsync();
2403}
2404
2405void SurfaceFlinger::updateCursorAsync()
2406{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2408 auto& displayDevice = mDisplays[displayId];
2409 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002410 continue;
2411 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412
2413 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2414 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002415 }
2416 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002417}
2418
2419void SurfaceFlinger::commitTransaction()
2420{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002421 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002423 for (const auto& l : mLayersPendingRemoval) {
2424 recordBufferingStats(l->getName().string(),
2425 l->getOccupancyHistory(true));
2426 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 }
2428 mLayersPendingRemoval.clear();
2429 }
2430
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002431 // If this transaction is part of a window animation then the next frame
2432 // we composite should be considered an animation as well.
2433 mAnimCompositionPending = mAnimTransactionPending;
2434
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002436 mDrawingState.traverseInZOrder([](Layer* layer) {
2437 layer->commitChildList();
2438 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002439 mTransactionPending = false;
2440 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002441 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442}
2443
Chia-I Wuab0c3192017-08-01 11:29:00 -07002444void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002445 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446{
Mathias Agopian841cde52012-03-01 15:44:37 -08002447 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002449
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 Region aboveOpaqueLayers;
2451 Region aboveCoveredLayers;
2452 Region dirty;
2453
Mathias Agopian87baae12012-07-31 12:38:26 -07002454 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Robert Carr2047fae2016-11-28 14:09:09 -08002456 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002458 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459
Jesse Hall01e29052013-02-19 16:13:35 -08002460 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002461 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002462 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002463
Mathias Agopianab028732010-03-16 16:41:46 -07002464 /*
2465 * opaqueRegion: area of a surface that is fully opaque.
2466 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002468
2469 /*
2470 * visibleRegion: area of a surface that is visible on screen
2471 * and not fully transparent. This is essentially the layer's
2472 * footprint minus the opaque regions above it.
2473 * Areas covered by a translucent surface are considered visible.
2474 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002476
2477 /*
2478 * coveredRegion: area of a surface that is covered by all
2479 * visible regions above it (which includes the translucent areas).
2480 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002482
Jesse Halla8026d22012-09-25 13:25:04 -07002483 /*
2484 * transparentRegion: area of a surface that is hinted to be completely
2485 * transparent. This is only used to tell when the layer has no visible
2486 * non-transparent regions and can be removed from the layer list. It
2487 * does not affect the visibleRegion of this layer or any layers
2488 * beneath it. The hint may not be correct if apps don't respect the
2489 * SurfaceView restrictions (which, sadly, some don't).
2490 */
2491 Region transparentRegion;
2492
Mathias Agopianab028732010-03-16 16:41:46 -07002493
2494 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002495 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002496 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002497 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002499 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002500 if (!visibleRegion.isEmpty()) {
2501 // Remove the transparent area from the visible region
2502 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002503 if (tr.preserveRects()) {
2504 // transform the transparent region
2505 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002506 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002507 // transformation too complex, can't do the
2508 // transparent region optimization.
2509 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002510 }
Mathias Agopianab028732010-03-16 16:41:46 -07002511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Mathias Agopianab028732010-03-16 16:41:46 -07002513 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002516 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2517 // the opaque region is the layer's footprint
2518 opaqueRegion = visibleRegion;
2519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 }
2521 }
2522
Mathias Agopianab028732010-03-16 16:41:46 -07002523 // Clip the covered region to the visible region
2524 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2525
2526 // Update aboveCoveredLayers for next (lower) layer
2527 aboveCoveredLayers.orSelf(visibleRegion);
2528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529 // subtract the opaque region covered by the layers above us
2530 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531
2532 // compute this layer's dirty region
2533 if (layer->contentDirty) {
2534 // we need to invalidate the whole region
2535 dirty = visibleRegion;
2536 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002537 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 layer->contentDirty = false;
2539 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002540 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002541 * the exposed region consists of two components:
2542 * 1) what's VISIBLE now and was COVERED before
2543 * 2) what's EXPOSED now less what was EXPOSED before
2544 *
2545 * note that (1) is conservative, we start with the whole
2546 * visible region but only keep what used to be covered by
2547 * something -- which mean it may have been exposed.
2548 *
2549 * (2) handles areas that were not covered by anything but got
2550 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002551 */
Mathias Agopianab028732010-03-16 16:41:46 -07002552 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 const Region oldVisibleRegion = layer->visibleRegion;
2554 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002555 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2556 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 }
2558 dirty.subtractSelf(aboveOpaqueLayers);
2559
2560 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002561 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562
Mathias Agopianab028732010-03-16 16:41:46 -07002563 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002565
Jesse Halla8026d22012-09-25 13:25:04 -07002566 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 layer->setVisibleRegion(visibleRegion);
2568 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002569 layer->setVisibleNonTransparentRegion(
2570 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002571 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572
Mathias Agopian87baae12012-07-31 12:38:26 -07002573 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574}
2575
Chia-I Wuab0c3192017-08-01 11:29:00 -07002576void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002577 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002578 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002579 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002580 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002581 }
2582 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002583}
2584
Dan Stoza6b9454d2014-11-07 16:00:59 -08002585bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("handlePageFlip");
2588
Brian Andersond6927fb2016-07-23 23:37:30 -07002589 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
Mathias Agopian4fec8732012-06-29 14:12:52 -07002591 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002592 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002593 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002594
2595 // Store the set of layers that need updates. This set must not change as
2596 // buffers are being latched, as this could result in a deadlock.
2597 // Example: Two producers share the same command stream and:
2598 // 1.) Layer 0 is latched
2599 // 2.) Layer 0 gets a new frame
2600 // 2.) Layer 1 gets a new frame
2601 // 3.) Layer 1 is latched.
2602 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2603 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002604 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002605 if (layer->hasQueuedFrame()) {
2606 frameQueued = true;
2607 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002608 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002609 } else {
2610 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002611 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002612 } else {
2613 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002614 }
Robert Carr2047fae2016-11-28 14:09:09 -08002615 });
2616
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002618 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002619 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002620 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002621 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002622 newDataLatched = true;
2623 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002624 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002625
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002626 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002627
2628 // If we will need to wake up at some time in the future to deal with a
2629 // queued frame that shouldn't be displayed during this vsync period, wake
2630 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002631 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002632 signalLayerUpdate();
2633 }
2634
2635 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002636 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637}
2638
Mathias Agopianad456f92011-01-13 17:53:01 -08002639void SurfaceFlinger::invalidateHwcGeometry()
2640{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002642}
2643
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002644
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645void SurfaceFlinger::doDisplayComposition(
2646 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002647 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648{
Dan Stoza71433162014-02-04 16:22:36 -08002649 // We only need to actually compose the display if:
2650 // 1) It is being handled by hardware composer, which may need this to
2651 // keep its virtual display state machine in sync, or
2652 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002653 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002654 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002656 return;
2657 }
2658
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 ALOGV("doDisplayComposition");
2660
Mathias Agopian87baae12012-07-31 12:38:26 -07002661 Region dirtyRegion(inDirtyRegion);
2662
Mathias Agopianb8a55602009-06-26 19:06:36 -07002663 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002664 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Fabien Sanglard830b8472016-11-30 16:35:58 -08002666 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002667 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002668 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2669 // takes a rectangle, we must make sure to update that whole
2670 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002671 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002672 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002673 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002674 // We need to redraw the rectangle that will be updated
2675 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002676 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002677 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002678 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002679 } else {
2680 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002681 dirtyRegion.set(displayDevice->bounds());
2682 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 }
2684 }
2685
Fabien Sanglard830b8472016-11-30 16:35:58 -08002686 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002688 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002689 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002690
2691 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002692 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693}
2694
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695bool SurfaceFlinger::doComposeSurfaces(
2696 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002697{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002699
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002701
2702 mat4 oldColorMatrix;
2703 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2704 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2705 if (applyColorMatrix) {
2706 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2707 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2708 }
2709
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2711 if (hasClientComposition) {
2712 ALOGV("hasClientComposition");
2713
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002714#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002715 mRenderEngine->setWideColor(
2716 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2717 mRenderEngine->setColorMode(mForceNativeColorMode ?
2718 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002719#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002721 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002722 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002723 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002724
2725 // |mStateLock| not needed as we are on the main thread
2726 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002727 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2728 }
2729 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002730 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002731
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002732 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2734 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002735 // when using overlays, we assume a fully transparent framebuffer
2736 // NOTE: we could reduce how much we need to clear, for instance
2737 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002738 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002739 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002741 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002742 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002744
2745 // we remove the scissor part
2746 // we're left with the letterbox region
2747 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002749
2750 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002751 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002752
2753 // but limit it to the dirty region
2754 region.andSelf(dirty);
2755
Mathias Agopianb9494d52012-04-18 02:28:45 -07002756 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002757 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002758 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002760 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002761 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002762
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002764 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002765 // scissor on the main display. It should never be needed
2766 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 const Rect& bounds(displayDevice->getBounds());
2768 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002769 if (scissor != bounds) {
2770 // scissor doesn't match the screen's dimensions, so we
2771 // need to clear everything outside of it and enable
2772 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002773
Mathias Agopianf45c5102012-10-24 16:29:17 -07002774 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002775 const uint32_t height = displayDevice->getHeight();
2776 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002777 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002778 }
2779 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002780 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002781
Mathias Agopian85d751c2012-08-29 16:59:24 -07002782 /*
2783 * and then, render the layers targeted at the framebuffer
2784 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002785
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 ALOGV("Rendering client layers");
2787 const Transform& displayTransform = displayDevice->getTransform();
2788 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002789 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 bool firstLayer = true;
2791 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2792 const Region clip(dirty.intersect(
2793 displayTransform.transform(layer->visibleRegion)));
2794 ALOGV("Layer: %s", layer->getName().string());
2795 ALOGV(" Composition type: %s",
2796 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002797 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 switch (layer->getCompositionType(hwcId)) {
2799 case HWC2::Composition::Cursor:
2800 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002801 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002803 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2805 layer->isOpaque(state) && (state.alpha == 1.0f)
2806 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002807 // never clear the very first layer since we're
2808 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002809 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002810 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002811 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002812 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002813 case HWC2::Composition::Client: {
2814 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002815 break;
2816 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002818 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002819 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 } else {
2821 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002822 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002824 }
2825 } else {
2826 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002828 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002830 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002832 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002833 }
2834 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002835
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002836 if (applyColorMatrix) {
2837 getRenderEngine().setupColorTransform(oldColorMatrix);
2838 }
2839
Mathias Agopianf45c5102012-10-24 16:29:17 -07002840 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002842 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Fabien Sanglard830b8472016-11-30 16:35:58 -08002845void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2846 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002847 RenderEngine& engine(getRenderEngine());
2848 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849}
2850
Dan Stoza7d89d062015-04-30 13:29:25 -07002851status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002852 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002853 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854 const sp<Layer>& lbc,
2855 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002856{
Dan Stoza7d89d062015-04-30 13:29:25 -07002857 // add this layer to the current state list
2858 {
2859 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002861 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2862 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002863 return NO_MEMORY;
2864 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 if (parent == nullptr) {
2866 mCurrentState.layersSortedByZ.add(lbc);
2867 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002868 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2869 ALOGE("addClientLayer called with a removed parent");
2870 return NAME_NOT_FOUND;
2871 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 parent->addChild(lbc);
2873 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002874
Dan Stoza7d89d062015-04-30 13:29:25 -07002875 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002876 mLayersAdded = true;
2877 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002878 }
2879
Mathias Agopian96f08192010-06-02 23:28:45 -07002880 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002881 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002882
Dan Stoza7d89d062015-04-30 13:29:25 -07002883 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002884}
2885
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002886status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002887 Mutex::Autolock _l(mStateLock);
2888
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002890 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002891 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002892 if (topLevelOnly) {
2893 return NO_ERROR;
2894 }
2895
Chia-I Wu98f1c102017-05-30 14:54:08 -07002896 sp<Layer> ancestor = p;
2897 while (ancestor->getParent() != nullptr) {
2898 ancestor = ancestor->getParent();
2899 }
2900 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2901 ALOGE("removeLayer called with a layer whose parent has been removed");
2902 return NAME_NOT_FOUND;
2903 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002904
2905 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002906 } else {
2907 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002908 }
2909
Robert Carr136e2f62017-02-08 17:54:29 -08002910 // As a matter of normal operation, the LayerCleaner will produce a second
2911 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2912 // so we will succeed in promoting it, but it's already been removed
2913 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2914 // otherwise something has gone wrong and we are leaking the layer.
2915 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2917 layer->getName().string(),
2918 (p != nullptr) ? p->getName().string() : "no-parent");
2919 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002920 } else if (index < 0) {
2921 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002922 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923
Chia-I Wuc6657022017-08-15 11:18:17 -07002924 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 mLayersPendingRemoval.add(layer);
2926 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002927 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002928 setTransactionFlags(eTransactionNeeded);
2929 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002932uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002933 return android_atomic_release_load(&mTransactionFlags);
2934}
2935
Mathias Agopian3f844832013-08-07 21:24:32 -07002936uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2938}
2939
Mathias Agopian3f844832013-08-07 21:24:32 -07002940uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2942 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002943 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944 }
2945 return old;
2946}
2947
Mathias Agopian8b33f032012-07-24 20:43:54 -07002948void SurfaceFlinger::setTransactionState(
2949 const Vector<ComposerState>& state,
2950 const Vector<DisplayState>& displays,
2951 uint32_t flags)
2952{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002953 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002954 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002955 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002956
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002957 if (flags & eAnimation) {
2958 // For window updates that are part of an animation we must wait for
2959 // previous animation "frames" to be handled.
2960 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002961 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002962 if (CC_UNLIKELY(err != NO_ERROR)) {
2963 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002964 // caller after a few seconds.
2965 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2966 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002967 mAnimTransactionPending = false;
2968 break;
2969 }
2970 }
2971 }
2972
Mathias Agopiane57f2922012-08-09 16:29:12 -07002973 size_t count = displays.size();
2974 for (size_t i=0 ; i<count ; i++) {
2975 const DisplayState& s(displays[i]);
2976 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002977 }
2978
Mathias Agopiane57f2922012-08-09 16:29:12 -07002979 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002980 for (size_t i=0 ; i<count ; i++) {
2981 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002982 // Here we need to check that the interface we're given is indeed
2983 // one of our own. A malicious client could give us a NULL
2984 // IInterface, or one of its own or even one of our own but a
2985 // different type. All these situations would cause us to crash.
2986 //
2987 // NOTE: it would be better to use RTTI as we could directly check
2988 // that we have a Client*. however, RTTI is disabled in Android.
2989 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002990 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002991 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002992 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002993 sp<Client> client( static_cast<Client *>(s.client.get()) );
2994 transactionFlags |= setClientStateLocked(client, s.state);
2995 }
2996 }
2997 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002998 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002999
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003000 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3001 // anyway. This can be used as a flush mechanism for previous async transactions.
3002 // Empty animation transaction can be used to simulate back-pressure, so also force a
3003 // transaction for empty animation transactions.
3004 if (transactionFlags == 0 &&
3005 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003006 transactionFlags = eTransactionNeeded;
3007 }
3008
Mathias Agopian386aa982011-11-07 21:58:03 -08003009 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003010 if (mInterceptor.isEnabled()) {
3011 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3012 }
Irvel468051e2016-06-13 16:44:44 -07003013
Mathias Agopian386aa982011-11-07 21:58:03 -08003014 // this triggers the transaction
3015 setTransactionFlags(transactionFlags);
3016
3017 // if this is a synchronous transaction, wait for it to take effect
3018 // before returning.
3019 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003020 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003021 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003022 if (flags & eAnimation) {
3023 mAnimTransactionPending = true;
3024 }
3025 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003026 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3027 if (CC_UNLIKELY(err != NO_ERROR)) {
3028 // just in case something goes wrong in SF, return to the
3029 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003030 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3031 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003032 break;
3033 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 }
3036}
3037
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3039{
Jesse Hall9a143922012-10-04 16:29:19 -07003040 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3041 if (dpyIdx < 0)
3042 return 0;
3043
Mathias Agopiane57f2922012-08-09 16:29:12 -07003044 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003045 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003046 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047 const uint32_t what = s.what;
3048 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003049 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003050 disp.surface = s.surface;
3051 flags |= eDisplayTransactionNeeded;
3052 }
3053 }
3054 if (what & DisplayState::eLayerStackChanged) {
3055 if (disp.layerStack != s.layerStack) {
3056 disp.layerStack = s.layerStack;
3057 flags |= eDisplayTransactionNeeded;
3058 }
3059 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003060 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 if (disp.orientation != s.orientation) {
3062 disp.orientation = s.orientation;
3063 flags |= eDisplayTransactionNeeded;
3064 }
3065 if (disp.frame != s.frame) {
3066 disp.frame = s.frame;
3067 flags |= eDisplayTransactionNeeded;
3068 }
3069 if (disp.viewport != s.viewport) {
3070 disp.viewport = s.viewport;
3071 flags |= eDisplayTransactionNeeded;
3072 }
3073 }
Michael Lentine47e45402014-07-18 15:34:25 -07003074 if (what & DisplayState::eDisplaySizeChanged) {
3075 if (disp.width != s.width) {
3076 disp.width = s.width;
3077 flags |= eDisplayTransactionNeeded;
3078 }
3079 if (disp.height != s.height) {
3080 disp.height = s.height;
3081 flags |= eDisplayTransactionNeeded;
3082 }
3083 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003084 }
3085 return flags;
3086}
3087
3088uint32_t SurfaceFlinger::setClientStateLocked(
3089 const sp<Client>& client,
3090 const layer_state_t& s)
3091{
3092 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003093 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003094 if (layer != 0) {
3095 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003096 bool geometryAppliesWithResize =
3097 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003099 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003101 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 }
3103 if (what & layer_state_t::eLayerChanged) {
3104 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 const auto& p = layer->getParent();
3106 if (p == nullptr) {
3107 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3108 if (layer->setLayer(s.z) && idx >= 0) {
3109 mCurrentState.layersSortedByZ.removeAt(idx);
3110 mCurrentState.layersSortedByZ.add(layer);
3111 // we need traversal (state changed)
3112 // AND transaction (list changed)
3113 flags |= eTransactionNeeded|eTraversalNeeded;
3114 }
3115 } else {
3116 if (p->setChildLayer(layer, s.z)) {
3117 flags |= eTransactionNeeded|eTraversalNeeded;
3118 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003119 }
3120 }
Robert Carrdb66e622017-04-10 16:55:57 -07003121 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003122 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003123 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003124 mCurrentState.layersSortedByZ.removeAt(idx);
3125 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003126 flags |= eTransactionNeeded|eTraversalNeeded;
3127 }
3128 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003129 if (what & layer_state_t::eSizeChanged) {
3130 if (layer->setSize(s.w, s.h)) {
3131 flags |= eTraversalNeeded;
3132 }
3133 }
3134 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003135 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003136 flags |= eTraversalNeeded;
3137 }
3138 if (what & layer_state_t::eMatrixChanged) {
3139 if (layer->setMatrix(s.matrix))
3140 flags |= eTraversalNeeded;
3141 }
3142 if (what & layer_state_t::eTransparentRegionChanged) {
3143 if (layer->setTransparentRegionHint(s.transparentRegion))
3144 flags |= eTraversalNeeded;
3145 }
Dan Stoza23116082015-06-18 14:58:39 -07003146 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003147 if (layer->setFlags(s.flags, s.mask))
3148 flags |= eTraversalNeeded;
3149 }
3150 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003151 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003152 flags |= eTraversalNeeded;
3153 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003154 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003155 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003156 flags |= eTraversalNeeded;
3157 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003158 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003159 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003160 // We only allow setting layer stacks for top level layers,
3161 // everything else inherits layer stack from its parent.
3162 if (layer->hasParent()) {
3163 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3164 layer->getName().string());
3165 } else if (idx < 0) {
3166 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3167 "that also does not appear in the top level layer list. Something"
3168 " has gone wrong.", layer->getName().string());
3169 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003170 mCurrentState.layersSortedByZ.removeAt(idx);
3171 mCurrentState.layersSortedByZ.add(layer);
3172 // we need traversal (state changed)
3173 // AND transaction (list changed)
3174 flags |= eTransactionNeeded|eTraversalNeeded;
3175 }
3176 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003177 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003178 if (s.barrierHandle != nullptr) {
3179 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3180 } else if (s.barrierGbp != nullptr) {
3181 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3182 if (authenticateSurfaceTextureLocked(gbp)) {
3183 const auto& otherLayer =
3184 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3185 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3186 } else {
3187 ALOGE("Attempt to defer transaction to to an"
3188 " unrecognized GraphicBufferProducer");
3189 }
3190 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003191 // We don't trigger a traversal here because if no other state is
3192 // changed, we don't want this to cause any more work
3193 }
Robert Carr1db73f62016-12-21 12:58:51 -08003194 if (what & layer_state_t::eReparentChildren) {
3195 if (layer->reparentChildren(s.reparentHandle)) {
3196 flags |= eTransactionNeeded|eTraversalNeeded;
3197 }
3198 }
Robert Carr9524cb32017-02-13 11:32:32 -08003199 if (what & layer_state_t::eDetachChildren) {
3200 layer->detachChildren();
3201 }
Robert Carrc3574f72016-03-24 12:19:32 -07003202 if (what & layer_state_t::eOverrideScalingModeChanged) {
3203 layer->setOverrideScalingMode(s.overrideScalingMode);
3204 // We don't trigger a traversal here because if no other state is
3205 // changed, we don't want this to cause any more work
3206 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003207 }
3208 return flags;
3209}
3210
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003211status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003212 const String8& name,
3213 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003214 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003215 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3216 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003218 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003219 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003220 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003221 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003222 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003223
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003224 status_t result = NO_ERROR;
3225
3226 sp<Layer> layer;
3227
Cody Northropbc755282017-03-31 12:00:08 -06003228 String8 uniqueName = getUniqueLayerName(name);
3229
Mathias Agopian3165cc22012-08-08 19:42:09 -07003230 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3231 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003232 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003233 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003234 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003236 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003237 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003238 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239 handle, gbp, &layer);
3240 break;
3241 default:
3242 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 break;
3244 }
3245
Dan Stoza7d89d062015-04-30 13:29:25 -07003246 if (result != NO_ERROR) {
3247 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003249
Chia-I Wuab0c3192017-08-01 11:29:00 -07003250 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3251 // TODO b/64227542
3252 if (windowType == 441731) {
3253 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3254 layer->setPrimaryDisplayOnly();
3255 }
3256
Albert Chaulk479c60c2017-01-27 14:21:34 -05003257 layer->setInfo(windowType, ownerUid);
3258
Robert Carr1f0a16a2016-10-24 16:27:39 -07003259 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003260 if (result != NO_ERROR) {
3261 return result;
3262 }
Irvelffc9efc2016-07-27 15:16:37 -07003263 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003264
3265 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267}
3268
Cody Northropbc755282017-03-31 12:00:08 -06003269String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3270{
3271 bool matchFound = true;
3272 uint32_t dupeCounter = 0;
3273
3274 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3275 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3276
3277 // Loop over layers until we're sure there is no matching name
3278 while (matchFound) {
3279 matchFound = false;
3280 mDrawingState.traverseInZOrder([&](Layer* layer) {
3281 if (layer->getName() == uniqueName) {
3282 matchFound = true;
3283 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3284 }
3285 });
3286 }
3287
3288 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3289
3290 return uniqueName;
3291}
3292
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003293status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3294 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3295 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296{
3297 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003298 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299 case PIXEL_FORMAT_TRANSPARENT:
3300 case PIXEL_FORMAT_TRANSLUCENT:
3301 format = PIXEL_FORMAT_RGBA_8888;
3302 break;
3303 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003304 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305 break;
3306 }
3307
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003308 *outLayer = new Layer(this, client, name, w, h, flags);
3309 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3310 if (err == NO_ERROR) {
3311 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003312 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003314
3315 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3316 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317}
3318
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003319status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3320 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3321 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003322{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003323 *outLayer = new LayerDim(this, client, name, w, h, flags);
3324 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003325 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003326 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003327}
3328
Mathias Agopianac9fa422013-02-11 16:40:36 -08003329status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003330{
Robert Carr9524cb32017-02-13 11:32:32 -08003331 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003332 status_t err = NO_ERROR;
3333 sp<Layer> l(client->getLayerUser(handle));
3334 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003335 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003336 err = removeLayer(l);
3337 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3338 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003339 }
3340 return err;
3341}
3342
Mathias Agopian13127d82013-03-05 17:47:11 -08003343status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003344{
Mathias Agopian67106042013-03-14 19:18:13 -07003345 // called by ~LayerCleaner() when all references to the IBinder (handle)
3346 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003347 sp<Layer> l = layer.promote();
3348 if (l == nullptr) {
3349 // The layer has already been removed, carry on
3350 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003351 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003352 // If we have a parent, then we can continue to live as long as it does.
3353 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Mathias Agopianb60314a2012-04-10 22:09:54 -07003356// ---------------------------------------------------------------------------
3357
Andy McFadden13a082e2012-08-24 10:16:42 -07003358void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003359 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003360 Vector<ComposerState> state;
3361 Vector<DisplayState> displays;
3362 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003363 d.what = DisplayState::eDisplayProjectionChanged |
3364 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003365 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003366 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003367 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003368 d.frame.makeInvalid();
3369 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003370 d.width = 0;
3371 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003372 displays.add(d);
3373 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003374 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3375 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003376
Dan Stoza9e56aa02015-11-02 13:00:03 -08003377 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3378 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003379 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003380
Brian Andersond0010582017-03-07 13:20:31 -08003381 // Use phase of 0 since phase is not known.
3382 // Use latency of 0, which will snap to the ideal latency.
3383 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003384}
3385
3386void SurfaceFlinger::initializeDisplays() {
3387 class MessageScreenInitialized : public MessageBase {
3388 SurfaceFlinger* flinger;
3389 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003390 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003391 virtual bool handler() {
3392 flinger->onInitializeDisplays();
3393 return true;
3394 }
3395 };
3396 sp<MessageBase> msg = new MessageScreenInitialized(this);
3397 postMessageAsync(msg); // we may be called from main thread, use async message
3398}
3399
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003401 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003402 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3403 this);
3404 int32_t type = hw->getDisplayType();
3405 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003406
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003407 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003408 return;
3409 }
3410
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003411 hw->setPowerMode(mode);
3412 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3413 ALOGW("Trying to set power mode for virtual display");
3414 return;
3415 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003416
Irvelffc9efc2016-07-27 15:16:37 -07003417 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003418 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003419 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3420 if (idx < 0) {
3421 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3422 return;
3423 }
3424 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3425 }
3426
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003428 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003429 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003430 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3431 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003432 // FIXME: eventthread only knows about the main display right now
3433 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003434 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003435 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003437 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003438 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003439 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003440
3441 struct sched_param param = {0};
3442 param.sched_priority = 1;
3443 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3444 ALOGW("Couldn't set SCHED_FIFO on display on");
3445 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003447 // Turn off the display
3448 struct sched_param param = {0};
3449 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3450 ALOGW("Couldn't set SCHED_OTHER on display off");
3451 }
3452
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003453 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003454 disableHardwareVsync(true); // also cancels any in-progress resync
3455
Mathias Agopiancde87a32012-09-13 14:09:01 -07003456 // FIXME: eventthread only knows about the main display right now
3457 mEventThread->onScreenReleased();
3458 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003459
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 getHwComposer().setPowerMode(type, mode);
3461 mVisibleRegionsDirty = true;
3462 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003463 } else if (mode == HWC_POWER_MODE_DOZE ||
3464 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003465 // Update display while dozing
3466 getHwComposer().setPowerMode(type, mode);
3467 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3468 // FIXME: eventthread only knows about the main display right now
3469 mEventThread->onScreenAcquired();
3470 resyncToHardwareVsync(true);
3471 }
3472 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3473 // Leave display going to doze
3474 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3475 disableHardwareVsync(true); // also cancels any in-progress resync
3476 // FIXME: eventthread only knows about the main display right now
3477 mEventThread->onScreenReleased();
3478 }
3479 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003480 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003481 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003482 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003483 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003484}
3485
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003486void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3487 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003488 SurfaceFlinger& mFlinger;
3489 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003490 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003491 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003492 MessageSetPowerMode(SurfaceFlinger& flinger,
3493 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3494 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003495 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003496 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003497 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003499 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003500 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003501 ALOGW("Attempt to set power mode = %d for virtual display",
3502 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003503 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003504 mFlinger.setPowerModeInternal(
3505 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003506 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003507 return true;
3508 }
3509 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003511 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003512}
3513
3514// ---------------------------------------------------------------------------
3515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3517{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003519
Mathias Agopianbd115332013-04-18 16:41:04 -07003520 IPCThreadState* ipc = IPCThreadState::self();
3521 const int pid = ipc->getCallingPid();
3522 const int uid = ipc->getCallingUid();
3523 if ((uid != AID_SHELL) &&
3524 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003525 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003526 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003528 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003529 // (this would indicate SF is stuck, but we want to be able to
3530 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003531 status_t err = mStateLock.timedLock(s2ns(1));
3532 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003533 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003534 result.appendFormat(
3535 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3536 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003537 }
3538
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003539 bool dumpAll = true;
3540 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003541 size_t numArgs = args.size();
3542 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003543 if ((index < numArgs) &&
3544 (args[index] == String16("--list"))) {
3545 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003546 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003547 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003548 }
3549
3550 if ((index < numArgs) &&
3551 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003552 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003553 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003554 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003555 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003556
3557 if ((index < numArgs) &&
3558 (args[index] == String16("--latency-clear"))) {
3559 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003560 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003561 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003562 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003563
3564 if ((index < numArgs) &&
3565 (args[index] == String16("--dispsync"))) {
3566 index++;
3567 mPrimaryDispSync.dump(result);
3568 dumpAll = false;
3569 }
Dan Stozab90cf072015-03-05 11:05:59 -08003570
3571 if ((index < numArgs) &&
3572 (args[index] == String16("--static-screen"))) {
3573 index++;
3574 dumpStaticScreenStats(result);
3575 dumpAll = false;
3576 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003577
3578 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003579 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003580 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003581 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003582 dumpAll = false;
3583 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003584
3585 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3586 index++;
3587 dumpWideColorInfo(result);
3588 dumpAll = false;
3589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003591
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003592 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003593 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003594 }
3595
Mathias Agopian9795c422009-08-26 16:36:26 -07003596 if (locked) {
3597 mStateLock.unlock();
3598 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599 }
3600 write(fd, result.string(), result.size());
3601 return NO_ERROR;
3602}
3603
Dan Stozac7014012014-02-14 15:03:43 -08003604void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3605 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003606{
Robert Carr2047fae2016-11-28 14:09:09 -08003607 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003608 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003609 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003610}
3611
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003612void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003613 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003614{
3615 String8 name;
3616 if (index < args.size()) {
3617 name = String8(args[index]);
3618 index++;
3619 }
3620
Dan Stoza9e56aa02015-11-02 13:00:03 -08003621 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3622 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003623 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003624
3625 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003626 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003627 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003628 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003629 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003630 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003631 }
Robert Carr2047fae2016-11-28 14:09:09 -08003632 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003633 }
3634}
3635
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003636void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003637 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003638{
3639 String8 name;
3640 if (index < args.size()) {
3641 name = String8(args[index]);
3642 index++;
3643 }
3644
Robert Carr2047fae2016-11-28 14:09:09 -08003645 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003646 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003647 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003648 }
Robert Carr2047fae2016-11-28 14:09:09 -08003649 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003650
Svetoslavd85084b2014-03-20 10:28:31 -07003651 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003652}
3653
Jamie Gennis6547ff42013-07-16 20:12:42 -07003654// This should only be called from the main thread. Otherwise it would need
3655// the lock and should use mCurrentState rather than mDrawingState.
3656void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003657 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003658 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003659 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003660
3661 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3662}
3663
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003664void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003665{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003666 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003667 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3668
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003669 if (isLayerTripleBufferingDisabled())
3670 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003671
3672 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003673 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003674 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003675 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003676 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3677 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003678 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003679}
3680
Dan Stozab90cf072015-03-05 11:05:59 -08003681void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3682{
3683 result.appendFormat("Static screen stats:\n");
3684 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3685 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3686 float percent = 100.0f *
3687 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3688 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3689 b + 1, bucketTimeSec, percent);
3690 }
3691 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3692 float percent = 100.0f *
3693 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3694 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3695 NUM_BUCKETS - 1, bucketTimeSec, percent);
3696}
3697
Dan Stozae77c7662016-05-13 11:37:28 -07003698void SurfaceFlinger::recordBufferingStats(const char* layerName,
3699 std::vector<OccupancyTracker::Segment>&& history) {
3700 Mutex::Autolock lock(mBufferingStatsMutex);
3701 auto& stats = mBufferingStats[layerName];
3702 for (const auto& segment : history) {
3703 if (!segment.usedThirdBuffer) {
3704 stats.twoBufferTime += segment.totalTime;
3705 }
3706 if (segment.occupancyAverage < 1.0f) {
3707 stats.doubleBufferedTime += segment.totalTime;
3708 } else if (segment.occupancyAverage < 2.0f) {
3709 stats.tripleBufferedTime += segment.totalTime;
3710 }
3711 ++stats.numSegments;
3712 stats.totalTime += segment.totalTime;
3713 }
3714}
3715
Brian Andersond6927fb2016-07-23 23:37:30 -07003716void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3717 result.appendFormat("Layer frame timestamps:\n");
3718
3719 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3720 const size_t count = currentLayers.size();
3721 for (size_t i=0 ; i<count ; i++) {
3722 currentLayers[i]->dumpFrameEvents(result);
3723 }
3724}
3725
Dan Stozae77c7662016-05-13 11:37:28 -07003726void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3727 result.append("Buffering stats:\n");
3728 result.append(" [Layer name] <Active time> <Two buffer> "
3729 "<Double buffered> <Triple buffered>\n");
3730 Mutex::Autolock lock(mBufferingStatsMutex);
3731 typedef std::tuple<std::string, float, float, float> BufferTuple;
3732 std::map<float, BufferTuple, std::greater<float>> sorted;
3733 for (const auto& statsPair : mBufferingStats) {
3734 const char* name = statsPair.first.c_str();
3735 const BufferingStats& stats = statsPair.second;
3736 if (stats.numSegments == 0) {
3737 continue;
3738 }
3739 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3740 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3741 stats.totalTime;
3742 float doubleBufferRatio = static_cast<float>(
3743 stats.doubleBufferedTime) / stats.totalTime;
3744 float tripleBufferRatio = static_cast<float>(
3745 stats.tripleBufferedTime) / stats.totalTime;
3746 sorted.insert({activeTime, {name, twoBufferRatio,
3747 doubleBufferRatio, tripleBufferRatio}});
3748 }
3749 for (const auto& sortedPair : sorted) {
3750 float activeTime = sortedPair.first;
3751 const BufferTuple& values = sortedPair.second;
3752 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3753 std::get<0>(values).c_str(), activeTime,
3754 std::get<1>(values), std::get<2>(values),
3755 std::get<3>(values));
3756 }
3757 result.append("\n");
3758}
3759
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003760void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3761 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003762 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003763
3764 // TODO: print out if wide-color mode is active or not
3765
3766 for (size_t d = 0; d < mDisplays.size(); d++) {
3767 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3768 int32_t hwcId = displayDevice->getHwcDisplayId();
3769 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3770 continue;
3771 }
3772
3773 result.appendFormat("Display %d color modes:\n", hwcId);
3774 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3775 for (auto&& mode : modes) {
3776 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3777 }
3778
3779 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3780 result.appendFormat(" Current color mode: %s (%d)\n",
3781 decodeColorMode(currentMode).c_str(), currentMode);
3782 }
3783 result.append("\n");
3784}
3785
Mathias Agopian74d211a2013-04-22 16:55:35 +02003786void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3787 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003788{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003789 bool colorize = false;
3790 if (index < args.size()
3791 && (args[index] == String16("--color"))) {
3792 colorize = true;
3793 index++;
3794 }
3795
3796 Colorizer colorizer(colorize);
3797
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003798 // figure out if we're stuck somewhere
3799 const nsecs_t now = systemTime();
3800 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3801 const nsecs_t inTransaction(mDebugInTransaction);
3802 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3803 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3804
3805 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003806 * Dump library configuration.
3807 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003808
3809 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003810 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003811 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003812 appendSfConfigString(result);
3813 appendUiConfigString(result);
3814 appendGuiConfigString(result);
3815 result.append("\n");
3816
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003817 result.append("\nWide-Color information:\n");
3818 dumpWideColorInfo(result);
3819
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003820 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003821 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003822 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003823 result.append(SyncFeatures::getInstance().toString());
3824 result.append("\n");
3825
Dan Stoza9e56aa02015-11-02 13:00:03 -08003826 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3827
Andy McFadden41d67d72014-04-25 16:58:34 -07003828 colorizer.bold(result);
3829 result.append("DispSync configuration: ");
3830 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003831 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003832 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003833 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003834 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003835 result.append("\n");
3836
Dan Stozab90cf072015-03-05 11:05:59 -08003837 // Dump static screen stats
3838 result.append("\n");
3839 dumpStaticScreenStats(result);
3840 result.append("\n");
3841
Dan Stozae77c7662016-05-13 11:37:28 -07003842 dumpBufferingStats(result);
3843
Andy McFadden4803b742012-09-24 19:07:20 -07003844 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845 * Dump the visible layer list
3846 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003847 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003848 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003849 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003850 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003851 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003852 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853
3854 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003855 * Dump Display state
3856 */
3857
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003859 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003861 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3862 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003863 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003864 }
3865
3866 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867 * Dump SurfaceFlinger global state
3868 */
3869
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003870 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003872 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873
Mathias Agopian888c8222012-08-04 21:10:38 -07003874 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003875 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003876
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003877 colorizer.bold(result);
3878 result.appendFormat("EGL implementation : %s\n",
3879 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3880 colorizer.reset(result);
3881 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003882 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003883
Mathias Agopian875d8e12013-06-07 15:35:48 -07003884 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003885
Mathias Agopian42977342012-08-05 00:40:46 -07003886 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3888 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003889 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003890 " last eglSwapBuffers() time: %f us\n"
3891 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003892 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003893 " refresh-rate : %f fps\n"
3894 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003895 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003896 " gpu_to_cpu_unsupported : %d\n"
3897 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003898 mLastSwapBufferTime/1000.0,
3899 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003900 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003901 1e9 / activeConfig->getVsyncPeriod(),
3902 activeConfig->getDpiX(),
3903 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003904 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003905
Mathias Agopian74d211a2013-04-22 16:55:35 +02003906 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003908
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911
3912 /*
3913 * VSYNC state
3914 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003915 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003916 result.append("\n");
3917
3918 /*
3919 * HWC layer minidump
3920 */
3921 for (size_t d = 0; d < mDisplays.size(); d++) {
3922 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3923 int32_t hwcId = displayDevice->getHwcDisplayId();
3924 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3925 continue;
3926 }
3927
3928 result.appendFormat("Display %d HWC layers:\n", hwcId);
3929 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003930 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003931 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003932 });
Dan Stozae22aec72016-08-01 13:20:59 -07003933 result.append("\n");
3934 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935
3936 /*
3937 * Dump HWComposer state
3938 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003939 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003940 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003941 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003942 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003943 result.appendFormat(" h/w composer %s\n",
3944 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003945 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946
3947 /*
3948 * Dump gralloc state
3949 */
3950 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3951 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003952
3953 /*
3954 * Dump VrFlinger state if in use.
3955 */
3956 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3957 result.append("VrFlinger state:\n");
3958 result.append(mVrFlinger->Dump().c_str());
3959 result.append("\n");
3960 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961}
3962
Mathias Agopian13127d82013-03-05 17:47:11 -08003963const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003964SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003965 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003966 wp<IBinder> dpy;
3967 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3968 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3969 dpy = mDisplays.keyAt(i);
3970 break;
3971 }
3972 }
3973 if (dpy == NULL) {
3974 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3975 // Just use the primary display so we have something to return
3976 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3977 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003978 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003979}
3980
Keun young Park63f165f2012-08-31 10:53:36 -07003981bool SurfaceFlinger::startDdmConnection()
3982{
3983 void* libddmconnection_dso =
3984 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3985 if (!libddmconnection_dso) {
3986 return false;
3987 }
3988 void (*DdmConnection_start)(const char* name);
3989 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003990 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003991 if (!DdmConnection_start) {
3992 dlclose(libddmconnection_dso);
3993 return false;
3994 }
3995 (*DdmConnection_start)(getServiceName());
3996 return true;
3997}
3998
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003999status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 switch (code) {
4001 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004002 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004003 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004004 case CLEAR_ANIMATION_FRAME_STATS:
4005 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004006 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004007 case GET_HDR_CAPABILITIES:
Chia-I Wu6200eac2017-10-05 14:24:41 -07004008 case ENABLE_VSYNC_INJECTIONS:
4009 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 {
4011 // codes that require permission check
4012 IPCThreadState* ipc = IPCThreadState::self();
4013 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004014 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004015 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004016 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004017 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004018 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004020 break;
4021 }
Robert Carr1db73f62016-12-21 12:58:51 -08004022 /*
4023 * Calling setTransactionState is safe, because you need to have been
4024 * granted a reference to Client* and Handle* to do anything with it.
4025 *
4026 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4027 */
4028 case SET_TRANSACTION_STATE:
4029 case CREATE_SCOPED_CONNECTION:
4030 {
4031 return OK;
4032 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004033 case CAPTURE_SCREEN:
4034 {
4035 // codes that require permission check
4036 IPCThreadState* ipc = IPCThreadState::self();
4037 const int pid = ipc->getCallingPid();
4038 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004039 if ((uid != AID_GRAPHICS) &&
4040 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004041 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004042 return PERMISSION_DENIED;
4043 }
4044 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 }
4046 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004047 return OK;
4048}
4049
4050status_t SurfaceFlinger::onTransact(
4051 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4052{
4053 status_t credentialCheck = CheckTransactCodeCredentials(code);
4054 if (credentialCheck != OK) {
4055 return credentialCheck;
4056 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004057
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4059 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004060 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004061 IPCThreadState* ipc = IPCThreadState::self();
4062 const int uid = ipc->getCallingUid();
4063 if (CC_UNLIKELY(uid != AID_SYSTEM
4064 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004065 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004066 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004067 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 return PERMISSION_DENIED;
4069 }
4070 int n;
4071 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004072 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004073 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 return NO_ERROR;
4075 case 1002: // SHOW_UPDATES
4076 n = data.readInt32();
4077 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004078 invalidateHwcGeometry();
4079 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004082 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004083 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004085 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004086 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004087 setTransactionFlags(
4088 eTransactionNeeded|
4089 eDisplayTransactionNeeded|
4090 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004091 return NO_ERROR;
4092 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004093 case 1006:{ // send empty update
4094 signalRefresh();
4095 return NO_ERROR;
4096 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004097 case 1008: // toggle use of hw composer
4098 n = data.readInt32();
4099 mDebugDisableHWC = n ? 1 : 0;
4100 invalidateHwcGeometry();
4101 repaintEverything();
4102 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004103 case 1009: // toggle use of transform hint
4104 n = data.readInt32();
4105 mDebugDisableTransformHint = n ? 1 : 0;
4106 invalidateHwcGeometry();
4107 repaintEverything();
4108 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004110 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004111 reply->writeInt32(0);
4112 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004113 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004114 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004115 return NO_ERROR;
4116 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004117 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004118 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004119 return NO_ERROR;
4120 }
4121 case 1014: {
4122 // daltonize
4123 n = data.readInt32();
4124 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004125 case 1:
4126 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4127 break;
4128 case 2:
4129 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4130 break;
4131 case 3:
4132 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4133 break;
4134 default:
4135 mDaltonizer.setType(ColorBlindnessType::None);
4136 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004137 }
4138 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004139 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004140 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004141 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004142 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004143 invalidateHwcGeometry();
4144 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004147 case 1015: {
4148 // apply a color matrix
4149 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004150 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004151 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004152 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004153 for (size_t j = 0; j < 4; j++) {
4154 mColorMatrix[i][j] = data.readFloat();
4155 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004156 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004157 } else {
4158 mColorMatrix = mat4();
4159 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004160
4161 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4162 // the division by w in the fragment shader
4163 float4 lastRow(transpose(mColorMatrix)[3]);
4164 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4165 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4166 }
4167
Alan Viverette9c5a3332013-09-12 20:04:35 -07004168 invalidateHwcGeometry();
4169 repaintEverything();
4170 return NO_ERROR;
4171 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004172 // This is an experimental interface
4173 // Needs to be shifted to proper binder interface when we productize
4174 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004175 n = data.readInt32();
4176 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004177 return NO_ERROR;
4178 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004179 case 1017: {
4180 n = data.readInt32();
4181 mForceFullDamage = static_cast<bool>(n);
4182 return NO_ERROR;
4183 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004184 case 1018: { // Modify Choreographer's phase offset
4185 n = data.readInt32();
4186 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4187 return NO_ERROR;
4188 }
4189 case 1019: { // Modify SurfaceFlinger's phase offset
4190 n = data.readInt32();
4191 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4192 return NO_ERROR;
4193 }
Irvel468051e2016-06-13 16:44:44 -07004194 case 1020: { // Layer updates interceptor
4195 n = data.readInt32();
4196 if (n) {
4197 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004198 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004199 }
4200 else{
4201 ALOGV("Interceptor disabled");
4202 mInterceptor.disable();
4203 }
4204 return NO_ERROR;
4205 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004206 case 1021: { // Disable HWC virtual displays
4207 n = data.readInt32();
4208 mUseHwcVirtualDisplays = !n;
4209 return NO_ERROR;
4210 }
Romain Guy0147a172017-06-01 13:53:56 -07004211 case 1022: { // Set saturation boost
4212 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4213
4214 invalidateHwcGeometry();
4215 repaintEverything();
4216 return NO_ERROR;
4217 }
Romain Guy54f154a2017-10-24 21:40:32 +01004218 case 1023: { // Set native mode
4219 mForceNativeColorMode = data.readInt32() == 1;
4220
4221 invalidateHwcGeometry();
4222 repaintEverything();
4223 return NO_ERROR;
4224 }
4225 case 1024: { // Is wide color gamut rendering/color management supported?
4226 reply->writeBool(hasWideColorDisplay);
4227 return NO_ERROR;
4228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229 }
4230 }
4231 return err;
4232}
4233
Steven Thomas6d8110b2017-08-31 18:24:21 -07004234void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004235 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004236 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004237}
4238
Steven Thomas6d8110b2017-08-31 18:24:21 -07004239void SurfaceFlinger::repaintEverything() {
4240 ConditionalLock _l(mStateLock,
4241 std::this_thread::get_id() != mMainThreadId);
4242 repaintEverythingLocked();
4243}
4244
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004245// Checks that the requested width and height are valid and updates them to the display dimensions
4246// if they are set to 0
4247static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4248 Transform::orientation_flags rotation,
4249 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4250 // get screen geometry
4251 uint32_t displayWidth = displayDevice->getWidth();
4252 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004253
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004254 if (rotation & Transform::ROT_90) {
4255 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004256 }
4257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004258 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4259 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4260 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4261 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004262 }
4263
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004264 if (*requestedWidth == 0) {
4265 *requestedWidth = displayWidth;
4266 }
4267 if (*requestedHeight == 0) {
4268 *requestedHeight = displayHeight;
4269 }
4270
4271 return NO_ERROR;
4272}
4273
4274// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4275class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004276public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004277 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4278 ~WindowDisconnector() {
4279 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004280 }
4281
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004282private:
4283 ANativeWindow* mWindow;
4284 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004285};
4286
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004287static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4288 uint32_t requestedHeight, bool hasWideColorDisplay,
4289 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4290 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4291 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4292
4293 int err = 0;
4294 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4295 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4296 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4297 err |= native_window_set_usage(window, usage);
4298
4299 if (hasWideColorDisplay) {
4300 err |= native_window_set_buffers_data_space(window,
4301 renderEngineUsesWideColor
4302 ? HAL_DATASPACE_DISPLAY_P3
4303 : HAL_DATASPACE_V0_SRGB);
4304 }
4305
4306 if (err != NO_ERROR) {
4307 return BAD_VALUE;
4308 }
4309
4310 /* TODO: Once we have the sync framework everywhere this can use
4311 * server-side waits on the fence that dequeueBuffer returns.
4312 */
4313 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4314 if (err != NO_ERROR) {
4315 return err;
4316 }
4317
4318 return NO_ERROR;
4319}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004320
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004321status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4322 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004323 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004324 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004325 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004326 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004327
4328 if (CC_UNLIKELY(display == 0))
4329 return BAD_VALUE;
4330
4331 if (CC_UNLIKELY(producer == 0))
4332 return BAD_VALUE;
4333
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004334 // if we have secure windows on this display, never allow the screen capture
4335 // unless the producer interface is local (i.e.: we can take a screenshot for
4336 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004337 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004338
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004339 // Convert to surfaceflinger's internal rotation type.
4340 Transform::orientation_flags rotationFlags;
4341 switch (rotation) {
4342 case ISurfaceComposer::eRotateNone:
4343 rotationFlags = Transform::ROT_0;
4344 break;
4345 case ISurfaceComposer::eRotate90:
4346 rotationFlags = Transform::ROT_90;
4347 break;
4348 case ISurfaceComposer::eRotate180:
4349 rotationFlags = Transform::ROT_180;
4350 break;
4351 case ISurfaceComposer::eRotate270:
4352 rotationFlags = Transform::ROT_270;
4353 break;
4354 default:
4355 rotationFlags = Transform::ROT_0;
4356 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4357 break;
4358 }
4359
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004360 { // Autolock scope
4361 Mutex::Autolock lock(mStateLock);
4362 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4363 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004364 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004365
4366 // create a surface (because we're a producer, and we need to
4367 // dequeue/queue a buffer)
4368 sp<Surface> surface = new Surface(producer, false);
4369
4370 // Put the screenshot Surface into async mode so that
4371 // Layer::headFenceHasSignaled will always return true and we'll latch the
4372 // first buffer regardless of whether or not its acquire fence has
4373 // signaled. This is needed to avoid a race condition in the rotation
4374 // animation. See b/30209608
4375 surface->setAsyncMode(true);
4376
4377 ANativeWindow* window = surface.get();
4378
4379 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4380 if (result != NO_ERROR) {
4381 return result;
4382 }
4383 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4384
4385 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004386 result = getWindowBuffer(window, reqWidth, reqHeight,
4387 hasWideColorDisplay && !mForceNativeColorMode,
4388 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004389 if (result != NO_ERROR) {
4390 return result;
4391 }
4392
4393 // This mutex protects syncFd and captureResult for communication of the return values from the
4394 // main thread back to this Binder thread
4395 std::mutex captureMutex;
4396 std::condition_variable captureCondition;
4397 std::unique_lock<std::mutex> captureLock(captureMutex);
4398 int syncFd = -1;
4399 std::optional<status_t> captureResult;
4400
4401 sp<LambdaMessage> message = new LambdaMessage([&]() {
4402 // If there is a refresh pending, bug out early and tell the binder thread to try again
4403 // after the refresh.
4404 if (mRefreshPending) {
4405 ATRACE_NAME("Skipping screenshot for now");
4406 std::unique_lock<std::mutex> captureLock(captureMutex);
4407 captureResult = std::make_optional<status_t>(EAGAIN);
4408 captureCondition.notify_one();
4409 return;
4410 }
4411
4412 status_t result = NO_ERROR;
4413 int fd = -1;
4414 {
4415 Mutex::Autolock _l(mStateLock);
4416 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4417 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4418 minLayerZ, maxLayerZ, useIdentityTransform,
4419 rotationFlags, isLocalScreenshot, &fd);
4420 }
4421
4422 {
4423 std::unique_lock<std::mutex> captureLock(captureMutex);
4424 syncFd = fd;
4425 captureResult = std::make_optional<status_t>(result);
4426 captureCondition.notify_one();
4427 }
4428 });
4429
4430 result = postMessageAsync(message);
4431 if (result == NO_ERROR) {
4432 captureCondition.wait(captureLock, [&]() { return captureResult; });
4433 while (*captureResult == EAGAIN) {
4434 captureResult.reset();
4435 result = postMessageAsync(message);
4436 if (result != NO_ERROR) {
4437 return result;
4438 }
4439 captureCondition.wait(captureLock, [&]() { return captureResult; });
4440 }
4441 result = *captureResult;
4442 }
4443
4444 if (result == NO_ERROR) {
4445 // queueBuffer takes ownership of syncFd
4446 result = window->queueBuffer(window, buffer, syncFd);
4447 }
4448
4449 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004450}
4451
Mathias Agopian180f10d2013-04-10 22:55:41 -07004452
4453void SurfaceFlinger::renderScreenImplLocked(
4454 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004455 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004456 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004457 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004458{
4459 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004460 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004461
4462 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004463 const int32_t hw_w = hw->getWidth();
4464 const int32_t hw_h = hw->getHeight();
4465 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004466 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004467
Dan Stozac1879002014-05-22 15:59:05 -07004468 // if a default or invalid sourceCrop is passed in, set reasonable values
4469 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4470 !sourceCrop.isValid()) {
4471 sourceCrop.setLeftTop(Point(0, 0));
4472 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4473 }
4474
4475 // ensure that sourceCrop is inside screen
4476 if (sourceCrop.left < 0) {
4477 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4478 }
Dan Stozabe31f442014-06-11 11:20:54 -07004479 if (sourceCrop.right > hw_w) {
4480 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004481 }
4482 if (sourceCrop.top < 0) {
4483 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4484 }
Dan Stozabe31f442014-06-11 11:20:54 -07004485 if (sourceCrop.bottom > hw_h) {
4486 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004487 }
4488
Romain Guy88d37dd2017-05-26 17:57:05 -07004489#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004490 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4491 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004492#endif
4493
Mathias Agopian180f10d2013-04-10 22:55:41 -07004494 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004495 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004496
4497 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004498 engine.setViewportAndProjection(
4499 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004500 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004501
4502 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004503 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004504
Robert Carr1f0a16a2016-10-24 16:27:39 -07004505 // We loop through the first level of layers without traversing,
4506 // as we need to interpret min/max layer Z in the top level Z space.
4507 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004508 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004509 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004510 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004511 const Layer::State& state(layer->getDrawingState());
4512 if (state.z < minLayerZ || state.z > maxLayerZ) {
4513 continue;
4514 }
Dan Stoza412903f2017-04-27 13:42:17 -07004515 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004516 if (!layer->isVisible()) {
4517 return;
4518 }
4519 if (filtering) layer->setFiltering(true);
4520 layer->draw(hw, useIdentityTransform);
4521 if (filtering) layer->setFiltering(false);
4522 });
4523 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524
Mathias Agopian931bda12013-08-28 18:11:46 -07004525 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004526}
4527
Dan Stozaabcda352017-06-01 14:37:39 -07004528// A simple RAII class that holds an EGLImage and destroys it either:
4529// a) When the destroy() method is called
4530// b) When the object goes out of scope
4531class ImageHolder {
4532public:
4533 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4534 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004535
Dan Stozaabcda352017-06-01 14:37:39 -07004536 void destroy() {
4537 if (mImage != EGL_NO_IMAGE_KHR) {
4538 eglDestroyImageKHR(mDisplay, mImage);
4539 mImage = EGL_NO_IMAGE_KHR;
4540 }
4541 }
4542
4543private:
4544 const EGLDisplay mDisplay;
4545 EGLImageKHR mImage;
4546};
4547
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004548status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4549 ANativeWindowBuffer* buffer, Rect sourceCrop,
4550 uint32_t reqWidth, uint32_t reqHeight,
4551 int32_t minLayerZ, int32_t maxLayerZ,
4552 bool useIdentityTransform,
4553 Transform::orientation_flags rotation,
4554 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004555 ATRACE_CALL();
4556
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004557 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004558 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004559 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004560 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004561 (state.z < minLayerZ || state.z > maxLayerZ)) {
4562 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004563 }
Dan Stoza412903f2017-04-27 13:42:17 -07004564 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004565 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4566 layer->isSecure());
4567 });
4568 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004569
4570 if (!isLocalScreenshot && secureLayerIsVisible) {
4571 ALOGW("FB is protected: PERMISSION_DENIED");
4572 return PERMISSION_DENIED;
4573 }
4574
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004575 int syncFd = -1;
4576 // create an EGLImage from the buffer so we can later
4577 // turn it into a texture
4578 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4579 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4580 if (image == EGL_NO_IMAGE_KHR) {
4581 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004582 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004583
Dan Stozaabcda352017-06-01 14:37:39 -07004584 // This will automatically destroy the image if we return before calling its destroy method
4585 ImageHolder imageHolder(mEGLDisplay, image);
4586
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004587 // this binds the given EGLImage as a framebuffer for the
4588 // duration of this scope.
4589 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004590 if (imageBond.getStatus() != NO_ERROR) {
4591 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004592 return INVALID_OPERATION;
4593 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004594
Dan Stozaabcda352017-06-01 14:37:39 -07004595 // this will in fact render into our dequeued buffer
4596 // via an FBO, which means we didn't have to create
4597 // an EGLSurface and therefore we're not
4598 // dependent on the context's EGLConfig.
4599 renderScreenImplLocked(
4600 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4601 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004602
Dan Stozaabcda352017-06-01 14:37:39 -07004603 // Attempt to create a sync khr object that can produce a sync point. If that
4604 // isn't available, create a non-dupable sync object in the fallback path and
4605 // wait on it directly.
4606 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4607 if (!DEBUG_SCREENSHOTS) {
4608 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4609 // native fence fd will not be populated until flush() is done.
4610 getRenderEngine().flush();
4611 }
4612
4613 if (sync != EGL_NO_SYNC_KHR) {
4614 // get the sync fd
4615 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4616 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4617 ALOGW("captureScreen: failed to dup sync khr object");
4618 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004619 }
Dan Stozaabcda352017-06-01 14:37:39 -07004620 eglDestroySyncKHR(mEGLDisplay, sync);
4621 } else {
4622 // fallback path
4623 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004624 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004625 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4626 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4627 EGLint eglErr = eglGetError();
4628 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4629 ALOGW("captureScreen: fence wait timed out");
4630 } else {
4631 ALOGW_IF(eglErr != EGL_SUCCESS,
4632 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004633 }
4634 eglDestroySyncKHR(mEGLDisplay, sync);
4635 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004636 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004637 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004638 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004639 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004640
4641 if (DEBUG_SCREENSHOTS) {
4642 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4643 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4644 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4645 hw, minLayerZ, maxLayerZ);
4646 delete [] pixels;
4647 }
4648
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004649 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004650 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004651
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004652 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004653}
4654
Mathias Agopiand5556842013-09-19 17:08:37 -07004655void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004656 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004657 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004658 for (size_t y=0 ; y<h ; y++) {
4659 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4660 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004661 if (p[x] != 0xFF000000) return;
4662 }
4663 }
4664 ALOGE("*** we just took a black screenshot ***\n"
4665 "requested minz=%d, maxz=%d, layerStack=%d",
4666 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004667
Robert Carr2047fae2016-11-28 14:09:09 -08004668 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004669 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004670 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004671 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004672 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004673 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004674 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4675 layer->isVisible() ? '+' : '-',
4676 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004677 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004678 i++;
4679 });
4680 }
4681 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004682 }
4683}
4684
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004685// ---------------------------------------------------------------------------
4686
Dan Stoza412903f2017-04-27 13:42:17 -07004687void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4688 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004689}
4690
Dan Stoza412903f2017-04-27 13:42:17 -07004691void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4692 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004693}
4694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004695}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004696
4697
4698#if defined(__gl_h_)
4699#error "don't include gl/gl.h in this file"
4700#endif
4701
4702#if defined(__gl2_h_)
4703#error "don't include gl2/gl2.h in this file"
4704#endif