blob: 000b4c6dcae2aed0025ad98569129f7bc92a1537 [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>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800118uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800119bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800120bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800121int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600122bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700125 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700127 mTransactionPending(false),
128 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700129 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700130 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700131 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800132 mHwc(nullptr),
133 mRealHwc(nullptr),
134 mVrHwc(nullptr),
135 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800140 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700142 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700143 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700144 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700145 mDebugInSwapBuffers(0),
146 mLastSwapBufferTime(0),
147 mDebugInTransaction(0),
148 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700149 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700150 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800151 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasPoweredOff(false),
156 mFrameBuckets(),
157 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700158 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800159 mNumLayers(0),
160 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800162 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800163
164 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
165 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
166
167 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
169
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800170 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700173 useContextPriority = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::useContextPriority>(false);
175
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700176 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
178
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700179 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
181
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800182 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
184
Steven Thomas050b2c82017-03-06 11:45:16 -0800185 // Vr flinger is only enabled on Daydream ready devices.
186 useVrFlinger = getBool< ISurfaceFlingerConfigs,
187 &ISurfaceFlingerConfigs::useVrFlinger>(false);
188
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
191
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600192 hasWideColorDisplay =
193 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 // debugging stuff...
196 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700197
Mathias Agopianb4b17302013-03-20 18:36:41 -0700198 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700199 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 property_get("debug.sf.showupdates", value, "0");
202 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700203
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204 property_get("debug.sf.ddms", value, "0");
205 mDebugDDMS = atoi(value);
206 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700207 if (!startDdmConnection()) {
208 // start failed, and DDMS debugging not enabled
209 mDebugDDMS = 0;
210 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700211 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700212 ALOGI_IF(mDebugRegion, "showupdates enabled");
213 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700214
215 property_get("debug.sf.disable_backpressure", value, "0");
216 mPropagateBackpressure = !atoi(value);
217 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700218
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800219 property_get("debug.sf.enable_hwc_vds", value, "0");
220 mUseHwcVirtualDisplays = atoi(value);
221 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800222
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800223 property_get("ro.sf.disable_triple_buffer", value, "1");
224 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800225 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226}
227
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800228void SurfaceFlinger::onFirstRef()
229{
230 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800231}
232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233SurfaceFlinger::~SurfaceFlinger()
234{
Mathias Agopiana4912602012-07-12 14:25:33 -0700235 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
236 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
237 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238}
239
Dan Stozac7014012014-02-14 15:03:43 -0800240void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241{
242 // the window manager died on us. prepare its eulogy.
243
Andy McFadden13a082e2012-08-24 10:16:42 -0700244 // restore initial conditions (default device unblank, etc)
245 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800246
247 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700248 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800249}
250
Robert Carr1db73f62016-12-21 12:58:51 -0800251static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700252 status_t err = client->initCheck();
253 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800254 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 }
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return nullptr;
257}
258
259sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
260 return initClient(new Client(this));
261}
262
263sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
264 const sp<IGraphicBufferProducer>& gbp) {
265 if (authenticateSurfaceTexture(gbp) == false) {
266 return nullptr;
267 }
268 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
269 if (layer == nullptr) {
270 return nullptr;
271 }
272
273 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274}
275
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700276sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
277 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700278{
279 class DisplayToken : public BBinder {
280 sp<SurfaceFlinger> flinger;
281 virtual ~DisplayToken() {
282 // no more references, this display must be terminated
283 Mutex::Autolock _l(flinger->mStateLock);
284 flinger->mCurrentState.displays.removeItem(this);
285 flinger->setTransactionFlags(eDisplayTransactionNeeded);
286 }
287 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700288 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700289 : flinger(flinger) {
290 }
291 };
292
293 sp<BBinder> token = new DisplayToken(this);
294
295 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700296 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700297 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700298 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700299 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 return token;
301}
302
Jesse Hall6c913be2013-08-08 12:15:49 -0700303void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
304 Mutex::Autolock _l(mStateLock);
305
306 ssize_t idx = mCurrentState.displays.indexOfKey(display);
307 if (idx < 0) {
308 ALOGW("destroyDisplay: invalid display token");
309 return;
310 }
311
312 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
313 if (!info.isVirtualDisplay()) {
314 ALOGE("destroyDisplay called for non-virtual display");
315 return;
316 }
Irvelffc9efc2016-07-27 15:16:37 -0700317 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700318 mCurrentState.displays.removeItemsAt(idx);
319 setTransactionFlags(eDisplayTransactionNeeded);
320}
321
Jesse Hall692c7232012-11-08 15:41:56 -0800322void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800323 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800324 ALOGW_IF(mBuiltinDisplays[type],
325 "Overwriting display token for display type %d", type);
326 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800327 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700328 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800329 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700330 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800331}
332
Mathias Agopiane57f2922012-08-09 16:29:12 -0700333sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700334 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
336 return NULL;
337 }
Jesse Hall692c7232012-11-08 15:41:56 -0800338 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339}
340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341void SurfaceFlinger::bootFinished()
342{
Wei Wangb254fa32017-01-31 17:43:23 -0800343 if (mStartBootAnimThread->join() != NO_ERROR) {
344 ALOGE("Join StartBootAnimThread failed!");
345 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 const nsecs_t now = systemTime();
347 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000348 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700349 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700350
351 // wait patiently for the window manager death
352 const String16 name("window");
353 sp<IBinder> window(defaultServiceManager()->getService(name));
354 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700355 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700356 }
357
Steven Thomas050b2c82017-03-06 11:45:16 -0800358 if (mVrFlinger) {
359 mVrFlinger->OnBootFinished();
360 }
361
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700362 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 // formerly we would just kill the process, but we now ask it to exit so it
364 // can choose where to stop the animation.
365 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700366
367 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
368 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
369 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370}
371
Mathias Agopian3f844832013-08-07 21:24:32 -0700372void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700373 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700374 RenderEngine& engine;
375 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700377 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
378 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 }
380 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700381 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700382 return true;
383 }
384 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386}
387
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700388class DispSyncSource : public VSyncSource, private DispSync::Callback {
389public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700390 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000391 const char* name) :
392 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700393 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700394 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
396 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700397 mDispSync(dispSync),
398 mCallbackMutex(),
399 mCallback(),
400 mVsyncMutex(),
401 mPhaseOffset(phaseOffset),
402 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700403
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404 virtual ~DispSyncSource() {}
405
406 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700407 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700408 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000409 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 static_cast<DispSync::Callback*>(this));
411 if (err != NO_ERROR) {
412 ALOGE("error registering vsync callback: %s (%d)",
413 strerror(-err), err);
414 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700415 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 } else {
417 status_t err = mDispSync->removeEventListener(
418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error unregistering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 }
427
428 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700429 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 mCallback = callback;
431 }
432
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 virtual void setPhaseOffset(nsecs_t phaseOffset) {
434 Mutex::Autolock lock(mVsyncMutex);
435
436 // Normalize phaseOffset to [0, period)
437 auto period = mDispSync->getPeriod();
438 phaseOffset %= period;
439 if (phaseOffset < 0) {
440 // If we're here, then phaseOffset is in (-period, 0). After this
441 // operation, it will be in (0, period)
442 phaseOffset += period;
443 }
444 mPhaseOffset = phaseOffset;
445
446 // If we're not enabled, we don't need to mess with the listeners
447 if (!mEnabled) {
448 return;
449 }
450
451 // Remove the listener with the old offset
452 status_t err = mDispSync->removeEventListener(
453 static_cast<DispSync::Callback*>(this));
454 if (err != NO_ERROR) {
455 ALOGE("error unregistering vsync callback: %s (%d)",
456 strerror(-err), err);
457 }
458
459 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000460 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error registering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466 }
467
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468private:
469 virtual void onDispSyncEvent(nsecs_t when) {
470 sp<VSyncSource::Callback> callback;
471 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 callback = mCallback;
474
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700475 if (mTraceVsync) {
476 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700477 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700478 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 }
480
481 if (callback != NULL) {
482 callback->onVSyncEvent(when);
483 }
484 }
485
Tim Murray4a4e4a22016-04-19 16:29:23 +0000486 const char* const mName;
487
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 int mValue;
489
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700490 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700491 const String8 mVsyncOnLabel;
492 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700493
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700495
496 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700498
499 Mutex mVsyncMutex; // Protects the following
500 nsecs_t mPhaseOffset;
501 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502};
503
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700504class InjectVSyncSource : public VSyncSource {
505public:
506 InjectVSyncSource() {}
507
508 virtual ~InjectVSyncSource() {}
509
510 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
511 std::lock_guard<std::mutex> lock(mCallbackMutex);
512 mCallback = callback;
513 }
514
515 virtual void onInjectSyncEvent(nsecs_t when) {
516 std::lock_guard<std::mutex> lock(mCallbackMutex);
517 mCallback->onVSyncEvent(when);
518 }
519
520 virtual void setVSyncEnabled(bool) {}
521 virtual void setPhaseOffset(nsecs_t) {}
522
523private:
524 std::mutex mCallbackMutex; // Protects the following
525 sp<VSyncSource::Callback> mCallback;
526};
527
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700529 ALOGI( "SurfaceFlinger's main thread ready to run. "
530 "Initializing graphics H/W...");
531
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900532 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
533
Dan Stoza9e56aa02015-11-02 13:00:03 -0800534 { // Autolock scope
535 Mutex::Autolock _l(mStateLock);
536
537 // initialize EGL for the default display
538 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
539 eglInitialize(mEGLDisplay, NULL, NULL);
540
541 // start the EventThread
542 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
543 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700544 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800545 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
546 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700547 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800548 mEventQueue.setEventThread(mSFEventThread);
549
Tim Murray22752852017-05-04 13:38:49 -0700550 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700551 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700552 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700553 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
554 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
555 }
Tim Murray22752852017-05-04 13:38:49 -0700556 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
557 ALOGE("Couldn't set SCHED_FIFO for EventThread");
558 }
Tim Murray41a38532016-06-22 12:42:10 -0700559
Dan Stoza9e56aa02015-11-02 13:00:03 -0800560 // Get a RenderEngine for the given display / config (can't fail)
561 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700562 HAL_PIXEL_FORMAT_RGBA_8888,
563 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800564 }
565
566 // Drop the state lock while we initialize the hardware composer. We drop
567 // the lock because on creation, it will call back into SurfaceFlinger to
568 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
570 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800571 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800572 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
574
Jesse Hall692c7232012-11-08 15:41:56 -0800575 Mutex::Autolock _l(mStateLock);
576
Ian Elliott5c34de22017-04-10 14:42:30 -0600577 // Inform native graphics APIs whether the present timestamp is supported:
578 if (getHwComposer().hasCapability(
579 HWC2::Capability::PresentFenceIsNotReliable)) {
580 property_set(kTimestampProperty, "0");
581 } else {
582 property_set(kTimestampProperty, "1");
583 }
584
Steven Thomas050b2c82017-03-06 11:45:16 -0800585 if (useVrFlinger) {
586 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700587 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800588 mVrFlingerRequestsDisplay = requestDisplay;
589 signalTransaction();
590 };
591 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
592 vrFlingerRequestDisplayCallback);
593 if (!mVrFlinger) {
594 ALOGE("Failed to start vrflinger");
595 }
596 }
597
Mathias Agopian875d8e12013-06-07 15:35:48 -0700598 // retrieve the EGL context that was selected/created
599 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700600
Mathias Agopianda27af92012-09-13 18:17:13 -0700601 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
602 "couldn't create EGLContext");
603
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604 // make the GLContext current so that we can create textures when creating
605 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700606 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700607
Jamie Gennisd1700752013-10-14 12:22:52 -0700608 mEventControlThread = new EventControlThread(this);
609 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
610
Mathias Agopian92a979a2012-08-02 18:32:23 -0700611 // initialize our drawing state
612 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700613
Andy McFadden13a082e2012-08-24 10:16:42 -0700614 // set initial conditions (e.g. unblank default device)
615 initializeDisplays();
616
Dan Stoza4e637772016-07-28 13:31:51 -0700617 mRenderEngine->primeCache();
618
Wei Wangb254fa32017-01-31 17:43:23 -0800619 mStartBootAnimThread = new StartBootAnimThread();
620 if (mStartBootAnimThread->Start() != NO_ERROR) {
621 ALOGE("Run StartBootAnimThread failed!");
622 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800623
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700625}
626
Mathias Agopiana67e4182012-06-19 17:26:12 -0700627void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800628 // Start boot animation service by setting a property mailbox
629 // if property setting thread is already running, Start() will be just a NOP
630 mStartBootAnimThread->Start();
631 // Wait until property was set
632 if (mStartBootAnimThread->join() != NO_ERROR) {
633 ALOGE("Join StartBootAnimThread failed!");
634 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700635}
636
Mathias Agopian875d8e12013-06-07 15:35:48 -0700637size_t SurfaceFlinger::getMaxTextureSize() const {
638 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700639}
640
Mathias Agopian875d8e12013-06-07 15:35:48 -0700641size_t SurfaceFlinger::getMaxViewportDims() const {
642 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700643}
644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800646
Jamie Gennis582270d2011-08-17 18:19:00 -0700647bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800648 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800649 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800650 return authenticateSurfaceTextureLocked(bufferProducer);
651}
652
653bool SurfaceFlinger::authenticateSurfaceTextureLocked(
654 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800655 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700656 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800657}
658
Brian Anderson6b376712017-04-04 10:51:39 -0700659status_t SurfaceFlinger::getSupportedFrameTimestamps(
660 std::vector<FrameEvent>* outSupported) const {
661 *outSupported = {
662 FrameEvent::REQUESTED_PRESENT,
663 FrameEvent::ACQUIRE,
664 FrameEvent::LATCH,
665 FrameEvent::FIRST_REFRESH_START,
666 FrameEvent::LAST_REFRESH_START,
667 FrameEvent::GPU_COMPOSITION_DONE,
668 FrameEvent::DEQUEUE_READY,
669 FrameEvent::RELEASE,
670 };
671 if (!getHwComposer().hasCapability(
672 HWC2::Capability::PresentFenceIsNotReliable)) {
673 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
674 }
675 return NO_ERROR;
676}
677
Dan Stoza7f7da322014-05-02 15:26:25 -0700678status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
679 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700680 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700681 return BAD_VALUE;
682 }
683
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500684 if (!display.get())
685 return NAME_NOT_FOUND;
686
Jesse Hall692c7232012-11-08 15:41:56 -0800687 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700688 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800689 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700690 type = i;
691 break;
692 }
693 }
694
695 if (type < 0) {
696 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700697 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700698
Mathias Agopian8b736f12012-08-13 17:54:26 -0700699 // TODO: Not sure if display density should handled by SF any longer
700 class Density {
701 static int getDensityFromProperty(char const* propName) {
702 char property[PROPERTY_VALUE_MAX];
703 int density = 0;
704 if (property_get(propName, property, NULL) > 0) {
705 density = atoi(property);
706 }
707 return density;
708 }
709 public:
710 static int getEmuDensity() {
711 return getDensityFromProperty("qemu.sf.lcd_density"); }
712 static int getBuildDensity() {
713 return getDensityFromProperty("ro.sf.lcd_density"); }
714 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700715
Dan Stoza7f7da322014-05-02 15:26:25 -0700716 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700717
Dan Stoza9e56aa02015-11-02 13:00:03 -0800718 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 DisplayInfo info = DisplayInfo();
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 float xdpi = hwConfig->getDpiX();
722 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700723
724 if (type == DisplayDevice::DISPLAY_PRIMARY) {
725 // The density of the device is provided by a build property
726 float density = Density::getBuildDensity() / 160.0f;
727 if (density == 0) {
728 // the build doesn't provide a density -- this is wrong!
729 // use xdpi instead
730 ALOGE("ro.sf.lcd_density must be defined as a build property");
731 density = xdpi / 160.0f;
732 }
733 if (Density::getEmuDensity()) {
734 // if "qemu.sf.lcd_density" is specified, it overrides everything
735 xdpi = ydpi = density = Density::getEmuDensity();
736 density /= 160.0f;
737 }
738 info.density = density;
739
740 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000741 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
742 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 } else {
744 // TODO: where should this value come from?
745 static const int TV_DENSITY = 213;
746 info.density = TV_DENSITY / 160.0f;
747 info.orientation = 0;
748 }
749
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 info.w = hwConfig->getWidth();
751 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 info.xdpi = xdpi;
753 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900755 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756
Andy McFadden91b2ca82014-06-13 14:04:23 -0700757 // This is how far in advance a buffer must be queued for
758 // presentation at a given time. If you want a buffer to appear
759 // on the screen at time N, you must submit the buffer before
760 // (N - presentationDeadline).
761 //
762 // Normally it's one full refresh period (to give SF a chance to
763 // latch the buffer), but this can be reduced by configuring a
764 // DispSync offset. Any additional delays introduced by the hardware
765 // composer or panel must be accounted for here.
766 //
767 // We add an additional 1ms to allow for processing time and
768 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800770 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700771
772 // All non-virtual displays are currently considered secure.
773 info.secure = true;
774
Michael Wright28f24d02016-07-12 13:30:53 -0700775 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700776 }
777
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 return NO_ERROR;
779}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700780
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800781status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700782 DisplayStatInfo* stats) {
783 if (stats == NULL) {
784 return BAD_VALUE;
785 }
786
787 // FIXME for now we always return stats for the primary display
788 memset(stats, 0, sizeof(*stats));
789 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
790 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
791 return NO_ERROR;
792}
793
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700794int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800795 if (display == NULL) {
796 ALOGE("%s : display is NULL", __func__);
797 return BAD_VALUE;
798 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700799
800 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700801 if (device != NULL) {
802 return device->getActiveConfig();
803 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700804
Dan Stoza24a42e92015-03-09 10:04:11 -0700805 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700806}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700807
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700808void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
809 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
810 this);
811 int32_t type = hw->getDisplayType();
812 int currentMode = hw->getActiveConfig();
813
814 if (mode == currentMode) {
815 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
816 return;
817 }
818
819 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
820 ALOGW("Trying to set config for virtual display");
821 return;
822 }
823
824 hw->setActiveConfig(mode);
825 getHwComposer().setActiveConfig(type, mode);
826}
827
828status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
829 class MessageSetActiveConfig: public MessageBase {
830 SurfaceFlinger& mFlinger;
831 sp<IBinder> mDisplay;
832 int mMode;
833 public:
834 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
835 int mode) :
836 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
837 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700838 Vector<DisplayInfo> configs;
839 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700840 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700841 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700842 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700843 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700844 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700845 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
846 if (hw == NULL) {
847 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700848 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700849 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
850 ALOGW("Attempt to set active config = %d for virtual display",
851 mMode);
852 } else {
853 mFlinger.setActiveConfigInternal(hw, mMode);
854 }
855 return true;
856 }
857 };
858 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
859 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700860 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700861}
Michael Wright28f24d02016-07-12 13:30:53 -0700862status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
863 Vector<android_color_mode_t>* outColorModes) {
864 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
865 return BAD_VALUE;
866 }
867
868 if (!display.get()) {
869 return NAME_NOT_FOUND;
870 }
871
872 int32_t type = NAME_NOT_FOUND;
873 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
874 if (display == mBuiltinDisplays[i]) {
875 type = i;
876 break;
877 }
878 }
879
880 if (type < 0) {
881 return type;
882 }
883
884 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
885 outColorModes->clear();
886 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
887
888 return NO_ERROR;
889}
890
891android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700892 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700893 if (device != nullptr) {
894 return device->getActiveColorMode();
895 }
896 return static_cast<android_color_mode_t>(BAD_VALUE);
897}
898
899void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
900 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700901 int32_t type = hw->getDisplayType();
902 android_color_mode_t currentMode = hw->getActiveColorMode();
903
904 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700905 return;
906 }
907
908 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
909 ALOGW("Trying to set config for virtual display");
910 return;
911 }
912
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600913 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
914 hw->getDisplayType());
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 hw->setActiveColorMode(mode);
917 getHwComposer().setActiveColorMode(type, mode);
918}
919
920
921status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
922 android_color_mode_t colorMode) {
923 class MessageSetActiveColorMode: public MessageBase {
924 SurfaceFlinger& mFlinger;
925 sp<IBinder> mDisplay;
926 android_color_mode_t mMode;
927 public:
928 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
929 android_color_mode_t mode) :
930 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
931 virtual bool handler() {
932 Vector<android_color_mode_t> modes;
933 mFlinger.getDisplayColorModes(mDisplay, &modes);
934 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
935 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600936 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
937 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700938 return true;
939 }
940 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
941 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600942 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
943 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700944 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600945 ALOGW("Attempt to set active color mode %s %d for virtual display",
946 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700947 } else {
948 mFlinger.setActiveColorModeInternal(hw, mMode);
949 }
950 return true;
951 }
952 };
953 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
954 postMessageSync(msg);
955 return NO_ERROR;
956}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700957
Svetoslavd85084b2014-03-20 10:28:31 -0700958status_t SurfaceFlinger::clearAnimationFrameStats() {
959 Mutex::Autolock _l(mStateLock);
960 mAnimFrameTracker.clearStats();
961 return NO_ERROR;
962}
963
964status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
965 Mutex::Autolock _l(mStateLock);
966 mAnimFrameTracker.getStats(outStats);
967 return NO_ERROR;
968}
969
Dan Stozac4f471e2016-03-24 09:31:08 -0700970status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
971 HdrCapabilities* outCapabilities) const {
972 Mutex::Autolock _l(mStateLock);
973
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700974 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700975 if (displayDevice == nullptr) {
976 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
977 return BAD_VALUE;
978 }
979
980 std::unique_ptr<HdrCapabilities> capabilities =
981 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
982 if (capabilities) {
983 std::swap(*outCapabilities, *capabilities);
984 } else {
985 return BAD_VALUE;
986 }
987
988 return NO_ERROR;
989}
990
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700991status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
992 if (enable == mInjectVSyncs) {
993 return NO_ERROR;
994 }
995
996 if (enable) {
997 mInjectVSyncs = enable;
998 ALOGV("VSync Injections enabled");
999 if (mVSyncInjector.get() == nullptr) {
1000 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001001 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001002 }
1003 mEventQueue.setEventThread(mInjectorEventThread);
1004 } else {
1005 mInjectVSyncs = enable;
1006 ALOGV("VSync Injections disabled");
1007 mEventQueue.setEventThread(mSFEventThread);
1008 mVSyncInjector.clear();
1009 }
1010 return NO_ERROR;
1011}
1012
1013status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1014 if (!mInjectVSyncs) {
1015 ALOGE("VSync Injections not enabled");
1016 return BAD_VALUE;
1017 }
1018 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1019 ALOGV("Injecting VSync inside SurfaceFlinger");
1020 mVSyncInjector->onInjectSyncEvent(when);
1021 }
1022 return NO_ERROR;
1023}
1024
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001025// ----------------------------------------------------------------------------
1026
1027sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001028 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001029}
1030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001032
1033void SurfaceFlinger::waitForEvent() {
1034 mEventQueue.waitMessage();
1035}
1036
1037void SurfaceFlinger::signalTransaction() {
1038 mEventQueue.invalidate();
1039}
1040
1041void SurfaceFlinger::signalLayerUpdate() {
1042 mEventQueue.invalidate();
1043}
1044
1045void SurfaceFlinger::signalRefresh() {
1046 mEventQueue.refresh();
1047}
1048
1049status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001050 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001051 return mEventQueue.postMessage(msg, reltime);
1052}
1053
1054status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001055 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001056 status_t res = mEventQueue.postMessage(msg, reltime);
1057 if (res == NO_ERROR) {
1058 msg->wait();
1059 }
1060 return res;
1061}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001063void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001064 do {
1065 waitForEvent();
1066 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067}
1068
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069void SurfaceFlinger::enableHardwareVsync() {
1070 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001071 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001073 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1074 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001076 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077}
1078
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 Mutex::Autolock _l(mHWVsyncLock);
1081
Jesse Hall948fe0c2013-10-14 12:56:09 -07001082 if (makeAvailable) {
1083 mHWVsyncAvailable = true;
1084 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001085 // Hardware vsync is not currently available, so abort the resync
1086 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087 return;
1088 }
1089
Dan Stoza9e56aa02015-11-02 13:00:03 -08001090 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1091 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092
1093 mPrimaryDispSync.reset();
1094 mPrimaryDispSync.setPeriod(period);
1095
1096 if (!mPrimaryHWVsyncEnabled) {
1097 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001098 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1099 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100 mPrimaryHWVsyncEnabled = true;
1101 }
1102}
1103
Jesse Hall948fe0c2013-10-14 12:56:09 -07001104void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105 Mutex::Autolock _l(mHWVsyncLock);
1106 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1108 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 mPrimaryDispSync.endResync();
1110 mPrimaryHWVsyncEnabled = false;
1111 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001112 if (makeUnavailable) {
1113 mHWVsyncAvailable = false;
1114 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115}
1116
Tim Murray4a4e4a22016-04-19 16:29:23 +00001117void SurfaceFlinger::resyncWithRateLimit() {
1118 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001119
1120 // No explicit locking is needed here since EventThread holds a lock while calling this method
1121 static nsecs_t sLastResyncAttempted = 0;
1122 const nsecs_t now = systemTime();
1123 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001124 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001125 }
Dan Stoza57164302017-05-08 14:03:54 -07001126 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001127}
1128
Steven Thomas3cfac282017-02-06 12:29:30 -08001129void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1130 nsecs_t timestamp) {
1131 Mutex::Autolock lock(mStateLock);
1132 // Ignore any vsyncs from the non-active hardware composer.
1133 if (composer != mHwc) {
1134 return;
1135 }
1136
Jamie Gennisd1700752013-10-14 12:22:52 -07001137 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001138
Jamie Gennisd1700752013-10-14 12:22:52 -07001139 { // Scope for the lock
1140 Mutex::Autolock _l(mHWVsyncLock);
1141 if (type == 0 && mPrimaryHWVsyncEnabled) {
1142 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001143 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001144 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001145
1146 if (needsHwVsync) {
1147 enableHardwareVsync();
1148 } else {
1149 disableHardwareVsync(false);
1150 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001151}
1152
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001153void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001154 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001155 *compositorTiming = mCompositorTiming;
1156}
1157
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001158void SurfaceFlinger::createDefaultDisplayDevice() {
1159 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1160 wp<IBinder> token = mBuiltinDisplays[type];
1161
1162 // All non-virtual displays are currently considered secure.
1163 const bool isSecure = true;
1164
1165 sp<IGraphicBufferProducer> producer;
1166 sp<IGraphicBufferConsumer> consumer;
1167 BufferQueue::createBufferQueue(&producer, &consumer);
1168
1169 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1170
1171 bool hasWideColorModes = false;
1172 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1173 for (android_color_mode_t colorMode : modes) {
1174 switch (colorMode) {
1175 case HAL_COLOR_MODE_DISPLAY_P3:
1176 case HAL_COLOR_MODE_ADOBE_RGB:
1177 case HAL_COLOR_MODE_DCI_P3:
1178 hasWideColorModes = true;
1179 break;
1180 default:
1181 break;
1182 }
1183 }
1184 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1185 token, fbs, producer, mRenderEngine->getEGLConfig(),
1186 hasWideColorModes && hasWideColorDisplay);
1187 mDisplays.add(token, hw);
1188 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1189 if (hasWideColorModes && hasWideColorDisplay) {
1190 defaultColorMode = HAL_COLOR_MODE_SRGB;
1191 }
1192 setActiveColorModeInternal(hw, defaultColorMode);
1193}
1194
1195void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001197
1198 if (composer->isUsingVrComposer()) {
1199 // We handle initializing the primary display device for the VR
1200 // window manager hwc explicitly at the time of transition.
1201 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1202 ALOGE("External displays are not supported by the vr hardware composer.");
1203 }
1204 return;
1205 }
1206
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1208 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001209 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1210 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 } else {
1212 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001213 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001214 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001215 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001216 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001217 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1218 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001219 }
1220 setTransactionFlags(eDisplayTransactionNeeded);
1221
Andy McFadden9e9689c2012-10-10 18:17:51 -07001222 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001223 }
Mathias Agopian86303202012-07-24 22:46:10 -07001224}
1225
Steven Thomas3cfac282017-02-06 12:29:30 -08001226void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1227 Mutex::Autolock lock(mStateLock);
1228 if (composer == mHwc) {
1229 repaintEverything();
1230 } else {
1231 // This isn't from our current hardware composer. If it's a callback
1232 // from the real composer, forward the refresh request to vr
1233 // flinger. Otherwise ignore it.
1234 if (!composer->isUsingVrComposer()) {
1235 mVrFlinger->OnHardwareComposerRefresh();
1236 }
1237 }
1238}
1239
Dan Stoza9e56aa02015-11-02 13:00:03 -08001240void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001242 getHwComposer().setVsyncEnabled(disp,
1243 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001244}
1245
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001246void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1247 for (size_t i = 0; i < layers.size(); ++i) {
1248 layers[i]->clearHwcLayers();
1249 }
1250}
1251
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001252// Note: it is assumed the caller holds |mStateLock| when this is called
1253void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001254 disableHardwareVsync(true);
1255 clearHwcLayers(mDrawingState.layersSortedByZ);
1256 clearHwcLayers(mCurrentState.layersSortedByZ);
1257 // Clear the drawing state so that the logic inside of
1258 // handleTransactionLocked will fire. It will determine the delta between
1259 // mCurrentState and mDrawingState and re-apply all changes when we make the
1260 // transition.
1261 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001262 // Release virtual display hwcId during vr mode transition.
1263 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1264 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1265 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1266 displayDevice->disconnect(getHwComposer());
1267 }
1268 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001269 mDisplays.clear();
1270}
1271
Steven Thomas050b2c82017-03-06 11:45:16 -08001272void SurfaceFlinger::updateVrFlinger() {
1273 if (!mVrFlinger)
1274 return;
1275 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1276 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001277 return;
1278 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279
Steven Thomas050b2c82017-03-06 11:45:16 -08001280 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001281 // Construct new HWComposer without holding any locks.
1282 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001283
1284 // Set up the event handlers. This step is neccessary to initialize the internal state of
1285 // the hardware composer object properly. Our callbacks are designed such that if they are
1286 // triggered between now and the point where the display is properly re-initialized, they
1287 // will not have any effect, so this is safe to do here, before the lock is aquired.
1288 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001289 ALOGV("Vr HWC created");
1290 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001291
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001293
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001294 if (vrFlingerRequestsDisplay) {
1295 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001296
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001297 mHwc = mVrHwc;
1298 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001299
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300 } else {
1301 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303 resetHwcLocked();
1304
1305 mHwc = mRealHwc;
1306 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001307 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001308
1309 mVisibleRegionsDirty = true;
1310 invalidateHwcGeometry();
1311
1312 // Explicitly re-initialize the primary display. This is because some other
1313 // parts of this class rely on the primary display always being available.
1314 createDefaultDisplayDevice();
1315
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001316 // Reset the timing values to account for the period of the swapped in HWC
1317 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1318 const nsecs_t period = activeConfig->getVsyncPeriod();
1319 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1320 setCompositorTimingSnapped(0, period, 0);
1321
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322 android_atomic_or(1, &mRepaintEverything);
1323 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324}
1325
Mathias Agopian4fec8732012-06-29 14:12:52 -07001326void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001327 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001328 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001329 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001330 bool frameMissed = !mHadClientComposition &&
1331 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332 (mPreviousPresentFence->getSignalTime() ==
1333 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001334 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001335 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001336 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001337 signalLayerUpdate();
1338 break;
1339 }
1340
Steven Thomas050b2c82017-03-06 11:45:16 -08001341 // Now that we're going to make it to the handleMessageTransaction()
1342 // call below it's safe to call updateVrFlinger(), which will
1343 // potentially trigger a display handoff.
1344 updateVrFlinger();
1345
Dan Stoza6b9454d2014-11-07 16:00:59 -08001346 bool refreshNeeded = handleMessageTransaction();
1347 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001348 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001349 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001350 // Signal a refresh if a transaction modified the window state,
1351 // a new buffer was latched, or if HWC has requested a full
1352 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001353 signalRefresh();
1354 }
1355 break;
1356 }
1357 case MessageQueue::REFRESH: {
1358 handleMessageRefresh();
1359 break;
1360 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001361 }
1362}
1363
Dan Stoza6b9454d2014-11-07 16:00:59 -08001364bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001365 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001366 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001367 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001369 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001370 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001371}
1372
Dan Stoza6b9454d2014-11-07 16:00:59 -08001373bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001374 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001375 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001376}
1377
1378void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001379 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001380
Pablo Ceballos40845df2016-01-25 17:41:15 -08001381 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001382
Brian Andersond6927fb2016-07-23 23:37:30 -07001383 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001384 rebuildLayerStacks();
1385 setUpHWComposer();
1386 doDebugFlashRegions();
1387 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001389
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001390 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001391
1392 mHadClientComposition = false;
1393 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1394 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1395 mHadClientComposition = mHadClientComposition ||
1396 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1397 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001398
Dan Stoza9e56aa02015-11-02 13:00:03 -08001399 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001400}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001401
Mathias Agopiancd60f992012-08-16 16:28:27 -07001402void SurfaceFlinger::doDebugFlashRegions()
1403{
1404 // is debugging enabled
1405 if (CC_LIKELY(!mDebugRegion))
1406 return;
1407
1408 const bool repaintEverything = mRepaintEverything;
1409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1410 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001411 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001412 // transform the dirty region into this screen's coordinate space
1413 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1414 if (!dirtyRegion.isEmpty()) {
1415 // redraw the whole screen
1416 doComposeSurfaces(hw, Region(hw->bounds()));
1417
1418 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001420 RenderEngine& engine(getRenderEngine());
1421 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1422
Mathias Agopianda27af92012-09-13 18:17:13 -07001423 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424 }
1425 }
1426 }
1427
1428 postFramebuffer();
1429
1430 if (mDebugRegion > 1) {
1431 usleep(mDebugRegion * 1000);
1432 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001433
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001435 auto& displayDevice = mDisplays[displayId];
1436 if (!displayDevice->isDisplayOn()) {
1437 continue;
1438 }
1439
1440 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001441 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1442 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001443 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444}
1445
Brian Andersond6927fb2016-07-23 23:37:30 -07001446void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001448 ATRACE_CALL();
1449 ALOGV("preComposition");
1450
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001452 mDrawingState.traverseInZOrder([&](Layer* layer) {
1453 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454 needExtraInvalidate = true;
1455 }
Robert Carr2047fae2016-11-28 14:09:09 -08001456 });
1457
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458 if (needExtraInvalidate) {
1459 signalLayerUpdate();
1460 }
1461}
1462
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001463void SurfaceFlinger::updateCompositorTiming(
1464 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1465 std::shared_ptr<FenceTime>& presentFenceTime) {
1466 // Update queue of past composite+present times and determine the
1467 // most recently known composite to present latency.
1468 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1469 nsecs_t compositeToPresentLatency = -1;
1470 while (!mCompositePresentTimes.empty()) {
1471 CompositePresentTime& cpt = mCompositePresentTimes.front();
1472 // Cached values should have been updated before calling this method,
1473 // which helps avoid duplicate syscalls.
1474 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1475 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1476 break;
1477 }
1478 compositeToPresentLatency = displayTime - cpt.composite;
1479 mCompositePresentTimes.pop();
1480 }
1481
1482 // Don't let mCompositePresentTimes grow unbounded, just in case.
1483 while (mCompositePresentTimes.size() > 16) {
1484 mCompositePresentTimes.pop();
1485 }
1486
Brian Andersond0010582017-03-07 13:20:31 -08001487 setCompositorTimingSnapped(
1488 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1489}
1490
1491void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1492 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 // Integer division and modulo round toward 0 not -inf, so we need to
1494 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001495 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1497 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1498
Brian Andersond0010582017-03-07 13:20:31 -08001499 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1500 if (idealLatency <= 0) {
1501 idealLatency = vsyncInterval;
1502 }
1503
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504 // Snap the latency to a value that removes scheduling jitter from the
1505 // composition and present times, which often have >1ms of jitter.
1506 // Reducing jitter is important if an app attempts to extrapolate
1507 // something (such as user input) to an accurate diasplay time.
1508 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1509 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001510 nsecs_t bias = vsyncInterval / 2;
1511 int64_t extraVsyncs =
1512 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1513 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1514 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515
Brian Andersond0010582017-03-07 13:20:31 -08001516 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001517 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1518 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001519 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001520}
1521
1522void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001524 ATRACE_CALL();
1525 ALOGV("postComposition");
1526
Brian Anderson3546a3f2016-07-14 11:51:14 -07001527 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001528 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001529 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001530 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001531 }
1532
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533 // |mStateLock| not needed as we are on the main thread
1534 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001535
1536 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1537 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1538 glCompositionDoneFenceTime =
1539 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1540 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1541 } else {
1542 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1543 }
1544 mGlCompositionDoneTimeline.updateSignalTimes();
1545
Brian Anderson4e606e32017-03-16 15:34:57 -07001546 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1547 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1548 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001549 mDisplayTimeline.updateSignalTimes();
1550
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1552 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1553
1554 // We use the refreshStartTime which might be sampled a little later than
1555 // when we started doing work for this frame, but that should be okay
1556 // since updateCompositorTiming has snapping logic.
1557 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001558 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001559 CompositorTiming compositorTiming;
1560 {
1561 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1562 compositorTiming = mCompositorTiming;
1563 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564
Robert Carr2047fae2016-11-28 14:09:09 -08001565 mDrawingState.traverseInZOrder([&](Layer* layer) {
1566 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001567 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001568 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001569 recordBufferingStats(layer->getName().string(),
1570 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001571 }
Robert Carr2047fae2016-11-28 14:09:09 -08001572 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001573
Brian Anderson4e606e32017-03-16 15:34:57 -07001574 if (presentFence->isValid()) {
1575 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001576 enableHardwareVsync();
1577 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001578 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001579 }
1580 }
1581
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001582 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001583 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001584 enableHardwareVsync();
1585 }
1586 }
1587
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001588 if (mAnimCompositionPending) {
1589 mAnimCompositionPending = false;
1590
Brian Anderson4e606e32017-03-16 15:34:57 -07001591 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001592 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001593 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001594 } else {
1595 // The HWC doesn't support present fences, so use the refresh
1596 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001597 nsecs_t presentTime =
1598 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001599 mAnimFrameTracker.setActualPresentTime(presentTime);
1600 }
1601 mAnimFrameTracker.advanceFrame();
1602 }
Dan Stozab90cf072015-03-05 11:05:59 -08001603
1604 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1605 return;
1606 }
1607
1608 nsecs_t currentTime = systemTime();
1609 if (mHasPoweredOff) {
1610 mHasPoweredOff = false;
1611 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001612 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001614 if (numPeriods < NUM_BUCKETS - 1) {
1615 mFrameBuckets[numPeriods] += elapsedTime;
1616 } else {
1617 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1618 }
1619 mTotalTime += elapsedTime;
1620 }
1621 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622}
1623
1624void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001625 ATRACE_CALL();
1626 ALOGV("rebuildLayerStacks");
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001629 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1630 ATRACE_CALL();
1631 mVisibleRegionsDirty = false;
1632 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001633
Jeff Sharkey76488112017-02-27 14:15:18 -07001634 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1635 Region opaqueRegion;
1636 Region dirtyRegion;
1637 Vector<sp<Layer>> layersSortedByZ;
1638 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1639 const Transform& tr(displayDevice->getTransform());
1640 const Rect bounds(displayDevice->getBounds());
1641 if (displayDevice->isDisplayOn()) {
1642 computeVisibleRegions(
1643 displayDevice->getLayerStack(), dirtyRegion,
1644 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001645
Jeff Sharkey76488112017-02-27 14:15:18 -07001646 mDrawingState.traverseInZOrder([&](Layer* layer) {
1647 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1648 Region drawRegion(tr.transform(
1649 layer->visibleNonTransparentRegion));
1650 drawRegion.andSelf(bounds);
1651 if (!drawRegion.isEmpty()) {
1652 layersSortedByZ.add(layer);
1653 } else {
1654 // Clear out the HWC layer if this layer was
1655 // previously visible, but no longer is
1656 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1657 nullptr);
1658 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001659 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001660 // WM changes displayDevice->layerStack upon sleep/awake.
1661 // Here we make sure we delete the HWC layers even if
1662 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001663 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1664 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001665 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001666 });
1667 }
1668 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1669 displayDevice->undefinedRegion.set(bounds);
1670 displayDevice->undefinedRegion.subtractSelf(
1671 tr.transform(opaqueRegion));
1672 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001673 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001674 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001676
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001677// pickColorMode translates a given dataspace into the best available color mode.
1678// Currently only support sRGB and Display-P3.
1679android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1680 switch (dataSpace) {
1681 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1682 // system expects.
1683 case HAL_DATASPACE_UNKNOWN:
1684 case HAL_DATASPACE_SRGB:
1685 case HAL_DATASPACE_V0_SRGB:
1686 return HAL_COLOR_MODE_SRGB;
1687 break;
1688
1689 case HAL_DATASPACE_DISPLAY_P3:
1690 return HAL_COLOR_MODE_DISPLAY_P3;
1691 break;
1692
1693 default:
1694 // TODO (courtneygo): Do we want to assert an error here?
1695 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1696 dataSpace);
1697 return HAL_COLOR_MODE_SRGB;
1698 break;
1699 }
1700}
1701
1702android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1703 // Only support sRGB and Display-P3 right now.
1704 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1705 return HAL_DATASPACE_DISPLAY_P3;
1706 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001707 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1708 return HAL_DATASPACE_DISPLAY_P3;
1709 }
1710 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1711 return HAL_DATASPACE_DISPLAY_P3;
1712 }
1713
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001714 return HAL_DATASPACE_V0_SRGB;
1715}
1716
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 ATRACE_CALL();
1719 ALOGV("setUpHWComposer");
1720
Jesse Hall028dc8f2013-08-20 16:35:32 -07001721 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001722 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1723 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1724 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1725
1726 // If nothing has changed (!dirty), don't recompose.
1727 // If something changed, but we don't currently have any visible layers,
1728 // and didn't when we last did a composition, then skip it this time.
1729 // The second rule does two things:
1730 // - When all layers are removed from a display, we'll emit one black
1731 // frame, then nothing more until we get new layers.
1732 // - When a display is created with a private layer stack, we won't
1733 // emit any black frames until a layer is added to the layer stack.
1734 bool mustRecompose = dirty && !(empty && wasEmpty);
1735
1736 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1737 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1738 mustRecompose ? "doing" : "skipping",
1739 dirty ? "+" : "-",
1740 empty ? "+" : "-",
1741 wasEmpty ? "+" : "-");
1742
Dan Stoza71433162014-02-04 16:22:36 -08001743 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001744
1745 if (mustRecompose) {
1746 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1747 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001748 }
1749
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750 // build the h/w work list
1751 if (CC_UNLIKELY(mGeometryInvalid)) {
1752 mGeometryInvalid = false;
1753 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1754 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1755 const auto hwcId = displayDevice->getHwcDisplayId();
1756 if (hwcId >= 0) {
1757 const Vector<sp<Layer>>& currentLayers(
1758 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001759 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001760 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 if (!layer->hasHwcLayer(hwcId)) {
1762 auto hwcLayer = mHwc->createLayer(hwcId);
1763 if (hwcLayer) {
1764 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1765 } else {
1766 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001768 }
1769 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001770
Robert Carrae060832016-11-28 10:51:00 -08001771 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001772 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001773 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001774 }
1775 }
1776 }
1777 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001778 }
Riley Andrews03414a12014-07-01 14:22:59 -07001779
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001780
1781 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1782
Dan Stoza9e56aa02015-11-02 13:00:03 -08001783 // Set the per-frame data
1784 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1785 auto& displayDevice = mDisplays[displayId];
1786 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001787
Dan Stoza9e56aa02015-11-02 13:00:03 -08001788 if (hwcId < 0) {
1789 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001790 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001791 if (colorMatrix != mPreviousColorMatrix) {
1792 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1793 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1794 "display %zd: %d", displayId, result);
1795 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1797 layer->setPerFrameData(displayDevice);
1798 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001799
1800 if (hasWideColorDisplay) {
1801 android_color_mode newColorMode;
1802 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1803
1804 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1805 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1806 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1807 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1808 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1809 }
1810 newColorMode = pickColorMode(newDataSpace);
1811
1812 setActiveColorModeInternal(displayDevice, newColorMode);
1813 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 }
1815
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001816 mPreviousColorMatrix = colorMatrix;
1817
Dan Stoza9e56aa02015-11-02 13:00:03 -08001818 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001819 auto& displayDevice = mDisplays[displayId];
1820 if (!displayDevice->isDisplayOn()) {
1821 continue;
1822 }
1823
1824 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1826 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001827 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001829
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830void SurfaceFlinger::doComposition() {
1831 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 ALOGV("doComposition");
1833
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001834 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001835 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001836 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001837 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001838 // transform the dirty region into this screen's coordinate space
1839 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001840
1841 // repaint the framebuffer (if needed)
1842 doDisplayComposition(hw, dirtyRegion);
1843
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844 hw->dirtyRegion.clear();
1845 hw->flip(hw->swapRegion);
1846 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001847 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001848 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001849 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001850}
1851
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001852void SurfaceFlinger::postFramebuffer()
1853{
Mathias Agopian841cde52012-03-01 15:44:37 -08001854 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001856
Mathias Agopiana44b0412011-10-16 18:46:35 -07001857 const nsecs_t now = systemTime();
1858 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001859
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1861 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001862 if (!displayDevice->isDisplayOn()) {
1863 continue;
1864 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 const auto hwcId = displayDevice->getHwcDisplayId();
1866 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001867 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001868 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001869 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001870 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1872 sp<Fence> releaseFence = Fence::NO_FENCE;
1873 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1874 releaseFence = displayDevice->getClientTargetAcquireFence();
1875 } else {
1876 auto hwcLayer = layer->getHwcLayer(hwcId);
1877 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001878 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 layer->onLayerDisplayed(releaseFence);
1880 }
1881 if (hwcId >= 0) {
1882 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001883 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001884 }
1885
Mathias Agopiana44b0412011-10-16 18:46:35 -07001886 mLastSwapBufferTime = systemTime() - now;
1887 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001888
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001889 // |mStateLock| not needed as we are on the main thread
1890 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001891 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1892 logFrameStats();
1893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001894}
1895
Mathias Agopian87baae12012-07-31 12:38:26 -07001896void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001897{
Mathias Agopian841cde52012-03-01 15:44:37 -08001898 ATRACE_CALL();
1899
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001900 // here we keep a copy of the drawing state (that is the state that's
1901 // going to be overwritten by handleTransactionLocked()) outside of
1902 // mStateLock so that the side-effects of the State assignment
1903 // don't happen with mStateLock held (which can cause deadlocks).
1904 State drawingState(mDrawingState);
1905
Mathias Agopianca4d3602011-05-19 15:38:14 -07001906 Mutex::Autolock _l(mStateLock);
1907 const nsecs_t now = systemTime();
1908 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001909
Mathias Agopianca4d3602011-05-19 15:38:14 -07001910 // Here we're guaranteed that some transaction flags are set
1911 // so we can call handleTransactionLocked() unconditionally.
1912 // We call getTransactionFlags(), which will also clear the flags,
1913 // with mStateLock held to guarantee that mCurrentState won't change
1914 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001915
Mathias Agopiane57f2922012-08-09 16:29:12 -07001916 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001917 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001918
Mathias Agopianca4d3602011-05-19 15:38:14 -07001919 mLastTransactionTime = systemTime() - now;
1920 mDebugInTransaction = 0;
1921 invalidateHwcGeometry();
1922 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001923}
1924
Mathias Agopian87baae12012-07-31 12:38:26 -07001925void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001926{
Dan Stoza7dde5992015-05-22 09:51:44 -07001927 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mCurrentState.traverseInZOrder([](Layer* layer) {
1929 layer->notifyAvailableFrames();
1930 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001931
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001932 /*
1933 * Traversal of the children
1934 * (perform the transaction for each of them if needed)
1935 */
1936
Mathias Agopian3559b072012-08-15 13:46:03 -07001937 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001938 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001939 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001940 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001941
1942 const uint32_t flags = layer->doTransaction(0);
1943 if (flags & Layer::eVisibleRegion)
1944 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001945 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001946 }
1947
1948 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001949 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001950 */
1951
Mathias Agopiane57f2922012-08-09 16:29:12 -07001952 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001953 // here we take advantage of Vector's copy-on-write semantics to
1954 // improve performance by skipping the transaction entirely when
1955 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001956 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1957 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001958 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001959 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001960 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001961 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001962
1963 // find the displays that were removed
1964 // (ie: in drawing state but not in current state)
1965 // also handle displays that changed
1966 // (ie: displays that are in both lists)
1967 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001968 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1969 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001970 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001971 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001972 // Call makeCurrent() on the primary display so we can
1973 // be sure that nothing associated with this display
1974 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001975 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001976 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001977 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07001978 if (hw != NULL)
1979 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001980 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001981 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001982 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001983 } else {
1984 ALOGW("trying to remove the main display");
1985 }
1986 } else {
1987 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001988 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001989 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001990 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1991 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001992 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001993 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001994 // recreating the DisplayDevice, so we just remove it
1995 // from the drawing state, so that it get re-added
1996 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001997 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07001998 if (hw != NULL)
1999 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002000 mDisplays.removeItem(display);
2001 mDrawingState.displays.removeItemsAt(i);
2002 dc--; i--;
2003 // at this point we must loop to the next item
2004 continue;
2005 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002006
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002007 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002008 if (disp != NULL) {
2009 if (state.layerStack != draw[i].layerStack) {
2010 disp->setLayerStack(state.layerStack);
2011 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002012 if ((state.orientation != draw[i].orientation)
2013 || (state.viewport != draw[i].viewport)
2014 || (state.frame != draw[i].frame))
2015 {
2016 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002017 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002018 }
Michael Lentine47e45402014-07-18 15:34:25 -07002019 if (state.width != draw[i].width || state.height != draw[i].height) {
2020 disp->setDisplaySize(state.width, state.height);
2021 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002022 }
2023 }
2024 }
2025
2026 // find displays that were added
2027 // (ie: in current state but not in drawing state)
2028 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002029 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002030 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002031
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002032 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002033 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002034 sp<IGraphicBufferProducer> bqProducer;
2035 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002036 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002037
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002039 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002040 // Virtual displays without a surface are dormant:
2041 // they have external state (layer stack, projection,
2042 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002043 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002044
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002045 // Allow VR composer to use virtual displays.
2046 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002047 int width = 0;
2048 int status = state.surface->query(
2049 NATIVE_WINDOW_WIDTH, &width);
2050 ALOGE_IF(status != NO_ERROR,
2051 "Unable to query width (%d)", status);
2052 int height = 0;
2053 status = state.surface->query(
2054 NATIVE_WINDOW_HEIGHT, &height);
2055 ALOGE_IF(status != NO_ERROR,
2056 "Unable to query height (%d)", status);
2057 int intFormat = 0;
2058 status = state.surface->query(
2059 NATIVE_WINDOW_FORMAT, &intFormat);
2060 ALOGE_IF(status != NO_ERROR,
2061 "Unable to query format (%d)", status);
2062 auto format = static_cast<android_pixel_format_t>(
2063 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002064
Dan Stoza8cf150a2016-08-02 10:27:31 -07002065 mHwc->allocateVirtualDisplay(width, height, &format,
2066 &hwcId);
2067 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068
Dan Stoza5cf424b2016-05-20 14:02:39 -07002069 // TODO: Plumb requested format back up to consumer
2070
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 sp<VirtualDisplaySurface> vds =
2072 new VirtualDisplaySurface(*mHwc,
2073 hwcId, state.surface, bqProducer,
2074 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002075
2076 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002077 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002078 }
2079 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002080 ALOGE_IF(state.surface!=NULL,
2081 "adding a supported display, but rendering "
2082 "surface is provided (%p), ignoring it",
2083 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002084
2085 hwcId = state.type;
2086 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2087 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002088 }
2089
2090 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002091 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002092 sp<DisplayDevice> hw =
2093 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2094 dispSurface, producer,
2095 mRenderEngine->getEGLConfig(),
2096 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002097 hw->setLayerStack(state.layerStack);
2098 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002099 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002100 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002101 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002103 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002104 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002105 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002106 }
2107 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002109 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110
Mathias Agopian84300952012-11-21 16:02:13 -08002111 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2112 // The transform hint might have changed for some layers
2113 // (either because a display has changed, or because a layer
2114 // as changed).
2115 //
2116 // Walk through all the layers in currentLayers,
2117 // and update their transform hint.
2118 //
2119 // If a layer is visible only on a single display, then that
2120 // display is used to calculate the hint, otherwise we use the
2121 // default display.
2122 //
2123 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2124 // the hint is set before we acquire a buffer from the surface texture.
2125 //
2126 // NOTE: layer transactions have taken place already, so we use their
2127 // drawing state. However, SurfaceFlinger's own transaction has not
2128 // happened yet, so we must use the current state layer list
2129 // (soon to become the drawing state list).
2130 //
2131 sp<const DisplayDevice> disp;
2132 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002133 bool first = true;
2134 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002135 // NOTE: we rely on the fact that layers are sorted by
2136 // layerStack first (so we don't have to traverse the list
2137 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002138 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002139 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002140 currentlayerStack = layerStack;
2141 // figure out if this layerstack is mirrored
2142 // (more than one display) if so, pick the default display,
2143 // if not, pick the only display it's on.
2144 disp.clear();
2145 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2146 sp<const DisplayDevice> hw(mDisplays[dpy]);
2147 if (hw->getLayerStack() == currentlayerStack) {
2148 if (disp == NULL) {
2149 disp = hw;
2150 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002151 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002152 break;
2153 }
2154 }
2155 }
2156 }
Chet Haase91d25932013-04-11 15:24:55 -07002157 if (disp == NULL) {
2158 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2159 // redraw after transform hint changes. See bug 8508397.
2160
2161 // could be null when this layer is using a layerStack
2162 // that is not visible on any display. Also can occur at
2163 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002164 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002165 }
Chet Haase91d25932013-04-11 15:24:55 -07002166 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002167
2168 first = false;
2169 });
Mathias Agopian84300952012-11-21 16:02:13 -08002170 }
2171
2172
Mathias Agopian3559b072012-08-15 13:46:03 -07002173 /*
2174 * Perform our own transaction if needed
2175 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176
2177 if (mLayersAdded) {
2178 mLayersAdded = false;
2179 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002180 mVisibleRegionsDirty = true;
2181 }
2182
2183 // some layers might have been removed, so
2184 // we need to update the regions they're exposing.
2185 if (mLayersRemoved) {
2186 mLayersRemoved = false;
2187 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002188 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002189 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002190 // this layer is not visible anymore
2191 // TODO: we could traverse the tree from front to back and
2192 // compute the actual visible region
2193 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002194 Region visibleReg;
2195 visibleReg.set(layer->computeScreenBounds());
2196 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002197 }
Robert Carr2047fae2016-11-28 14:09:09 -08002198 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002199 }
2200
2201 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002202
2203 updateCursorAsync();
2204}
2205
2206void SurfaceFlinger::updateCursorAsync()
2207{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2209 auto& displayDevice = mDisplays[displayId];
2210 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002211 continue;
2212 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213
2214 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2215 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002216 }
2217 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002218}
2219
2220void SurfaceFlinger::commitTransaction()
2221{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002222 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002223 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002224 for (const auto& l : mLayersPendingRemoval) {
2225 recordBufferingStats(l->getName().string(),
2226 l->getOccupancyHistory(true));
2227 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002228 }
2229 mLayersPendingRemoval.clear();
2230 }
2231
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002232 // If this transaction is part of a window animation then the next frame
2233 // we composite should be considered an animation as well.
2234 mAnimCompositionPending = mAnimTransactionPending;
2235
Mathias Agopian4fec8732012-06-29 14:12:52 -07002236 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002237 mDrawingState.traverseInZOrder([](Layer* layer) {
2238 layer->commitChildList();
2239 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002240 mTransactionPending = false;
2241 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002242 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243}
2244
Robert Carr2047fae2016-11-28 14:09:09 -08002245void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002246 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247{
Mathias Agopian841cde52012-03-01 15:44:37 -08002248 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002251 Region aboveOpaqueLayers;
2252 Region aboveCoveredLayers;
2253 Region dirty;
2254
Mathias Agopian87baae12012-07-31 12:38:26 -07002255 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256
Robert Carr2047fae2016-11-28 14:09:09 -08002257 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002259 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002260
Jesse Hall01e29052013-02-19 16:13:35 -08002261 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002263 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002264
Mathias Agopianab028732010-03-16 16:41:46 -07002265 /*
2266 * opaqueRegion: area of a surface that is fully opaque.
2267 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002269
2270 /*
2271 * visibleRegion: area of a surface that is visible on screen
2272 * and not fully transparent. This is essentially the layer's
2273 * footprint minus the opaque regions above it.
2274 * Areas covered by a translucent surface are considered visible.
2275 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002277
2278 /*
2279 * coveredRegion: area of a surface that is covered by all
2280 * visible regions above it (which includes the translucent areas).
2281 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002283
Jesse Halla8026d22012-09-25 13:25:04 -07002284 /*
2285 * transparentRegion: area of a surface that is hinted to be completely
2286 * transparent. This is only used to tell when the layer has no visible
2287 * non-transparent regions and can be removed from the layer list. It
2288 * does not affect the visibleRegion of this layer or any layers
2289 * beneath it. The hint may not be correct if apps don't respect the
2290 * SurfaceView restrictions (which, sadly, some don't).
2291 */
2292 Region transparentRegion;
2293
Mathias Agopianab028732010-03-16 16:41:46 -07002294
2295 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002296 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002297 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002298 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002301 if (!visibleRegion.isEmpty()) {
2302 // Remove the transparent area from the visible region
2303 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002304 if (tr.preserveRects()) {
2305 // transform the transparent region
2306 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002307 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002308 // transformation too complex, can't do the
2309 // transparent region optimization.
2310 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002311 }
Mathias Agopianab028732010-03-16 16:41:46 -07002312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Mathias Agopianab028732010-03-16 16:41:46 -07002314 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002315 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002316 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002317 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2318 // the opaque region is the layer's footprint
2319 opaqueRegion = visibleRegion;
2320 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 }
2322 }
2323
Mathias Agopianab028732010-03-16 16:41:46 -07002324 // Clip the covered region to the visible region
2325 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2326
2327 // Update aboveCoveredLayers for next (lower) layer
2328 aboveCoveredLayers.orSelf(visibleRegion);
2329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 // subtract the opaque region covered by the layers above us
2331 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002332
2333 // compute this layer's dirty region
2334 if (layer->contentDirty) {
2335 // we need to invalidate the whole region
2336 dirty = visibleRegion;
2337 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002338 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339 layer->contentDirty = false;
2340 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002341 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002342 * the exposed region consists of two components:
2343 * 1) what's VISIBLE now and was COVERED before
2344 * 2) what's EXPOSED now less what was EXPOSED before
2345 *
2346 * note that (1) is conservative, we start with the whole
2347 * visible region but only keep what used to be covered by
2348 * something -- which mean it may have been exposed.
2349 *
2350 * (2) handles areas that were not covered by anything but got
2351 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002352 */
Mathias Agopianab028732010-03-16 16:41:46 -07002353 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002354 const Region oldVisibleRegion = layer->visibleRegion;
2355 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002356 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2357 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358 }
2359 dirty.subtractSelf(aboveOpaqueLayers);
2360
2361 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002362 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363
Mathias Agopianab028732010-03-16 16:41:46 -07002364 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002366
Jesse Halla8026d22012-09-25 13:25:04 -07002367 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368 layer->setVisibleRegion(visibleRegion);
2369 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002370 layer->setVisibleNonTransparentRegion(
2371 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002372 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373
Mathias Agopian87baae12012-07-31 12:38:26 -07002374 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375}
2376
Mathias Agopian87baae12012-07-31 12:38:26 -07002377void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2378 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002379 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002380 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2381 if (hw->getLayerStack() == layerStack) {
2382 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002383 }
2384 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002385}
2386
Dan Stoza6b9454d2014-11-07 16:00:59 -08002387bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 ALOGV("handlePageFlip");
2390
Brian Andersond6927fb2016-07-23 23:37:30 -07002391 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopian4fec8732012-06-29 14:12:52 -07002393 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002394 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002395 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002396
2397 // Store the set of layers that need updates. This set must not change as
2398 // buffers are being latched, as this could result in a deadlock.
2399 // Example: Two producers share the same command stream and:
2400 // 1.) Layer 0 is latched
2401 // 2.) Layer 0 gets a new frame
2402 // 2.) Layer 1 gets a new frame
2403 // 3.) Layer 1 is latched.
2404 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2405 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002406 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002407 if (layer->hasQueuedFrame()) {
2408 frameQueued = true;
2409 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002410 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002411 } else {
2412 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002413 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002414 } else {
2415 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002416 }
Robert Carr2047fae2016-11-28 14:09:09 -08002417 });
2418
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002420 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002421 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002423 if (!dirty.isEmpty()) {
2424 newDataLatched = true;
2425 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002427
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002428 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002429
2430 // If we will need to wake up at some time in the future to deal with a
2431 // queued frame that shouldn't be displayed during this vsync period, wake
2432 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002433 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002434 signalLayerUpdate();
2435 }
2436
2437 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002438 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439}
2440
Mathias Agopianad456f92011-01-13 17:53:01 -08002441void SurfaceFlinger::invalidateHwcGeometry()
2442{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002444}
2445
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002446
Fabien Sanglard830b8472016-11-30 16:35:58 -08002447void SurfaceFlinger::doDisplayComposition(
2448 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002449 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450{
Dan Stoza71433162014-02-04 16:22:36 -08002451 // We only need to actually compose the display if:
2452 // 1) It is being handled by hardware composer, which may need this to
2453 // keep its virtual display state machine in sync, or
2454 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002455 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002456 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002458 return;
2459 }
2460
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 ALOGV("doDisplayComposition");
2462
Mathias Agopian87baae12012-07-31 12:38:26 -07002463 Region dirtyRegion(inDirtyRegion);
2464
Mathias Agopianb8a55602009-06-26 19:06:36 -07002465 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002466 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467
Fabien Sanglard830b8472016-11-30 16:35:58 -08002468 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002469 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002470 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2471 // takes a rectangle, we must make sure to update that whole
2472 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002473 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002474 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002475 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002476 // We need to redraw the rectangle that will be updated
2477 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002478 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002479 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002480 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002481 } else {
2482 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002483 dirtyRegion.set(displayDevice->bounds());
2484 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485 }
2486 }
2487
Fabien Sanglard830b8472016-11-30 16:35:58 -08002488 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002490 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002491 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002492
2493 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002494 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495}
2496
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497bool SurfaceFlinger::doComposeSurfaces(
2498 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002499{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002501
Dan Stoza9e56aa02015-11-02 13:00:03 -08002502 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002503
2504 mat4 oldColorMatrix;
2505 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2506 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2507 if (applyColorMatrix) {
2508 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2509 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2510 }
2511
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2513 if (hasClientComposition) {
2514 ALOGV("hasClientComposition");
2515
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002516#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002517 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002518 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002519#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002520 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002521 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002523 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002524
2525 // |mStateLock| not needed as we are on the main thread
2526 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002527 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2528 }
2529 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002530 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002531
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002532 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2534 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002535 // when using overlays, we assume a fully transparent framebuffer
2536 // NOTE: we could reduce how much we need to clear, for instance
2537 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002538 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002539 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002540 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002541 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002542 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002543 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002544
2545 // we remove the scissor part
2546 // we're left with the letterbox region
2547 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002548 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002549
2550 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002552
2553 // but limit it to the dirty region
2554 region.andSelf(dirty);
2555
Mathias Agopianb9494d52012-04-18 02:28:45 -07002556 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002557 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002558 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002559 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002560 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002561 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002562
Dan Stoza9e56aa02015-11-02 13:00:03 -08002563 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002564 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002565 // scissor on the main display. It should never be needed
2566 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002567 const Rect& bounds(displayDevice->getBounds());
2568 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002569 if (scissor != bounds) {
2570 // scissor doesn't match the screen's dimensions, so we
2571 // need to clear everything outside of it and enable
2572 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002573
Mathias Agopianf45c5102012-10-24 16:29:17 -07002574 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575 const uint32_t height = displayDevice->getHeight();
2576 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002577 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002578 }
2579 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002580 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002581
Mathias Agopian85d751c2012-08-29 16:59:24 -07002582 /*
2583 * and then, render the layers targeted at the framebuffer
2584 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002585
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 ALOGV("Rendering client layers");
2587 const Transform& displayTransform = displayDevice->getTransform();
2588 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002589 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002590 bool firstLayer = true;
2591 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2592 const Region clip(dirty.intersect(
2593 displayTransform.transform(layer->visibleRegion)));
2594 ALOGV("Layer: %s", layer->getName().string());
2595 ALOGV(" Composition type: %s",
2596 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002597 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 switch (layer->getCompositionType(hwcId)) {
2599 case HWC2::Composition::Cursor:
2600 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002601 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002603 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2605 layer->isOpaque(state) && (state.alpha == 1.0f)
2606 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002607 // never clear the very first layer since we're
2608 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002609 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002610 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002611 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002612 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 case HWC2::Composition::Client: {
2614 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002615 break;
2616 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002618 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002619 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 } else {
2621 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002622 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002624 }
2625 } else {
2626 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002628 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002630 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002631 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002632 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002633 }
2634 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002635
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002636 if (applyColorMatrix) {
2637 getRenderEngine().setupColorTransform(oldColorMatrix);
2638 }
2639
Mathias Agopianf45c5102012-10-24 16:29:17 -07002640 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002642 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643}
2644
Fabien Sanglard830b8472016-11-30 16:35:58 -08002645void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2646 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002647 RenderEngine& engine(getRenderEngine());
2648 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649}
2650
Dan Stoza7d89d062015-04-30 13:29:25 -07002651status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002652 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002653 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 const sp<Layer>& lbc,
2655 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002656{
Dan Stoza7d89d062015-04-30 13:29:25 -07002657 // add this layer to the current state list
2658 {
2659 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002661 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2662 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002663 return NO_MEMORY;
2664 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 if (parent == nullptr) {
2666 mCurrentState.layersSortedByZ.add(lbc);
2667 } else {
2668 parent->addChild(lbc);
2669 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002670 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002671 mLayersAdded = true;
2672 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002673 }
2674
Mathias Agopian96f08192010-06-02 23:28:45 -07002675 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002676 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002677
Dan Stoza7d89d062015-04-30 13:29:25 -07002678 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002679}
2680
Robert Carr9524cb32017-02-13 11:32:32 -08002681status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002682 Mutex::Autolock _l(mStateLock);
2683
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684 const auto& p = layer->getParent();
2685 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2686 mCurrentState.layersSortedByZ.remove(layer);
2687
Robert Carr136e2f62017-02-08 17:54:29 -08002688 // As a matter of normal operation, the LayerCleaner will produce a second
2689 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2690 // so we will succeed in promoting it, but it's already been removed
2691 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2692 // otherwise something has gone wrong and we are leaking the layer.
2693 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2695 layer->getName().string(),
2696 (p != nullptr) ? p->getName().string() : "no-parent");
2697 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002698 } else if (index < 0) {
2699 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002700 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701
2702 mLayersPendingRemoval.add(layer);
2703 mLayersRemoved = true;
2704 mNumLayers--;
2705 setTransactionFlags(eTransactionNeeded);
2706 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707}
2708
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002709uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002710 return android_atomic_release_load(&mTransactionFlags);
2711}
2712
Mathias Agopian3f844832013-08-07 21:24:32 -07002713uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2715}
2716
Mathias Agopian3f844832013-08-07 21:24:32 -07002717uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2719 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002720 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 }
2722 return old;
2723}
2724
Mathias Agopian8b33f032012-07-24 20:43:54 -07002725void SurfaceFlinger::setTransactionState(
2726 const Vector<ComposerState>& state,
2727 const Vector<DisplayState>& displays,
2728 uint32_t flags)
2729{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002730 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002731 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002732 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002733
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002734 if (flags & eAnimation) {
2735 // For window updates that are part of an animation we must wait for
2736 // previous animation "frames" to be handled.
2737 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002738 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002739 if (CC_UNLIKELY(err != NO_ERROR)) {
2740 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002741 // caller after a few seconds.
2742 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2743 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002744 mAnimTransactionPending = false;
2745 break;
2746 }
2747 }
2748 }
2749
Mathias Agopiane57f2922012-08-09 16:29:12 -07002750 size_t count = displays.size();
2751 for (size_t i=0 ; i<count ; i++) {
2752 const DisplayState& s(displays[i]);
2753 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002754 }
2755
Mathias Agopiane57f2922012-08-09 16:29:12 -07002756 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002757 for (size_t i=0 ; i<count ; i++) {
2758 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002759 // Here we need to check that the interface we're given is indeed
2760 // one of our own. A malicious client could give us a NULL
2761 // IInterface, or one of its own or even one of our own but a
2762 // different type. All these situations would cause us to crash.
2763 //
2764 // NOTE: it would be better to use RTTI as we could directly check
2765 // that we have a Client*. however, RTTI is disabled in Android.
2766 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002767 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002768 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002769 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002770 sp<Client> client( static_cast<Client *>(s.client.get()) );
2771 transactionFlags |= setClientStateLocked(client, s.state);
2772 }
2773 }
2774 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002775 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002776
Robert Carr2a7dbb42016-05-24 11:41:28 -07002777 // If a synchronous transaction is explicitly requested without any changes,
2778 // force a transaction anyway. This can be used as a flush mechanism for
2779 // previous async transactions.
2780 if (transactionFlags == 0 && (flags & eSynchronous)) {
2781 transactionFlags = eTransactionNeeded;
2782 }
2783
Mathias Agopian386aa982011-11-07 21:58:03 -08002784 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002785 if (mInterceptor.isEnabled()) {
2786 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2787 }
Irvel468051e2016-06-13 16:44:44 -07002788
Mathias Agopian386aa982011-11-07 21:58:03 -08002789 // this triggers the transaction
2790 setTransactionFlags(transactionFlags);
2791
2792 // if this is a synchronous transaction, wait for it to take effect
2793 // before returning.
2794 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002795 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002796 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002797 if (flags & eAnimation) {
2798 mAnimTransactionPending = true;
2799 }
2800 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002801 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2802 if (CC_UNLIKELY(err != NO_ERROR)) {
2803 // just in case something goes wrong in SF, return to the
2804 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002805 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2806 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002807 break;
2808 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002809 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 }
2811}
2812
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2814{
Jesse Hall9a143922012-10-04 16:29:19 -07002815 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2816 if (dpyIdx < 0)
2817 return 0;
2818
Mathias Agopiane57f2922012-08-09 16:29:12 -07002819 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002820 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002821 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002822 const uint32_t what = s.what;
2823 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002824 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002825 disp.surface = s.surface;
2826 flags |= eDisplayTransactionNeeded;
2827 }
2828 }
2829 if (what & DisplayState::eLayerStackChanged) {
2830 if (disp.layerStack != s.layerStack) {
2831 disp.layerStack = s.layerStack;
2832 flags |= eDisplayTransactionNeeded;
2833 }
2834 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002835 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002836 if (disp.orientation != s.orientation) {
2837 disp.orientation = s.orientation;
2838 flags |= eDisplayTransactionNeeded;
2839 }
2840 if (disp.frame != s.frame) {
2841 disp.frame = s.frame;
2842 flags |= eDisplayTransactionNeeded;
2843 }
2844 if (disp.viewport != s.viewport) {
2845 disp.viewport = s.viewport;
2846 flags |= eDisplayTransactionNeeded;
2847 }
2848 }
Michael Lentine47e45402014-07-18 15:34:25 -07002849 if (what & DisplayState::eDisplaySizeChanged) {
2850 if (disp.width != s.width) {
2851 disp.width = s.width;
2852 flags |= eDisplayTransactionNeeded;
2853 }
2854 if (disp.height != s.height) {
2855 disp.height = s.height;
2856 flags |= eDisplayTransactionNeeded;
2857 }
2858 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002859 }
2860 return flags;
2861}
2862
2863uint32_t SurfaceFlinger::setClientStateLocked(
2864 const sp<Client>& client,
2865 const layer_state_t& s)
2866{
2867 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002868 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002869 if (layer != 0) {
2870 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002871 bool geometryAppliesWithResize =
2872 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002873 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002874 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002875 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002876 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002877 }
2878 if (what & layer_state_t::eLayerChanged) {
2879 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 const auto& p = layer->getParent();
2881 if (p == nullptr) {
2882 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2883 if (layer->setLayer(s.z) && idx >= 0) {
2884 mCurrentState.layersSortedByZ.removeAt(idx);
2885 mCurrentState.layersSortedByZ.add(layer);
2886 // we need traversal (state changed)
2887 // AND transaction (list changed)
2888 flags |= eTransactionNeeded|eTraversalNeeded;
2889 }
2890 } else {
2891 if (p->setChildLayer(layer, s.z)) {
2892 flags |= eTransactionNeeded|eTraversalNeeded;
2893 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002894 }
2895 }
Robert Carrdb66e622017-04-10 16:55:57 -07002896 if (what & layer_state_t::eRelativeLayerChanged) {
2897 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2898 flags |= eTransactionNeeded|eTraversalNeeded;
2899 }
2900 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901 if (what & layer_state_t::eSizeChanged) {
2902 if (layer->setSize(s.w, s.h)) {
2903 flags |= eTraversalNeeded;
2904 }
2905 }
2906 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002908 flags |= eTraversalNeeded;
2909 }
2910 if (what & layer_state_t::eMatrixChanged) {
2911 if (layer->setMatrix(s.matrix))
2912 flags |= eTraversalNeeded;
2913 }
2914 if (what & layer_state_t::eTransparentRegionChanged) {
2915 if (layer->setTransparentRegionHint(s.transparentRegion))
2916 flags |= eTraversalNeeded;
2917 }
Dan Stoza23116082015-06-18 14:58:39 -07002918 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002919 if (layer->setFlags(s.flags, s.mask))
2920 flags |= eTraversalNeeded;
2921 }
2922 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002923 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002924 flags |= eTraversalNeeded;
2925 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002926 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002927 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002928 flags |= eTraversalNeeded;
2929 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002930 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002932 // We only allow setting layer stacks for top level layers,
2933 // everything else inherits layer stack from its parent.
2934 if (layer->hasParent()) {
2935 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2936 layer->getName().string());
2937 } else if (idx < 0) {
2938 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2939 "that also does not appear in the top level layer list. Something"
2940 " has gone wrong.", layer->getName().string());
2941 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002942 mCurrentState.layersSortedByZ.removeAt(idx);
2943 mCurrentState.layersSortedByZ.add(layer);
2944 // we need traversal (state changed)
2945 // AND transaction (list changed)
2946 flags |= eTransactionNeeded|eTraversalNeeded;
2947 }
2948 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002949 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002950 if (s.barrierHandle != nullptr) {
2951 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2952 } else if (s.barrierGbp != nullptr) {
2953 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2954 if (authenticateSurfaceTextureLocked(gbp)) {
2955 const auto& otherLayer =
2956 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2957 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2958 } else {
2959 ALOGE("Attempt to defer transaction to to an"
2960 " unrecognized GraphicBufferProducer");
2961 }
2962 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002963 // We don't trigger a traversal here because if no other state is
2964 // changed, we don't want this to cause any more work
2965 }
Robert Carr1db73f62016-12-21 12:58:51 -08002966 if (what & layer_state_t::eReparentChildren) {
2967 if (layer->reparentChildren(s.reparentHandle)) {
2968 flags |= eTransactionNeeded|eTraversalNeeded;
2969 }
2970 }
Robert Carr9524cb32017-02-13 11:32:32 -08002971 if (what & layer_state_t::eDetachChildren) {
2972 layer->detachChildren();
2973 }
Robert Carrc3574f72016-03-24 12:19:32 -07002974 if (what & layer_state_t::eOverrideScalingModeChanged) {
2975 layer->setOverrideScalingMode(s.overrideScalingMode);
2976 // We don't trigger a traversal here because if no other state is
2977 // changed, we don't want this to cause any more work
2978 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002979 }
2980 return flags;
2981}
2982
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002983status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002984 const String8& name,
2985 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002986 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002987 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2988 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002990 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002991 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002992 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002993 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002994 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002995
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002996 status_t result = NO_ERROR;
2997
2998 sp<Layer> layer;
2999
Cody Northropbc755282017-03-31 12:00:08 -06003000 String8 uniqueName = getUniqueLayerName(name);
3001
Mathias Agopian3165cc22012-08-08 19:42:09 -07003002 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3003 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003004 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003005 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003006 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003008 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003009 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003010 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003011 handle, gbp, &layer);
3012 break;
3013 default:
3014 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015 break;
3016 }
3017
Dan Stoza7d89d062015-04-30 13:29:25 -07003018 if (result != NO_ERROR) {
3019 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003021
Albert Chaulk479c60c2017-01-27 14:21:34 -05003022 layer->setInfo(windowType, ownerUid);
3023
Robert Carr1f0a16a2016-10-24 16:27:39 -07003024 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003025 if (result != NO_ERROR) {
3026 return result;
3027 }
Irvelffc9efc2016-07-27 15:16:37 -07003028 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003029
3030 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003031 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032}
3033
Cody Northropbc755282017-03-31 12:00:08 -06003034String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3035{
3036 bool matchFound = true;
3037 uint32_t dupeCounter = 0;
3038
3039 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3040 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3041
3042 // Loop over layers until we're sure there is no matching name
3043 while (matchFound) {
3044 matchFound = false;
3045 mDrawingState.traverseInZOrder([&](Layer* layer) {
3046 if (layer->getName() == uniqueName) {
3047 matchFound = true;
3048 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3049 }
3050 });
3051 }
3052
3053 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3054
3055 return uniqueName;
3056}
3057
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003058status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3059 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3060 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061{
3062 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003063 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 case PIXEL_FORMAT_TRANSPARENT:
3065 case PIXEL_FORMAT_TRANSLUCENT:
3066 format = PIXEL_FORMAT_RGBA_8888;
3067 break;
3068 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003069 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070 break;
3071 }
3072
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003073 *outLayer = new Layer(this, client, name, w, h, flags);
3074 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3075 if (err == NO_ERROR) {
3076 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003077 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003079
3080 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3081 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082}
3083
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003084status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3085 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3086 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003088 *outLayer = new LayerDim(this, client, name, w, h, flags);
3089 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003090 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003091 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003092}
3093
Mathias Agopianac9fa422013-02-11 16:40:36 -08003094status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095{
Robert Carr9524cb32017-02-13 11:32:32 -08003096 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003097 status_t err = NO_ERROR;
3098 sp<Layer> l(client->getLayerUser(handle));
3099 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003100 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003101 err = removeLayer(l);
3102 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3103 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003104 }
3105 return err;
3106}
3107
Mathias Agopian13127d82013-03-05 17:47:11 -08003108status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003109{
Mathias Agopian67106042013-03-14 19:18:13 -07003110 // called by ~LayerCleaner() when all references to the IBinder (handle)
3111 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003112 sp<Layer> l = layer.promote();
3113 if (l == nullptr) {
3114 // The layer has already been removed, carry on
3115 return NO_ERROR;
3116 } if (l->getParent() != nullptr) {
3117 // If we have a parent, then we can continue to live as long as it does.
3118 return NO_ERROR;
3119 }
3120 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121}
3122
Mathias Agopianb60314a2012-04-10 22:09:54 -07003123// ---------------------------------------------------------------------------
3124
Andy McFadden13a082e2012-08-24 10:16:42 -07003125void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003126 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003127 Vector<ComposerState> state;
3128 Vector<DisplayState> displays;
3129 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003130 d.what = DisplayState::eDisplayProjectionChanged |
3131 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003132 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003133 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003134 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003135 d.frame.makeInvalid();
3136 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003137 d.width = 0;
3138 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003139 displays.add(d);
3140 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003141 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003142
Dan Stoza9e56aa02015-11-02 13:00:03 -08003143 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3144 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003145 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003146
Brian Andersond0010582017-03-07 13:20:31 -08003147 // Use phase of 0 since phase is not known.
3148 // Use latency of 0, which will snap to the ideal latency.
3149 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003150}
3151
3152void SurfaceFlinger::initializeDisplays() {
3153 class MessageScreenInitialized : public MessageBase {
3154 SurfaceFlinger* flinger;
3155 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003156 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003157 virtual bool handler() {
3158 flinger->onInitializeDisplays();
3159 return true;
3160 }
3161 };
3162 sp<MessageBase> msg = new MessageScreenInitialized(this);
3163 postMessageAsync(msg); // we may be called from main thread, use async message
3164}
3165
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003166void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3167 int mode) {
3168 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3169 this);
3170 int32_t type = hw->getDisplayType();
3171 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003172
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003173 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003174 return;
3175 }
3176
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003177 hw->setPowerMode(mode);
3178 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3179 ALOGW("Trying to set power mode for virtual display");
3180 return;
3181 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003182
Irvelffc9efc2016-07-27 15:16:37 -07003183 if (mInterceptor.isEnabled()) {
3184 Mutex::Autolock _l(mStateLock);
3185 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3186 if (idx < 0) {
3187 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3188 return;
3189 }
3190 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3191 }
3192
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003193 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003194 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003195 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003196 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3197 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003198 // FIXME: eventthread only knows about the main display right now
3199 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003200 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003203 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003204 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003205 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003206
3207 struct sched_param param = {0};
3208 param.sched_priority = 1;
3209 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3210 ALOGW("Couldn't set SCHED_FIFO on display on");
3211 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003212 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003213 // Turn off the display
3214 struct sched_param param = {0};
3215 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3216 ALOGW("Couldn't set SCHED_OTHER on display off");
3217 }
3218
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003219 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003220 disableHardwareVsync(true); // also cancels any in-progress resync
3221
Mathias Agopiancde87a32012-09-13 14:09:01 -07003222 // FIXME: eventthread only knows about the main display right now
3223 mEventThread->onScreenReleased();
3224 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003225
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003226 getHwComposer().setPowerMode(type, mode);
3227 mVisibleRegionsDirty = true;
3228 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003229 } else if (mode == HWC_POWER_MODE_DOZE ||
3230 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003231 // Update display while dozing
3232 getHwComposer().setPowerMode(type, mode);
3233 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3234 // FIXME: eventthread only knows about the main display right now
3235 mEventThread->onScreenAcquired();
3236 resyncToHardwareVsync(true);
3237 }
3238 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3239 // Leave display going to doze
3240 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3241 disableHardwareVsync(true); // also cancels any in-progress resync
3242 // FIXME: eventthread only knows about the main display right now
3243 mEventThread->onScreenReleased();
3244 }
3245 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003246 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003247 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003248 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003249 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003250}
3251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003252void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3253 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003254 SurfaceFlinger& mFlinger;
3255 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003256 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003257 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003258 MessageSetPowerMode(SurfaceFlinger& flinger,
3259 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3260 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003261 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003263 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003264 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003265 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003266 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003267 ALOGW("Attempt to set power mode = %d for virtual display",
3268 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003269 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003270 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003271 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003272 return true;
3273 }
3274 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003275 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003276 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003277}
3278
3279// ---------------------------------------------------------------------------
3280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3282{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003284
Mathias Agopianbd115332013-04-18 16:41:04 -07003285 IPCThreadState* ipc = IPCThreadState::self();
3286 const int pid = ipc->getCallingPid();
3287 const int uid = ipc->getCallingUid();
3288 if ((uid != AID_SHELL) &&
3289 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003290 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003291 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003293 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003294 // (this would indicate SF is stuck, but we want to be able to
3295 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003296 status_t err = mStateLock.timedLock(s2ns(1));
3297 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003298 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003299 result.appendFormat(
3300 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3301 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003302 }
3303
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003304 bool dumpAll = true;
3305 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003306 size_t numArgs = args.size();
3307 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003308 if ((index < numArgs) &&
3309 (args[index] == String16("--list"))) {
3310 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003311 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003312 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003313 }
3314
3315 if ((index < numArgs) &&
3316 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003317 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003318 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003319 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003320 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003321
3322 if ((index < numArgs) &&
3323 (args[index] == String16("--latency-clear"))) {
3324 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003325 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003326 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003327 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003328
3329 if ((index < numArgs) &&
3330 (args[index] == String16("--dispsync"))) {
3331 index++;
3332 mPrimaryDispSync.dump(result);
3333 dumpAll = false;
3334 }
Dan Stozab90cf072015-03-05 11:05:59 -08003335
3336 if ((index < numArgs) &&
3337 (args[index] == String16("--static-screen"))) {
3338 index++;
3339 dumpStaticScreenStats(result);
3340 dumpAll = false;
3341 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003342
3343 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003344 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003345 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003346 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003347 dumpAll = false;
3348 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003349
3350 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3351 index++;
3352 dumpWideColorInfo(result);
3353 dumpAll = false;
3354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003356
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003357 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003358 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003359 }
3360
Mathias Agopian9795c422009-08-26 16:36:26 -07003361 if (locked) {
3362 mStateLock.unlock();
3363 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364 }
3365 write(fd, result.string(), result.size());
3366 return NO_ERROR;
3367}
3368
Dan Stozac7014012014-02-14 15:03:43 -08003369void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3370 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003371{
Robert Carr2047fae2016-11-28 14:09:09 -08003372 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003373 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003374 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003375}
3376
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003377void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003378 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003379{
3380 String8 name;
3381 if (index < args.size()) {
3382 name = String8(args[index]);
3383 index++;
3384 }
3385
Dan Stoza9e56aa02015-11-02 13:00:03 -08003386 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3387 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003388 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003389
3390 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003391 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003392 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003393 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003394 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003395 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003396 }
Robert Carr2047fae2016-11-28 14:09:09 -08003397 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003398 }
3399}
3400
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003401void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003402 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003403{
3404 String8 name;
3405 if (index < args.size()) {
3406 name = String8(args[index]);
3407 index++;
3408 }
3409
Robert Carr2047fae2016-11-28 14:09:09 -08003410 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003411 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003412 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003413 }
Robert Carr2047fae2016-11-28 14:09:09 -08003414 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003415
Svetoslavd85084b2014-03-20 10:28:31 -07003416 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003417}
3418
Jamie Gennis6547ff42013-07-16 20:12:42 -07003419// This should only be called from the main thread. Otherwise it would need
3420// the lock and should use mCurrentState rather than mDrawingState.
3421void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003422 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003423 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003424 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003425
3426 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3427}
3428
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003429void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003430{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003431 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003432 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3433
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003434 if (isLayerTripleBufferingDisabled())
3435 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003436
3437 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003438 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003439 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003440 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003441 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3442 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003443 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003444}
3445
Dan Stozab90cf072015-03-05 11:05:59 -08003446void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3447{
3448 result.appendFormat("Static screen stats:\n");
3449 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3450 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3451 float percent = 100.0f *
3452 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3453 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3454 b + 1, bucketTimeSec, percent);
3455 }
3456 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3457 float percent = 100.0f *
3458 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3459 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3460 NUM_BUCKETS - 1, bucketTimeSec, percent);
3461}
3462
Dan Stozae77c7662016-05-13 11:37:28 -07003463void SurfaceFlinger::recordBufferingStats(const char* layerName,
3464 std::vector<OccupancyTracker::Segment>&& history) {
3465 Mutex::Autolock lock(mBufferingStatsMutex);
3466 auto& stats = mBufferingStats[layerName];
3467 for (const auto& segment : history) {
3468 if (!segment.usedThirdBuffer) {
3469 stats.twoBufferTime += segment.totalTime;
3470 }
3471 if (segment.occupancyAverage < 1.0f) {
3472 stats.doubleBufferedTime += segment.totalTime;
3473 } else if (segment.occupancyAverage < 2.0f) {
3474 stats.tripleBufferedTime += segment.totalTime;
3475 }
3476 ++stats.numSegments;
3477 stats.totalTime += segment.totalTime;
3478 }
3479}
3480
Brian Andersond6927fb2016-07-23 23:37:30 -07003481void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3482 result.appendFormat("Layer frame timestamps:\n");
3483
3484 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3485 const size_t count = currentLayers.size();
3486 for (size_t i=0 ; i<count ; i++) {
3487 currentLayers[i]->dumpFrameEvents(result);
3488 }
3489}
3490
Dan Stozae77c7662016-05-13 11:37:28 -07003491void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3492 result.append("Buffering stats:\n");
3493 result.append(" [Layer name] <Active time> <Two buffer> "
3494 "<Double buffered> <Triple buffered>\n");
3495 Mutex::Autolock lock(mBufferingStatsMutex);
3496 typedef std::tuple<std::string, float, float, float> BufferTuple;
3497 std::map<float, BufferTuple, std::greater<float>> sorted;
3498 for (const auto& statsPair : mBufferingStats) {
3499 const char* name = statsPair.first.c_str();
3500 const BufferingStats& stats = statsPair.second;
3501 if (stats.numSegments == 0) {
3502 continue;
3503 }
3504 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3505 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3506 stats.totalTime;
3507 float doubleBufferRatio = static_cast<float>(
3508 stats.doubleBufferedTime) / stats.totalTime;
3509 float tripleBufferRatio = static_cast<float>(
3510 stats.tripleBufferedTime) / stats.totalTime;
3511 sorted.insert({activeTime, {name, twoBufferRatio,
3512 doubleBufferRatio, tripleBufferRatio}});
3513 }
3514 for (const auto& sortedPair : sorted) {
3515 float activeTime = sortedPair.first;
3516 const BufferTuple& values = sortedPair.second;
3517 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3518 std::get<0>(values).c_str(), activeTime,
3519 std::get<1>(values), std::get<2>(values),
3520 std::get<3>(values));
3521 }
3522 result.append("\n");
3523}
3524
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003525void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3526 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3527
3528 // TODO: print out if wide-color mode is active or not
3529
3530 for (size_t d = 0; d < mDisplays.size(); d++) {
3531 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3532 int32_t hwcId = displayDevice->getHwcDisplayId();
3533 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3534 continue;
3535 }
3536
3537 result.appendFormat("Display %d color modes:\n", hwcId);
3538 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3539 for (auto&& mode : modes) {
3540 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3541 }
3542
3543 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3544 result.appendFormat(" Current color mode: %s (%d)\n",
3545 decodeColorMode(currentMode).c_str(), currentMode);
3546 }
3547 result.append("\n");
3548}
3549
Mathias Agopian74d211a2013-04-22 16:55:35 +02003550void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3551 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003552{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003553 bool colorize = false;
3554 if (index < args.size()
3555 && (args[index] == String16("--color"))) {
3556 colorize = true;
3557 index++;
3558 }
3559
3560 Colorizer colorizer(colorize);
3561
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003562 // figure out if we're stuck somewhere
3563 const nsecs_t now = systemTime();
3564 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3565 const nsecs_t inTransaction(mDebugInTransaction);
3566 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3567 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3568
3569 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003570 * Dump library configuration.
3571 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003572
3573 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003574 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003575 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003576 appendSfConfigString(result);
3577 appendUiConfigString(result);
3578 appendGuiConfigString(result);
3579 result.append("\n");
3580
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003581 result.append("\nWide-Color information:\n");
3582 dumpWideColorInfo(result);
3583
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003584 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003585 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003586 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003587 result.append(SyncFeatures::getInstance().toString());
3588 result.append("\n");
3589
Dan Stoza9e56aa02015-11-02 13:00:03 -08003590 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3591
Andy McFadden41d67d72014-04-25 16:58:34 -07003592 colorizer.bold(result);
3593 result.append("DispSync configuration: ");
3594 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003595 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003596 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003597 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003598 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003599 result.append("\n");
3600
Dan Stozab90cf072015-03-05 11:05:59 -08003601 // Dump static screen stats
3602 result.append("\n");
3603 dumpStaticScreenStats(result);
3604 result.append("\n");
3605
Dan Stozae77c7662016-05-13 11:37:28 -07003606 dumpBufferingStats(result);
3607
Andy McFadden4803b742012-09-24 19:07:20 -07003608 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003609 * Dump the visible layer list
3610 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003611 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003612 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003613 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003614 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003615 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003616 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003617
3618 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003619 * Dump Display state
3620 */
3621
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003622 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003623 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003624 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003625 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3626 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003627 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003628 }
3629
3630 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003631 * Dump SurfaceFlinger global state
3632 */
3633
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003634 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003635 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003636 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003637
Mathias Agopian888c8222012-08-04 21:10:38 -07003638 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003639 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003640
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003641 colorizer.bold(result);
3642 result.appendFormat("EGL implementation : %s\n",
3643 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3644 colorizer.reset(result);
3645 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003646 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003647
Mathias Agopian875d8e12013-06-07 15:35:48 -07003648 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003649
Mathias Agopian42977342012-08-05 00:40:46 -07003650 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003651 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3652 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003653 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003654 " last eglSwapBuffers() time: %f us\n"
3655 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003656 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003657 " refresh-rate : %f fps\n"
3658 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003659 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003660 " gpu_to_cpu_unsupported : %d\n"
3661 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003662 mLastSwapBufferTime/1000.0,
3663 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003664 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003665 1e9 / activeConfig->getVsyncPeriod(),
3666 activeConfig->getDpiX(),
3667 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003668 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003669
Mathias Agopian74d211a2013-04-22 16:55:35 +02003670 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003671 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672
Mathias Agopian74d211a2013-04-22 16:55:35 +02003673 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003674 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675
3676 /*
3677 * VSYNC state
3678 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003679 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003680 result.append("\n");
3681
3682 /*
3683 * HWC layer minidump
3684 */
3685 for (size_t d = 0; d < mDisplays.size(); d++) {
3686 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3687 int32_t hwcId = displayDevice->getHwcDisplayId();
3688 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3689 continue;
3690 }
3691
3692 result.appendFormat("Display %d HWC layers:\n", hwcId);
3693 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003694 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003695 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003696 });
Dan Stozae22aec72016-08-01 13:20:59 -07003697 result.append("\n");
3698 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003699
3700 /*
3701 * Dump HWComposer state
3702 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003703 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003704 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003705 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003706 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003707 result.appendFormat(" h/w composer %s\n",
3708 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003709 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003710
3711 /*
3712 * Dump gralloc state
3713 */
3714 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3715 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716}
3717
Mathias Agopian13127d82013-03-05 17:47:11 -08003718const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003719SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003720 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003721 wp<IBinder> dpy;
3722 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3723 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3724 dpy = mDisplays.keyAt(i);
3725 break;
3726 }
3727 }
3728 if (dpy == NULL) {
3729 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3730 // Just use the primary display so we have something to return
3731 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3732 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003733 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003734}
3735
Keun young Park63f165f2012-08-31 10:53:36 -07003736bool SurfaceFlinger::startDdmConnection()
3737{
3738 void* libddmconnection_dso =
3739 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3740 if (!libddmconnection_dso) {
3741 return false;
3742 }
3743 void (*DdmConnection_start)(const char* name);
3744 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003745 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003746 if (!DdmConnection_start) {
3747 dlclose(libddmconnection_dso);
3748 return false;
3749 }
3750 (*DdmConnection_start)(getServiceName());
3751 return true;
3752}
3753
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003754status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 switch (code) {
3756 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003757 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003759 case CLEAR_ANIMATION_FRAME_STATS:
3760 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003762 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763 {
3764 // codes that require permission check
3765 IPCThreadState* ipc = IPCThreadState::self();
3766 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003767 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003768 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003769 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003770 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003771 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003772 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003773 break;
3774 }
Robert Carr1db73f62016-12-21 12:58:51 -08003775 /*
3776 * Calling setTransactionState is safe, because you need to have been
3777 * granted a reference to Client* and Handle* to do anything with it.
3778 *
3779 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3780 */
3781 case SET_TRANSACTION_STATE:
3782 case CREATE_SCOPED_CONNECTION:
3783 {
3784 return OK;
3785 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003786 case CAPTURE_SCREEN:
3787 {
3788 // codes that require permission check
3789 IPCThreadState* ipc = IPCThreadState::self();
3790 const int pid = ipc->getCallingPid();
3791 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003792 if ((uid != AID_GRAPHICS) &&
3793 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003794 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003795 return PERMISSION_DENIED;
3796 }
3797 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798 }
3799 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003800 return OK;
3801}
3802
3803status_t SurfaceFlinger::onTransact(
3804 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3805{
3806 status_t credentialCheck = CheckTransactCodeCredentials(code);
3807 if (credentialCheck != OK) {
3808 return credentialCheck;
3809 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003810
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3812 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003813 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003814 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003815 IPCThreadState* ipc = IPCThreadState::self();
3816 const int pid = ipc->getCallingPid();
3817 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003818 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003819 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 return PERMISSION_DENIED;
3821 }
3822 int n;
3823 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003824 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003825 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 return NO_ERROR;
3827 case 1002: // SHOW_UPDATES
3828 n = data.readInt32();
3829 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003830 invalidateHwcGeometry();
3831 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003834 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003835 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003837 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003838 setTransactionFlags(
3839 eTransactionNeeded|
3840 eDisplayTransactionNeeded|
3841 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003842 return NO_ERROR;
3843 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003844 case 1006:{ // send empty update
3845 signalRefresh();
3846 return NO_ERROR;
3847 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003848 case 1008: // toggle use of hw composer
3849 n = data.readInt32();
3850 mDebugDisableHWC = n ? 1 : 0;
3851 invalidateHwcGeometry();
3852 repaintEverything();
3853 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003854 case 1009: // toggle use of transform hint
3855 n = data.readInt32();
3856 mDebugDisableTransformHint = n ? 1 : 0;
3857 invalidateHwcGeometry();
3858 repaintEverything();
3859 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003861 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003862 reply->writeInt32(0);
3863 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003864 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003865 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 return NO_ERROR;
3867 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003868 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003869 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003870 return NO_ERROR;
3871 }
3872 case 1014: {
3873 // daltonize
3874 n = data.readInt32();
3875 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003876 case 1:
3877 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3878 break;
3879 case 2:
3880 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3881 break;
3882 case 3:
3883 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3884 break;
3885 default:
3886 mDaltonizer.setType(ColorBlindnessType::None);
3887 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003888 }
3889 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003890 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003891 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003892 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003893 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003894 invalidateHwcGeometry();
3895 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003898 case 1015: {
3899 // apply a color matrix
3900 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003901 if (n) {
Romain Guy88d37dd2017-05-26 17:57:05 -07003902 // color matrix is sent as a row-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003903 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003904 for (size_t j = 0; j < 4; j++) {
3905 mColorMatrix[i][j] = data.readFloat();
3906 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003907 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003908 } else {
3909 mColorMatrix = mat4();
3910 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003911
3912 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3913 // the division by w in the fragment shader
3914 float4 lastRow(transpose(mColorMatrix)[3]);
3915 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3916 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3917 }
3918
Alan Viverette9c5a3332013-09-12 20:04:35 -07003919 invalidateHwcGeometry();
3920 repaintEverything();
3921 return NO_ERROR;
3922 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003923 // This is an experimental interface
3924 // Needs to be shifted to proper binder interface when we productize
3925 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003926 n = data.readInt32();
3927 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003928 return NO_ERROR;
3929 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003930 case 1017: {
3931 n = data.readInt32();
3932 mForceFullDamage = static_cast<bool>(n);
3933 return NO_ERROR;
3934 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003935 case 1018: { // Modify Choreographer's phase offset
3936 n = data.readInt32();
3937 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3938 return NO_ERROR;
3939 }
3940 case 1019: { // Modify SurfaceFlinger's phase offset
3941 n = data.readInt32();
3942 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3943 return NO_ERROR;
3944 }
Irvel468051e2016-06-13 16:44:44 -07003945 case 1020: { // Layer updates interceptor
3946 n = data.readInt32();
3947 if (n) {
3948 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003949 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003950 }
3951 else{
3952 ALOGV("Interceptor disabled");
3953 mInterceptor.disable();
3954 }
3955 return NO_ERROR;
3956 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003957 case 1021: { // Disable HWC virtual displays
3958 n = data.readInt32();
3959 mUseHwcVirtualDisplays = !n;
3960 return NO_ERROR;
3961 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 }
3963 }
3964 return err;
3965}
3966
Mathias Agopian53331da2011-08-22 21:44:41 -07003967void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003968 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003969 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003970}
3971
Mathias Agopian59119e62010-10-11 12:37:43 -07003972// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003973// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003974// ---------------------------------------------------------------------------
3975
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003976/* The code below is here to handle b/8734824
3977 *
3978 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003979 * from the surfaceflinger thread to the calling binder thread, where they
3980 * are executed. This allows the calling thread in the calling process to be
3981 * reused and not depend on having "enough" binder threads to handle the
3982 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003983 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003984class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003985 /* Parts of GraphicProducerWrapper are run on two different threads,
3986 * communicating by sending messages via Looper but also by shared member
3987 * data. Coherence maintenance is subtle and in places implicit (ugh).
3988 *
3989 * Don't rely on Looper's sendMessage/handleMessage providing
3990 * release/acquire semantics for any data not actually in the Message.
3991 * Data going from surfaceflinger to binder threads needs to be
3992 * synchronized explicitly.
3993 *
3994 * Barrier open/wait do provide release/acquire semantics. This provides
3995 * implicit synchronization for data coming back from binder to
3996 * surfaceflinger threads.
3997 */
3998
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003999 sp<IGraphicBufferProducer> impl;
4000 sp<Looper> looper;
4001 status_t result;
4002 bool exitPending;
4003 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07004004 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004005 uint32_t code;
4006 Parcel const* data;
4007 Parcel* reply;
4008
4009 enum {
4010 MSG_API_CALL,
4011 MSG_EXIT
4012 };
4013
4014 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004015 * Called on surfaceflinger thread. This is called by our "fake"
4016 * BpGraphicBufferProducer. We package the data and reply Parcel and
4017 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004018 */
4019 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08004020 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004021 this->code = code;
4022 this->data = &data;
4023 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004024 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004025 // if we've exited, we run the message synchronously right here.
4026 // note (JH): as far as I can tell from looking at the code, this
4027 // never actually happens. if it does, i'm not sure if it happens
4028 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004029 handleMessage(Message(MSG_API_CALL));
4030 } else {
4031 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004032 // Prevent stores to this->{code, data, reply} from being
4033 // reordered later than the construction of Message.
4034 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004035 looper->sendMessage(this, Message(MSG_API_CALL));
4036 barrier.wait();
4037 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004038 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004039 }
4040
4041 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004042 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004043 * call the real BpGraphicBufferProducer.
4044 */
4045 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004046 int what = message.what;
4047 // Prevent reads below from happening before the read from Message
4048 atomic_thread_fence(memory_order_acquire);
4049 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004050 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004051 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004052 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004053 exitRequested = true;
4054 }
4055 }
4056
4057public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004058 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004059 : impl(impl),
4060 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004061 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004062 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004063 exitRequested(false),
4064 code(0),
4065 data(NULL),
4066 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004067 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004068
Jesse Hallb154c422014-07-13 12:47:02 -07004069 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004070 status_t waitForResponse() {
4071 do {
4072 looper->pollOnce(-1);
4073 } while (!exitRequested);
4074 return result;
4075 }
4076
Jesse Hallb154c422014-07-13 12:47:02 -07004077 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004078 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004079 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004080 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004081 // Ensure this->result is visible to the binder thread before it
4082 // handles the message.
4083 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004084 looper->sendMessage(this, Message(MSG_EXIT));
4085 }
4086};
4087
4088
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004089status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4090 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004091 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004092 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004093 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004094
4095 if (CC_UNLIKELY(display == 0))
4096 return BAD_VALUE;
4097
4098 if (CC_UNLIKELY(producer == 0))
4099 return BAD_VALUE;
4100
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004101 // if we have secure windows on this display, never allow the screen capture
4102 // unless the producer interface is local (i.e.: we can take a screenshot for
4103 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004104 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004105
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004106 // Convert to surfaceflinger's internal rotation type.
4107 Transform::orientation_flags rotationFlags;
4108 switch (rotation) {
4109 case ISurfaceComposer::eRotateNone:
4110 rotationFlags = Transform::ROT_0;
4111 break;
4112 case ISurfaceComposer::eRotate90:
4113 rotationFlags = Transform::ROT_90;
4114 break;
4115 case ISurfaceComposer::eRotate180:
4116 rotationFlags = Transform::ROT_180;
4117 break;
4118 case ISurfaceComposer::eRotate270:
4119 rotationFlags = Transform::ROT_270;
4120 break;
4121 default:
4122 rotationFlags = Transform::ROT_0;
4123 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4124 break;
4125 }
4126
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004127 class MessageCaptureScreen : public MessageBase {
4128 SurfaceFlinger* flinger;
4129 sp<IBinder> display;
4130 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004131 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004132 uint32_t reqWidth, reqHeight;
4133 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004134 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004135 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004136 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004137 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004138 public:
4139 MessageCaptureScreen(SurfaceFlinger* flinger,
4140 const sp<IBinder>& display,
4141 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004142 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004143 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004144 bool useIdentityTransform,
4145 Transform::orientation_flags rotation,
4146 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004147 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004148 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004149 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004150 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004151 rotation(rotation), result(PERMISSION_DENIED),
4152 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004153 {
4154 }
4155 status_t getResult() const {
4156 return result;
4157 }
4158 virtual bool handler() {
4159 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004160 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004161 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004162 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004163 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004164 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004165 return true;
4166 }
4167 };
4168
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004169 // this creates a "fake" BBinder which will serve as a "fake" remote
4170 // binder to receive the marshaled calls and forward them to the
4171 // real remote (a BpGraphicBufferProducer)
4172 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4173
4174 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4175 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004176 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004177 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004178 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004179 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004180
4181 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004182 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004183 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004184 }
4185 return res;
4186}
4187
Mathias Agopian180f10d2013-04-10 22:55:41 -07004188
4189void SurfaceFlinger::renderScreenImplLocked(
4190 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004191 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004192 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004193 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004194{
4195 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004196 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004197
4198 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004199 const int32_t hw_w = hw->getWidth();
4200 const int32_t hw_h = hw->getHeight();
4201 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004202 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004203
Dan Stozac1879002014-05-22 15:59:05 -07004204 // if a default or invalid sourceCrop is passed in, set reasonable values
4205 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4206 !sourceCrop.isValid()) {
4207 sourceCrop.setLeftTop(Point(0, 0));
4208 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4209 }
4210
4211 // ensure that sourceCrop is inside screen
4212 if (sourceCrop.left < 0) {
4213 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4214 }
Dan Stozabe31f442014-06-11 11:20:54 -07004215 if (sourceCrop.right > hw_w) {
4216 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004217 }
4218 if (sourceCrop.top < 0) {
4219 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4220 }
Dan Stozabe31f442014-06-11 11:20:54 -07004221 if (sourceCrop.bottom > hw_h) {
4222 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004223 }
4224
Romain Guy88d37dd2017-05-26 17:57:05 -07004225#ifdef USE_HWC2
4226 engine.setWideColor(hw->getWideColorSupport());
4227 engine.setColorMode(hw->getActiveColorMode());
4228#endif
4229
Mathias Agopian180f10d2013-04-10 22:55:41 -07004230 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004231 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004232
4233 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004234 engine.setViewportAndProjection(
4235 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004236 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004237
4238 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004239 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004240
Robert Carr1f0a16a2016-10-24 16:27:39 -07004241 // We loop through the first level of layers without traversing,
4242 // as we need to interpret min/max layer Z in the top level Z space.
4243 for (const auto& layer : mDrawingState.layersSortedByZ) {
4244 if (layer->getLayerStack() != hw->getLayerStack()) {
4245 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004246 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004247 const Layer::State& state(layer->getDrawingState());
4248 if (state.z < minLayerZ || state.z > maxLayerZ) {
4249 continue;
4250 }
Dan Stoza412903f2017-04-27 13:42:17 -07004251 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004252 if (!layer->isVisible()) {
4253 return;
4254 }
4255 if (filtering) layer->setFiltering(true);
4256 layer->draw(hw, useIdentityTransform);
4257 if (filtering) layer->setFiltering(false);
4258 });
4259 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004260
Mathias Agopian931bda12013-08-28 18:11:46 -07004261 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004262}
4263
4264
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004265status_t SurfaceFlinger::captureScreenImplLocked(
4266 const sp<const DisplayDevice>& hw,
4267 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004268 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004269 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004270 bool useIdentityTransform, Transform::orientation_flags rotation,
4271 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004272{
4273 ATRACE_CALL();
4274
Mathias Agopian180f10d2013-04-10 22:55:41 -07004275 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004276 uint32_t hw_w = hw->getWidth();
4277 uint32_t hw_h = hw->getHeight();
4278
4279 if (rotation & Transform::ROT_90) {
4280 std::swap(hw_w, hw_h);
4281 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004282
Mathias Agopian180f10d2013-04-10 22:55:41 -07004283 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4284 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4285 reqWidth, reqHeight, hw_w, hw_h);
4286 return BAD_VALUE;
4287 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004288
Mathias Agopian180f10d2013-04-10 22:55:41 -07004289 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4290 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4291
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004292 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004293 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004294 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004295 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4296 (state.z < minLayerZ || state.z > maxLayerZ)) {
4297 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004298 }
Dan Stoza412903f2017-04-27 13:42:17 -07004299 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004300 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4301 layer->isSecure());
4302 });
4303 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004304
4305 if (!isLocalScreenshot && secureLayerIsVisible) {
4306 ALOGW("FB is protected: PERMISSION_DENIED");
4307 return PERMISSION_DENIED;
4308 }
4309
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004310 // create a surface (because we're a producer, and we need to
4311 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004312 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004313
4314 // Put the screenshot Surface into async mode so that
4315 // Layer::headFenceHasSignaled will always return true and we'll latch the
4316 // first buffer regardless of whether or not its acquire fence has
4317 // signaled. This is needed to avoid a race condition in the rotation
4318 // animation. See b/30209608
4319 sur->setAsyncMode(true);
4320
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004321 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004322
Michael Lentine5a16a622015-05-21 13:48:24 -07004323 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4324 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004325 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4326 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004327
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004328 int err = 0;
4329 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004330 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004331 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4332 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004333
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004334 if (err == NO_ERROR) {
4335 ANativeWindowBuffer* buffer;
4336 /* TODO: Once we have the sync framework everywhere this can use
4337 * server-side waits on the fence that dequeueBuffer returns.
4338 */
4339 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4340 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004341 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004342 // create an EGLImage from the buffer so we can later
4343 // turn it into a texture
4344 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4345 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4346 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004347 // this binds the given EGLImage as a framebuffer for the
4348 // duration of this scope.
4349 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4350 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004351 // this will in fact render into our dequeued buffer
4352 // via an FBO, which means we didn't have to create
4353 // an EGLSurface and therefore we're not
4354 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004355 renderScreenImplLocked(
4356 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4357 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004358
Romain Guy8ec6ff22017-05-31 19:22:30 -07004359#ifdef USE_HWC2
4360 if (hasWideColorDisplay) {
4361 native_window_set_buffers_data_space(window,
4362 getRenderEngine().usesWideColor() ?
4363 HAL_DATASPACE_DISPLAY_P3 : HAL_DATASPACE_V0_SRGB);
4364 }
4365#endif
4366
Riley Andrews86639902014-08-15 12:27:24 -07004367 // Attempt to create a sync khr object that can produce a sync point. If that
4368 // isn't available, create a non-dupable sync object in the fallback path and
4369 // wait on it directly.
4370 EGLSyncKHR sync;
4371 if (!DEBUG_SCREENSHOTS) {
4372 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004373 // native fence fd will not be populated until flush() is done.
4374 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004375 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004376 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004377 }
Riley Andrews86639902014-08-15 12:27:24 -07004378 if (sync != EGL_NO_SYNC_KHR) {
4379 // get the sync fd
4380 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4381 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4382 ALOGW("captureScreen: failed to dup sync khr object");
4383 syncFd = -1;
4384 }
4385 eglDestroySyncKHR(mEGLDisplay, sync);
4386 } else {
4387 // fallback path
4388 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4389 if (sync != EGL_NO_SYNC_KHR) {
4390 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4391 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4392 EGLint eglErr = eglGetError();
4393 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4394 ALOGW("captureScreen: fence wait timed out");
4395 } else {
4396 ALOGW_IF(eglErr != EGL_SUCCESS,
4397 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4398 }
4399 eglDestroySyncKHR(mEGLDisplay, sync);
4400 } else {
4401 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4402 }
4403 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004404 if (DEBUG_SCREENSHOTS) {
4405 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4406 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4407 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4408 hw, minLayerZ, maxLayerZ);
4409 delete [] pixels;
4410 }
4411
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004412 } else {
4413 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4414 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004415 window->cancelBuffer(window, buffer, syncFd);
4416 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004417 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004418 // destroy our image
4419 eglDestroyImageKHR(mEGLDisplay, image);
4420 } else {
4421 result = BAD_VALUE;
4422 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004423 if (buffer) {
4424 // queueBuffer takes ownership of syncFd
4425 result = window->queueBuffer(window, buffer, syncFd);
4426 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004427 }
4428 } else {
4429 result = BAD_VALUE;
4430 }
4431 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4432 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004433
Mathias Agopian74c40c02010-09-29 13:02:36 -07004434 return result;
4435}
4436
Mathias Agopiand5556842013-09-19 17:08:37 -07004437void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004438 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004439 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004440 for (size_t y=0 ; y<h ; y++) {
4441 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4442 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004443 if (p[x] != 0xFF000000) return;
4444 }
4445 }
4446 ALOGE("*** we just took a black screenshot ***\n"
4447 "requested minz=%d, maxz=%d, layerStack=%d",
4448 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004449
Robert Carr2047fae2016-11-28 14:09:09 -08004450 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004451 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004452 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004453 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4454 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004455 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004456 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4457 layer->isVisible() ? '+' : '-',
4458 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004459 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004460 i++;
4461 });
4462 }
4463 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004464 }
4465}
4466
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004467// ---------------------------------------------------------------------------
4468
Dan Stoza412903f2017-04-27 13:42:17 -07004469void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4470 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004471}
4472
Dan Stoza412903f2017-04-27 13:42:17 -07004473void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4474 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004475}
4476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004478
4479
4480#if defined(__gl_h_)
4481#error "don't include gl/gl.h in this file"
4482#endif
4483
4484#if defined(__gl2_h_)
4485#error "don't include gl2/gl2.h in this file"
4486#endif