blob: 9df49f669e363daef0f1287201c79cf97e32adb8 [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
Mathias Agopianc666cae2012-07-25 18:56:13 -070040#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070041#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Romain Guyf8b4ca52017-03-16 18:39:20 +000047#include <gui/GraphicBufferAlloc.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;
Mathias Agopian99b49842011-06-27 16:05:52 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700123 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700125 mTransactionPending(false),
126 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700127 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700128 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700129 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800130 mHwc(nullptr),
131 mRealHwc(nullptr),
132 mVrHwc(nullptr),
133 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800135 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800138 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700140 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700141 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700142 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700143 mDebugInSwapBuffers(0),
144 mLastSwapBufferTime(0),
145 mDebugInTransaction(0),
146 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700147 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700148 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800149 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000150 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700151 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700152 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800153 mHasColorMatrix(false),
154 mHasPoweredOff(false),
155 mFrameBuckets(),
156 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700157 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800158 mNumLayers(0),
159 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800161 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800162
163 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
164 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
165
166 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
168
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800169 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700172 useContextPriority = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::useContextPriority>(false);
174
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700175 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
177
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700178 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
180
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800181 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
183
Steven Thomas050b2c82017-03-06 11:45:16 -0800184 // Vr flinger is only enabled on Daydream ready devices.
185 useVrFlinger = getBool< ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::useVrFlinger>(false);
187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188 // debugging stuff...
189 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700190
Mathias Agopianb4b17302013-03-20 18:36:41 -0700191 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700192 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 property_get("debug.sf.showupdates", value, "0");
195 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700197 property_get("debug.sf.ddms", value, "0");
198 mDebugDDMS = atoi(value);
199 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700200 if (!startDdmConnection()) {
201 // start failed, and DDMS debugging not enabled
202 mDebugDDMS = 0;
203 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700205 ALOGI_IF(mDebugRegion, "showupdates enabled");
206 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700207
208 property_get("debug.sf.disable_backpressure", value, "0");
209 mPropagateBackpressure = !atoi(value);
210 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700211
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800212 property_get("debug.sf.enable_hwc_vds", value, "0");
213 mUseHwcVirtualDisplays = atoi(value);
214 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800215
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800216 property_get("ro.sf.disable_triple_buffer", value, "1");
217 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800218 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219}
220
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800221void SurfaceFlinger::onFirstRef()
222{
223 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224}
225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226SurfaceFlinger::~SurfaceFlinger()
227{
Mathias Agopiana4912602012-07-12 14:25:33 -0700228 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
229 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
230 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231}
232
Dan Stozac7014012014-02-14 15:03:43 -0800233void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800234{
235 // the window manager died on us. prepare its eulogy.
236
Andy McFadden13a082e2012-08-24 10:16:42 -0700237 // restore initial conditions (default device unblank, etc)
238 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800239
240 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700241 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242}
243
Robert Carr1db73f62016-12-21 12:58:51 -0800244static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700245 status_t err = client->initCheck();
246 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800247 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 }
Robert Carr1db73f62016-12-21 12:58:51 -0800249 return nullptr;
250}
251
252sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
253 return initClient(new Client(this));
254}
255
256sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
257 const sp<IGraphicBufferProducer>& gbp) {
258 if (authenticateSurfaceTexture(gbp) == false) {
259 return nullptr;
260 }
261 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
262 if (layer == nullptr) {
263 return nullptr;
264 }
265
266 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267}
268
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700269sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
270 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700271{
272 class DisplayToken : public BBinder {
273 sp<SurfaceFlinger> flinger;
274 virtual ~DisplayToken() {
275 // no more references, this display must be terminated
276 Mutex::Autolock _l(flinger->mStateLock);
277 flinger->mCurrentState.displays.removeItem(this);
278 flinger->setTransactionFlags(eDisplayTransactionNeeded);
279 }
280 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700281 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700282 : flinger(flinger) {
283 }
284 };
285
286 sp<BBinder> token = new DisplayToken(this);
287
288 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700289 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700290 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700292 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293 return token;
294}
295
Jesse Hall6c913be2013-08-08 12:15:49 -0700296void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
297 Mutex::Autolock _l(mStateLock);
298
299 ssize_t idx = mCurrentState.displays.indexOfKey(display);
300 if (idx < 0) {
301 ALOGW("destroyDisplay: invalid display token");
302 return;
303 }
304
305 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
306 if (!info.isVirtualDisplay()) {
307 ALOGE("destroyDisplay called for non-virtual display");
308 return;
309 }
Irvelffc9efc2016-07-27 15:16:37 -0700310 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700311 mCurrentState.displays.removeItemsAt(idx);
312 setTransactionFlags(eDisplayTransactionNeeded);
313}
314
Jesse Hall692c7232012-11-08 15:41:56 -0800315void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800316 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800317 ALOGW_IF(mBuiltinDisplays[type],
318 "Overwriting display token for display type %d", type);
319 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800320 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700321 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800322 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800324}
325
Mathias Agopiane57f2922012-08-09 16:29:12 -0700326sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700327 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
329 return NULL;
330 }
Jesse Hall692c7232012-11-08 15:41:56 -0800331 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332}
333
Romain Guyf8b4ca52017-03-16 18:39:20 +0000334sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
335{
336 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
337 return gba;
338}
339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340void SurfaceFlinger::bootFinished()
341{
Wei Wangb254fa32017-01-31 17:43:23 -0800342 if (mStartBootAnimThread->join() != NO_ERROR) {
343 ALOGE("Join StartBootAnimThread failed!");
344 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 const nsecs_t now = systemTime();
346 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000347 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700348 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700349
350 // wait patiently for the window manager death
351 const String16 name("window");
352 sp<IBinder> window(defaultServiceManager()->getService(name));
353 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700354 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700355 }
356
Steven Thomas050b2c82017-03-06 11:45:16 -0800357 if (mVrFlinger) {
358 mVrFlinger->OnBootFinished();
359 }
360
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700361 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 // formerly we would just kill the process, but we now ask it to exit so it
363 // can choose where to stop the animation.
364 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700365
366 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
367 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
368 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian3f844832013-08-07 21:24:32 -0700371void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700372 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700373 RenderEngine& engine;
374 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700375 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700376 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
377 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 }
379 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700380 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 return true;
382 }
383 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700384 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385}
386
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700387class DispSyncSource : public VSyncSource, private DispSync::Callback {
388public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700389 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000390 const char* name) :
391 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700392 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700393 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000394 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
395 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700396 mDispSync(dispSync),
397 mCallbackMutex(),
398 mCallback(),
399 mVsyncMutex(),
400 mPhaseOffset(phaseOffset),
401 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700402
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700403 virtual ~DispSyncSource() {}
404
405 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700406 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700407 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 static_cast<DispSync::Callback*>(this));
410 if (err != NO_ERROR) {
411 ALOGE("error registering vsync callback: %s (%d)",
412 strerror(-err), err);
413 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700414 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 } else {
416 status_t err = mDispSync->removeEventListener(
417 static_cast<DispSync::Callback*>(this));
418 if (err != NO_ERROR) {
419 ALOGE("error unregistering vsync callback: %s (%d)",
420 strerror(-err), err);
421 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700422 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700424 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425 }
426
427 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700428 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 mCallback = callback;
430 }
431
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700432 virtual void setPhaseOffset(nsecs_t phaseOffset) {
433 Mutex::Autolock lock(mVsyncMutex);
434
435 // Normalize phaseOffset to [0, period)
436 auto period = mDispSync->getPeriod();
437 phaseOffset %= period;
438 if (phaseOffset < 0) {
439 // If we're here, then phaseOffset is in (-period, 0). After this
440 // operation, it will be in (0, period)
441 phaseOffset += period;
442 }
443 mPhaseOffset = phaseOffset;
444
445 // If we're not enabled, we don't need to mess with the listeners
446 if (!mEnabled) {
447 return;
448 }
449
450 // Remove the listener with the old offset
451 status_t err = mDispSync->removeEventListener(
452 static_cast<DispSync::Callback*>(this));
453 if (err != NO_ERROR) {
454 ALOGE("error unregistering vsync callback: %s (%d)",
455 strerror(-err), err);
456 }
457
458 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700460 static_cast<DispSync::Callback*>(this));
461 if (err != NO_ERROR) {
462 ALOGE("error registering vsync callback: %s (%d)",
463 strerror(-err), err);
464 }
465 }
466
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467private:
468 virtual void onDispSyncEvent(nsecs_t when) {
469 sp<VSyncSource::Callback> callback;
470 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 callback = mCallback;
473
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700474 if (mTraceVsync) {
475 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700476 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700477 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
479
480 if (callback != NULL) {
481 callback->onVSyncEvent(when);
482 }
483 }
484
Tim Murray4a4e4a22016-04-19 16:29:23 +0000485 const char* const mName;
486
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 int mValue;
488
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700489 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700490 const String8 mVsyncOnLabel;
491 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700492
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700494
495 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497
498 Mutex mVsyncMutex; // Protects the following
499 nsecs_t mPhaseOffset;
500 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501};
502
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700503class InjectVSyncSource : public VSyncSource {
504public:
505 InjectVSyncSource() {}
506
507 virtual ~InjectVSyncSource() {}
508
509 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
510 std::lock_guard<std::mutex> lock(mCallbackMutex);
511 mCallback = callback;
512 }
513
514 virtual void onInjectSyncEvent(nsecs_t when) {
515 std::lock_guard<std::mutex> lock(mCallbackMutex);
516 mCallback->onVSyncEvent(when);
517 }
518
519 virtual void setVSyncEnabled(bool) {}
520 virtual void setPhaseOffset(nsecs_t) {}
521
522private:
523 std::mutex mCallbackMutex; // Protects the following
524 sp<VSyncSource::Callback> mCallback;
525};
526
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700528 ALOGI( "SurfaceFlinger's main thread ready to run. "
529 "Initializing graphics H/W...");
530
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900531 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
532
Dan Stoza9e56aa02015-11-02 13:00:03 -0800533 { // Autolock scope
534 Mutex::Autolock _l(mStateLock);
535
536 // initialize EGL for the default display
537 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
538 eglInitialize(mEGLDisplay, NULL, NULL);
539
540 // start the EventThread
541 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
542 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700543 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800544 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
545 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700546 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 mEventQueue.setEventThread(mSFEventThread);
548
Tim Murrayacff43d2016-07-29 13:57:24 -0700549 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700550 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700551 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700552 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
553 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
554 }
555
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 // Get a RenderEngine for the given display / config (can't fail)
557 mRenderEngine = RenderEngine::create(mEGLDisplay,
558 HAL_PIXEL_FORMAT_RGBA_8888);
559 }
560
561 // Drop the state lock while we initialize the hardware composer. We drop
562 // the lock because on creation, it will call back into SurfaceFlinger to
563 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800564 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
565 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800566 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800567 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
569
Jesse Hall692c7232012-11-08 15:41:56 -0800570 Mutex::Autolock _l(mStateLock);
571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (useVrFlinger) {
573 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
574 mVrFlingerRequestsDisplay = requestDisplay;
575 signalTransaction();
576 };
577 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
578 vrFlingerRequestDisplayCallback);
579 if (!mVrFlinger) {
580 ALOGE("Failed to start vrflinger");
581 }
582 }
583
Mathias Agopian875d8e12013-06-07 15:35:48 -0700584 // retrieve the EGL context that was selected/created
585 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700586
Mathias Agopianda27af92012-09-13 18:17:13 -0700587 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
588 "couldn't create EGLContext");
589
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 // make the GLContext current so that we can create textures when creating
591 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700592 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
593
Jamie Gennisd1700752013-10-14 12:22:52 -0700594 mEventControlThread = new EventControlThread(this);
595 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
596
Mathias Agopian92a979a2012-08-02 18:32:23 -0700597 // initialize our drawing state
598 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700599
Andy McFadden13a082e2012-08-24 10:16:42 -0700600 // set initial conditions (e.g. unblank default device)
601 initializeDisplays();
602
Dan Stoza4e637772016-07-28 13:31:51 -0700603 mRenderEngine->primeCache();
604
Wei Wangb254fa32017-01-31 17:43:23 -0800605 mStartBootAnimThread = new StartBootAnimThread();
606 if (mStartBootAnimThread->Start() != NO_ERROR) {
607 ALOGE("Run StartBootAnimThread failed!");
608 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800609
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700611}
612
Mathias Agopiana67e4182012-06-19 17:26:12 -0700613void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800614 // Start boot animation service by setting a property mailbox
615 // if property setting thread is already running, Start() will be just a NOP
616 mStartBootAnimThread->Start();
617 // Wait until property was set
618 if (mStartBootAnimThread->join() != NO_ERROR) {
619 ALOGE("Join StartBootAnimThread failed!");
620 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700621}
622
Mathias Agopian875d8e12013-06-07 15:35:48 -0700623size_t SurfaceFlinger::getMaxTextureSize() const {
624 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700625}
626
Mathias Agopian875d8e12013-06-07 15:35:48 -0700627size_t SurfaceFlinger::getMaxViewportDims() const {
628 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700629}
630
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800631// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800632
Jamie Gennis582270d2011-08-17 18:19:00 -0700633bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800634 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800635 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800636 return authenticateSurfaceTextureLocked(bufferProducer);
637}
638
639bool SurfaceFlinger::authenticateSurfaceTextureLocked(
640 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800641 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700642 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800643}
644
Dan Stoza7f7da322014-05-02 15:26:25 -0700645status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
646 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700647 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700648 return BAD_VALUE;
649 }
650
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500651 if (!display.get())
652 return NAME_NOT_FOUND;
653
Jesse Hall692c7232012-11-08 15:41:56 -0800654 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700655 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800656 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700657 type = i;
658 break;
659 }
660 }
661
662 if (type < 0) {
663 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700664 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700665
Mathias Agopian8b736f12012-08-13 17:54:26 -0700666 // TODO: Not sure if display density should handled by SF any longer
667 class Density {
668 static int getDensityFromProperty(char const* propName) {
669 char property[PROPERTY_VALUE_MAX];
670 int density = 0;
671 if (property_get(propName, property, NULL) > 0) {
672 density = atoi(property);
673 }
674 return density;
675 }
676 public:
677 static int getEmuDensity() {
678 return getDensityFromProperty("qemu.sf.lcd_density"); }
679 static int getBuildDensity() {
680 return getDensityFromProperty("ro.sf.lcd_density"); }
681 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700682
Dan Stoza7f7da322014-05-02 15:26:25 -0700683 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700684
Dan Stoza9e56aa02015-11-02 13:00:03 -0800685 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700686 DisplayInfo info = DisplayInfo();
687
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688 float xdpi = hwConfig->getDpiX();
689 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700690
691 if (type == DisplayDevice::DISPLAY_PRIMARY) {
692 // The density of the device is provided by a build property
693 float density = Density::getBuildDensity() / 160.0f;
694 if (density == 0) {
695 // the build doesn't provide a density -- this is wrong!
696 // use xdpi instead
697 ALOGE("ro.sf.lcd_density must be defined as a build property");
698 density = xdpi / 160.0f;
699 }
700 if (Density::getEmuDensity()) {
701 // if "qemu.sf.lcd_density" is specified, it overrides everything
702 xdpi = ydpi = density = Density::getEmuDensity();
703 density /= 160.0f;
704 }
705 info.density = density;
706
707 // TODO: this needs to go away (currently needed only by webkit)
708 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
709 info.orientation = hw->getOrientation();
710 } else {
711 // TODO: where should this value come from?
712 static const int TV_DENSITY = 213;
713 info.density = TV_DENSITY / 160.0f;
714 info.orientation = 0;
715 }
716
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717 info.w = hwConfig->getWidth();
718 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 info.xdpi = xdpi;
720 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900722 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723
Andy McFadden91b2ca82014-06-13 14:04:23 -0700724 // This is how far in advance a buffer must be queued for
725 // presentation at a given time. If you want a buffer to appear
726 // on the screen at time N, you must submit the buffer before
727 // (N - presentationDeadline).
728 //
729 // Normally it's one full refresh period (to give SF a chance to
730 // latch the buffer), but this can be reduced by configuring a
731 // DispSync offset. Any additional delays introduced by the hardware
732 // composer or panel must be accounted for here.
733 //
734 // We add an additional 1ms to allow for processing time and
735 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800736 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800737 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700738
739 // All non-virtual displays are currently considered secure.
740 info.secure = true;
741
Michael Wright28f24d02016-07-12 13:30:53 -0700742 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700743 }
744
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 return NO_ERROR;
746}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700747
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800748status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700749 DisplayStatInfo* stats) {
750 if (stats == NULL) {
751 return BAD_VALUE;
752 }
753
754 // FIXME for now we always return stats for the primary display
755 memset(stats, 0, sizeof(*stats));
756 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
757 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
758 return NO_ERROR;
759}
760
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700761int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800762 if (display == NULL) {
763 ALOGE("%s : display is NULL", __func__);
764 return BAD_VALUE;
765 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700766 sp<DisplayDevice> device(getDisplayDevice(display));
767 if (device != NULL) {
768 return device->getActiveConfig();
769 }
770 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700771}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700772
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700773void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
774 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
775 this);
776 int32_t type = hw->getDisplayType();
777 int currentMode = hw->getActiveConfig();
778
779 if (mode == currentMode) {
780 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
781 return;
782 }
783
784 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
785 ALOGW("Trying to set config for virtual display");
786 return;
787 }
788
789 hw->setActiveConfig(mode);
790 getHwComposer().setActiveConfig(type, mode);
791}
792
793status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
794 class MessageSetActiveConfig: public MessageBase {
795 SurfaceFlinger& mFlinger;
796 sp<IBinder> mDisplay;
797 int mMode;
798 public:
799 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
800 int mode) :
801 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
802 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700803 Vector<DisplayInfo> configs;
804 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700805 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700806 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700807 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700808 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700809 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700810 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
811 if (hw == NULL) {
812 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700813 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700814 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
815 ALOGW("Attempt to set active config = %d for virtual display",
816 mMode);
817 } else {
818 mFlinger.setActiveConfigInternal(hw, mMode);
819 }
820 return true;
821 }
822 };
823 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
824 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700825 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826}
Michael Wright28f24d02016-07-12 13:30:53 -0700827status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
828 Vector<android_color_mode_t>* outColorModes) {
829 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
830 return BAD_VALUE;
831 }
832
833 if (!display.get()) {
834 return NAME_NOT_FOUND;
835 }
836
837 int32_t type = NAME_NOT_FOUND;
838 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
839 if (display == mBuiltinDisplays[i]) {
840 type = i;
841 break;
842 }
843 }
844
845 if (type < 0) {
846 return type;
847 }
848
849 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
850 outColorModes->clear();
851 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
852
853 return NO_ERROR;
854}
855
856android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
857 sp<DisplayDevice> device(getDisplayDevice(display));
858 if (device != nullptr) {
859 return device->getActiveColorMode();
860 }
861 return static_cast<android_color_mode_t>(BAD_VALUE);
862}
863
864void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
865 android_color_mode_t mode) {
866 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
867 this);
868 int32_t type = hw->getDisplayType();
869 android_color_mode_t currentMode = hw->getActiveColorMode();
870
871 if (mode == currentMode) {
872 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
873 return;
874 }
875
876 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
877 ALOGW("Trying to set config for virtual display");
878 return;
879 }
880
881 hw->setActiveColorMode(mode);
882 getHwComposer().setActiveColorMode(type, mode);
883}
884
885
886status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
887 android_color_mode_t colorMode) {
888 class MessageSetActiveColorMode: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 android_color_mode_t mMode;
892 public:
893 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 android_color_mode_t mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
897 Vector<android_color_mode_t> modes;
898 mFlinger.getDisplayColorModes(mDisplay, &modes);
899 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
900 if (mMode < 0 || !exists) {
901 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
902 mDisplay.get());
903 return true;
904 }
905 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
906 if (hw == nullptr) {
907 ALOGE("Attempt to set active color mode = %d for null display %p",
908 mMode, mDisplay.get());
909 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
910 ALOGW("Attempt to set active color mode= %d for virtual display",
911 mMode);
912 } else {
913 mFlinger.setActiveColorModeInternal(hw, mMode);
914 }
915 return true;
916 }
917 };
918 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
919 postMessageSync(msg);
920 return NO_ERROR;
921}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700922
Svetoslavd85084b2014-03-20 10:28:31 -0700923status_t SurfaceFlinger::clearAnimationFrameStats() {
924 Mutex::Autolock _l(mStateLock);
925 mAnimFrameTracker.clearStats();
926 return NO_ERROR;
927}
928
929status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
930 Mutex::Autolock _l(mStateLock);
931 mAnimFrameTracker.getStats(outStats);
932 return NO_ERROR;
933}
934
Dan Stozac4f471e2016-03-24 09:31:08 -0700935status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
936 HdrCapabilities* outCapabilities) const {
937 Mutex::Autolock _l(mStateLock);
938
939 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
940 if (displayDevice == nullptr) {
941 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
942 return BAD_VALUE;
943 }
944
945 std::unique_ptr<HdrCapabilities> capabilities =
946 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
947 if (capabilities) {
948 std::swap(*outCapabilities, *capabilities);
949 } else {
950 return BAD_VALUE;
951 }
952
953 return NO_ERROR;
954}
955
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700956status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
957 if (enable == mInjectVSyncs) {
958 return NO_ERROR;
959 }
960
961 if (enable) {
962 mInjectVSyncs = enable;
963 ALOGV("VSync Injections enabled");
964 if (mVSyncInjector.get() == nullptr) {
965 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700966 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700967 }
968 mEventQueue.setEventThread(mInjectorEventThread);
969 } else {
970 mInjectVSyncs = enable;
971 ALOGV("VSync Injections disabled");
972 mEventQueue.setEventThread(mSFEventThread);
973 mVSyncInjector.clear();
974 }
975 return NO_ERROR;
976}
977
978status_t SurfaceFlinger::injectVSync(nsecs_t when) {
979 if (!mInjectVSyncs) {
980 ALOGE("VSync Injections not enabled");
981 return BAD_VALUE;
982 }
983 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
984 ALOGV("Injecting VSync inside SurfaceFlinger");
985 mVSyncInjector->onInjectSyncEvent(when);
986 }
987 return NO_ERROR;
988}
989
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800990// ----------------------------------------------------------------------------
991
992sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800993 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700994}
995
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800997
998void SurfaceFlinger::waitForEvent() {
999 mEventQueue.waitMessage();
1000}
1001
1002void SurfaceFlinger::signalTransaction() {
1003 mEventQueue.invalidate();
1004}
1005
1006void SurfaceFlinger::signalLayerUpdate() {
1007 mEventQueue.invalidate();
1008}
1009
1010void SurfaceFlinger::signalRefresh() {
1011 mEventQueue.refresh();
1012}
1013
1014status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001015 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001016 return mEventQueue.postMessage(msg, reltime);
1017}
1018
1019status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001020 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001021 status_t res = mEventQueue.postMessage(msg, reltime);
1022 if (res == NO_ERROR) {
1023 msg->wait();
1024 }
1025 return res;
1026}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001028void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001029 do {
1030 waitForEvent();
1031 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032}
1033
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001034void SurfaceFlinger::enableHardwareVsync() {
1035 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001036 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001037 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001038 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1039 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001040 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001041 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001042}
1043
Jesse Hall948fe0c2013-10-14 12:56:09 -07001044void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001045 Mutex::Autolock _l(mHWVsyncLock);
1046
Jesse Hall948fe0c2013-10-14 12:56:09 -07001047 if (makeAvailable) {
1048 mHWVsyncAvailable = true;
1049 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001050 // Hardware vsync is not currently available, so abort the resync
1051 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052 return;
1053 }
1054
Dan Stoza9e56aa02015-11-02 13:00:03 -08001055 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1056 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057
1058 mPrimaryDispSync.reset();
1059 mPrimaryDispSync.setPeriod(period);
1060
1061 if (!mPrimaryHWVsyncEnabled) {
1062 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001063 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1064 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 mPrimaryHWVsyncEnabled = true;
1066 }
1067}
1068
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070 Mutex::Autolock _l(mHWVsyncLock);
1071 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001072 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1073 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 mPrimaryDispSync.endResync();
1075 mPrimaryHWVsyncEnabled = false;
1076 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001077 if (makeUnavailable) {
1078 mHWVsyncAvailable = false;
1079 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080}
1081
Tim Murray4a4e4a22016-04-19 16:29:23 +00001082void SurfaceFlinger::resyncWithRateLimit() {
1083 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1084 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001085 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001086 }
1087}
1088
Steven Thomas3cfac282017-02-06 12:29:30 -08001089void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1090 nsecs_t timestamp) {
1091 Mutex::Autolock lock(mStateLock);
1092 // Ignore any vsyncs from the non-active hardware composer.
1093 if (composer != mHwc) {
1094 return;
1095 }
1096
Jamie Gennisd1700752013-10-14 12:22:52 -07001097 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098
Jamie Gennisd1700752013-10-14 12:22:52 -07001099 { // Scope for the lock
1100 Mutex::Autolock _l(mHWVsyncLock);
1101 if (type == 0 && mPrimaryHWVsyncEnabled) {
1102 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001103 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001104 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001105
1106 if (needsHwVsync) {
1107 enableHardwareVsync();
1108 } else {
1109 disableHardwareVsync(false);
1110 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001111}
1112
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001113void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001114 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001115 *compositorTiming = mCompositorTiming;
1116}
1117
Dan Stoza9e56aa02015-11-02 13:00:03 -08001118void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1119 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1120 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1121 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001122
Dan Stoza9e56aa02015-11-02 13:00:03 -08001123 // All non-virtual displays are currently considered secure.
1124 bool isSecure = true;
1125
1126 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001127
1128 // When we're using the vr composer, the assumption is that we've
1129 // already created the IBinder object for the primary display.
1130 if (!mHwc->isUsingVrComposer()) {
1131 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1132 }
1133
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134 wp<IBinder> token = mBuiltinDisplays[type];
1135
1136 sp<IGraphicBufferProducer> producer;
1137 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001138 BufferQueue::createBufferQueue(&producer, &consumer,
1139 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140
1141 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1142 DisplayDevice::DISPLAY_PRIMARY, consumer);
1143 sp<DisplayDevice> hw = new DisplayDevice(this,
1144 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1145 producer, mRenderEngine->getEGLConfig());
1146 mDisplays.add(token, hw);
1147 } else {
1148 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001149 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001150 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001151 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001152 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001153 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1154 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001155 }
1156 setTransactionFlags(eDisplayTransactionNeeded);
1157
Andy McFadden9e9689c2012-10-10 18:17:51 -07001158 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001159 }
Mathias Agopian86303202012-07-24 22:46:10 -07001160}
1161
Steven Thomas3cfac282017-02-06 12:29:30 -08001162void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1163 Mutex::Autolock lock(mStateLock);
1164 if (composer == mHwc) {
1165 repaintEverything();
1166 } else {
1167 // This isn't from our current hardware composer. If it's a callback
1168 // from the real composer, forward the refresh request to vr
1169 // flinger. Otherwise ignore it.
1170 if (!composer->isUsingVrComposer()) {
1171 mVrFlinger->OnHardwareComposerRefresh();
1172 }
1173 }
1174}
1175
Dan Stoza9e56aa02015-11-02 13:00:03 -08001176void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001178 getHwComposer().setVsyncEnabled(disp,
1179 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001180}
1181
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001182void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1183 for (size_t i = 0; i < layers.size(); ++i) {
1184 layers[i]->clearHwcLayers();
1185 }
1186}
1187
1188void SurfaceFlinger::resetHwc() {
1189 disableHardwareVsync(true);
1190 clearHwcLayers(mDrawingState.layersSortedByZ);
1191 clearHwcLayers(mCurrentState.layersSortedByZ);
1192 // Clear the drawing state so that the logic inside of
1193 // handleTransactionLocked will fire. It will determine the delta between
1194 // mCurrentState and mDrawingState and re-apply all changes when we make the
1195 // transition.
1196 mDrawingState.displays.clear();
1197 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001198 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001199}
1200
Steven Thomas050b2c82017-03-06 11:45:16 -08001201void SurfaceFlinger::updateVrFlinger() {
1202 if (!mVrFlinger)
1203 return;
1204 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1205 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001206 return;
1207 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001208 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001209 // Construct new HWComposer without holding any locks.
1210 mVrHwc = new HWComposer(true);
1211 ALOGV("Vr HWC created");
1212 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001213 {
1214 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001215
Steven Thomas050b2c82017-03-06 11:45:16 -08001216 if (vrFlingerRequestsDisplay) {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001217 resetHwc();
1218
1219 mHwc = mVrHwc;
Steven Thomas050b2c82017-03-06 11:45:16 -08001220 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001221 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -08001222 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001223
1224 resetHwc();
1225
1226 mHwc = mRealHwc;
1227 enableHardwareVsync();
1228 }
1229
1230 mVisibleRegionsDirty = true;
1231 invalidateHwcGeometry();
1232 android_atomic_or(1, &mRepaintEverything);
1233 setTransactionFlags(eDisplayTransactionNeeded);
1234 }
1235 if (mVrHwc) {
1236 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1237 }
1238}
1239
Mathias Agopian4fec8732012-06-29 14:12:52 -07001240void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001241 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001243 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001244 bool frameMissed = !mHadClientComposition &&
1245 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001246 (mPreviousPresentFence->getSignalTime() ==
1247 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001248 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001249 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001250 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001251 signalLayerUpdate();
1252 break;
1253 }
1254
Steven Thomas050b2c82017-03-06 11:45:16 -08001255 // Now that we're going to make it to the handleMessageTransaction()
1256 // call below it's safe to call updateVrFlinger(), which will
1257 // potentially trigger a display handoff.
1258 updateVrFlinger();
1259
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 bool refreshNeeded = handleMessageTransaction();
1261 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001262 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001263 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001264 // Signal a refresh if a transaction modified the window state,
1265 // a new buffer was latched, or if HWC has requested a full
1266 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001267 signalRefresh();
1268 }
1269 break;
1270 }
1271 case MessageQueue::REFRESH: {
1272 handleMessageRefresh();
1273 break;
1274 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001275 }
1276}
1277
Dan Stoza6b9454d2014-11-07 16:00:59 -08001278bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001279 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001280 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001281 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001283 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001284 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001285}
1286
Dan Stoza6b9454d2014-11-07 16:00:59 -08001287bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001288 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001290}
1291
1292void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001293 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001294
Pablo Ceballos40845df2016-01-25 17:41:15 -08001295 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001296
Brian Andersond6927fb2016-07-23 23:37:30 -07001297 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001298 rebuildLayerStacks();
1299 setUpHWComposer();
1300 doDebugFlashRegions();
1301 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001302 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001303
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001304 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001305
1306 mHadClientComposition = false;
1307 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1308 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1309 mHadClientComposition = mHadClientComposition ||
1310 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1311 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001312
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001314}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001315
Mathias Agopiancd60f992012-08-16 16:28:27 -07001316void SurfaceFlinger::doDebugFlashRegions()
1317{
1318 // is debugging enabled
1319 if (CC_LIKELY(!mDebugRegion))
1320 return;
1321
1322 const bool repaintEverything = mRepaintEverything;
1323 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1324 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001325 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001326 // transform the dirty region into this screen's coordinate space
1327 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1328 if (!dirtyRegion.isEmpty()) {
1329 // redraw the whole screen
1330 doComposeSurfaces(hw, Region(hw->bounds()));
1331
1332 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001334 RenderEngine& engine(getRenderEngine());
1335 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1336
Mathias Agopianda27af92012-09-13 18:17:13 -07001337 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338 }
1339 }
1340 }
1341
1342 postFramebuffer();
1343
1344 if (mDebugRegion > 1) {
1345 usleep(mDebugRegion * 1000);
1346 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001347
Dan Stoza9e56aa02015-11-02 13:00:03 -08001348 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001349 auto& displayDevice = mDisplays[displayId];
1350 if (!displayDevice->isDisplayOn()) {
1351 continue;
1352 }
1353
1354 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1356 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001357 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001358}
1359
Brian Andersond6927fb2016-07-23 23:37:30 -07001360void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001361{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001362 ATRACE_CALL();
1363 ALOGV("preComposition");
1364
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001366 mDrawingState.traverseInZOrder([&](Layer* layer) {
1367 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001368 needExtraInvalidate = true;
1369 }
Robert Carr2047fae2016-11-28 14:09:09 -08001370 });
1371
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 if (needExtraInvalidate) {
1373 signalLayerUpdate();
1374 }
1375}
1376
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001377void SurfaceFlinger::updateCompositorTiming(
1378 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1379 std::shared_ptr<FenceTime>& presentFenceTime) {
1380 // Update queue of past composite+present times and determine the
1381 // most recently known composite to present latency.
1382 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1383 nsecs_t compositeToPresentLatency = -1;
1384 while (!mCompositePresentTimes.empty()) {
1385 CompositePresentTime& cpt = mCompositePresentTimes.front();
1386 // Cached values should have been updated before calling this method,
1387 // which helps avoid duplicate syscalls.
1388 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1389 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1390 break;
1391 }
1392 compositeToPresentLatency = displayTime - cpt.composite;
1393 mCompositePresentTimes.pop();
1394 }
1395
1396 // Don't let mCompositePresentTimes grow unbounded, just in case.
1397 while (mCompositePresentTimes.size() > 16) {
1398 mCompositePresentTimes.pop();
1399 }
1400
Brian Andersond0010582017-03-07 13:20:31 -08001401 setCompositorTimingSnapped(
1402 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1403}
1404
1405void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1406 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407 // Integer division and modulo round toward 0 not -inf, so we need to
1408 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001409 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1411 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1412
Brian Andersond0010582017-03-07 13:20:31 -08001413 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1414 if (idealLatency <= 0) {
1415 idealLatency = vsyncInterval;
1416 }
1417
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001418 // Snap the latency to a value that removes scheduling jitter from the
1419 // composition and present times, which often have >1ms of jitter.
1420 // Reducing jitter is important if an app attempts to extrapolate
1421 // something (such as user input) to an accurate diasplay time.
1422 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1423 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001424 nsecs_t bias = vsyncInterval / 2;
1425 int64_t extraVsyncs =
1426 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1427 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1428 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429
Brian Andersond0010582017-03-07 13:20:31 -08001430 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001431 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1432 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001433 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001434}
1435
1436void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001438 ATRACE_CALL();
1439 ALOGV("postComposition");
1440
Brian Anderson3546a3f2016-07-14 11:51:14 -07001441 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001442 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001443 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001444 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001445 }
1446
Brian Andersond6927fb2016-07-23 23:37:30 -07001447 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001448
1449 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1450 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1451 glCompositionDoneFenceTime =
1452 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1453 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1454 } else {
1455 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1456 }
1457 mGlCompositionDoneTimeline.updateSignalTimes();
1458
Brian Anderson4e606e32017-03-16 15:34:57 -07001459 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1460 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1461 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001462 mDisplayTimeline.updateSignalTimes();
1463
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001464 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1465 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1466
1467 // We use the refreshStartTime which might be sampled a little later than
1468 // when we started doing work for this frame, but that should be okay
1469 // since updateCompositorTiming has snapping logic.
1470 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001471 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001472 CompositorTiming compositorTiming;
1473 {
1474 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1475 compositorTiming = mCompositorTiming;
1476 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001477
Robert Carr2047fae2016-11-28 14:09:09 -08001478 mDrawingState.traverseInZOrder([&](Layer* layer) {
1479 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001480 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001481 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001482 recordBufferingStats(layer->getName().string(),
1483 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001484 }
Robert Carr2047fae2016-11-28 14:09:09 -08001485 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001486
Brian Anderson4e606e32017-03-16 15:34:57 -07001487 if (presentFence->isValid()) {
1488 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001489 enableHardwareVsync();
1490 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001491 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001492 }
1493 }
1494
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001495 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001496 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001497 enableHardwareVsync();
1498 }
1499 }
1500
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001501 if (mAnimCompositionPending) {
1502 mAnimCompositionPending = false;
1503
Brian Anderson4e606e32017-03-16 15:34:57 -07001504 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001505 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001506 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001507 } else {
1508 // The HWC doesn't support present fences, so use the refresh
1509 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 nsecs_t presentTime =
1511 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001512 mAnimFrameTracker.setActualPresentTime(presentTime);
1513 }
1514 mAnimFrameTracker.advanceFrame();
1515 }
Dan Stozab90cf072015-03-05 11:05:59 -08001516
1517 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1518 return;
1519 }
1520
1521 nsecs_t currentTime = systemTime();
1522 if (mHasPoweredOff) {
1523 mHasPoweredOff = false;
1524 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001525 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001527 if (numPeriods < NUM_BUCKETS - 1) {
1528 mFrameBuckets[numPeriods] += elapsedTime;
1529 } else {
1530 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1531 }
1532 mTotalTime += elapsedTime;
1533 }
1534 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535}
1536
1537void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001538 ATRACE_CALL();
1539 ALOGV("rebuildLayerStacks");
1540
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001542 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1543 ATRACE_CALL();
1544 mVisibleRegionsDirty = false;
1545 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001546
Jeff Sharkey76488112017-02-27 14:15:18 -07001547 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1548 Region opaqueRegion;
1549 Region dirtyRegion;
1550 Vector<sp<Layer>> layersSortedByZ;
1551 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1552 const Transform& tr(displayDevice->getTransform());
1553 const Rect bounds(displayDevice->getBounds());
1554 if (displayDevice->isDisplayOn()) {
1555 computeVisibleRegions(
1556 displayDevice->getLayerStack(), dirtyRegion,
1557 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001558
Jeff Sharkey76488112017-02-27 14:15:18 -07001559 mDrawingState.traverseInZOrder([&](Layer* layer) {
1560 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1561 Region drawRegion(tr.transform(
1562 layer->visibleNonTransparentRegion));
1563 drawRegion.andSelf(bounds);
1564 if (!drawRegion.isEmpty()) {
1565 layersSortedByZ.add(layer);
1566 } else {
1567 // Clear out the HWC layer if this layer was
1568 // previously visible, but no longer is
1569 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1570 nullptr);
1571 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001572 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001573 // WM changes displayDevice->layerStack upon sleep/awake.
1574 // Here we make sure we delete the HWC layers even if
1575 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001576 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1577 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001578 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001579 });
1580 }
1581 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1582 displayDevice->undefinedRegion.set(bounds);
1583 displayDevice->undefinedRegion.subtractSelf(
1584 tr.transform(opaqueRegion));
1585 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001586 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001587 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001589
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001591 ATRACE_CALL();
1592 ALOGV("setUpHWComposer");
1593
Jesse Hall028dc8f2013-08-20 16:35:32 -07001594 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001595 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1596 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1597 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1598
1599 // If nothing has changed (!dirty), don't recompose.
1600 // If something changed, but we don't currently have any visible layers,
1601 // and didn't when we last did a composition, then skip it this time.
1602 // The second rule does two things:
1603 // - When all layers are removed from a display, we'll emit one black
1604 // frame, then nothing more until we get new layers.
1605 // - When a display is created with a private layer stack, we won't
1606 // emit any black frames until a layer is added to the layer stack.
1607 bool mustRecompose = dirty && !(empty && wasEmpty);
1608
1609 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1610 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1611 mustRecompose ? "doing" : "skipping",
1612 dirty ? "+" : "-",
1613 empty ? "+" : "-",
1614 wasEmpty ? "+" : "-");
1615
Dan Stoza71433162014-02-04 16:22:36 -08001616 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001617
1618 if (mustRecompose) {
1619 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1620 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001621 }
1622
Dan Stoza9e56aa02015-11-02 13:00:03 -08001623 // build the h/w work list
1624 if (CC_UNLIKELY(mGeometryInvalid)) {
1625 mGeometryInvalid = false;
1626 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1627 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1628 const auto hwcId = displayDevice->getHwcDisplayId();
1629 if (hwcId >= 0) {
1630 const Vector<sp<Layer>>& currentLayers(
1631 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001632 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001633 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 if (!layer->hasHwcLayer(hwcId)) {
1635 auto hwcLayer = mHwc->createLayer(hwcId);
1636 if (hwcLayer) {
1637 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1638 } else {
1639 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001641 }
1642 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001643
Robert Carrae060832016-11-28 10:51:00 -08001644 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001645 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001647 }
1648 }
1649 }
1650 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001651 }
Riley Andrews03414a12014-07-01 14:22:59 -07001652
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001653
1654 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1655
Dan Stoza9e56aa02015-11-02 13:00:03 -08001656 // Set the per-frame data
1657 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1658 auto& displayDevice = mDisplays[displayId];
1659 const auto hwcId = displayDevice->getHwcDisplayId();
1660 if (hwcId < 0) {
1661 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001662 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001663 if (colorMatrix != mPreviousColorMatrix) {
1664 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1665 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1666 "display %zd: %d", displayId, result);
1667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001668 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1669 layer->setPerFrameData(displayDevice);
1670 }
1671 }
1672
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001673 mPreviousColorMatrix = colorMatrix;
1674
Dan Stoza9e56aa02015-11-02 13:00:03 -08001675 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001676 auto& displayDevice = mDisplays[displayId];
1677 if (!displayDevice->isDisplayOn()) {
1678 continue;
1679 }
1680
1681 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1683 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001684 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001686
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687void SurfaceFlinger::doComposition() {
1688 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001689 ALOGV("doComposition");
1690
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001691 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001692 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001693 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001694 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695 // transform the dirty region into this screen's coordinate space
1696 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001697
1698 // repaint the framebuffer (if needed)
1699 doDisplayComposition(hw, dirtyRegion);
1700
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701 hw->dirtyRegion.clear();
1702 hw->flip(hw->swapRegion);
1703 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001704 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001705 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001706 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707}
1708
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709void SurfaceFlinger::postFramebuffer()
1710{
Mathias Agopian841cde52012-03-01 15:44:37 -08001711 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001713
Mathias Agopiana44b0412011-10-16 18:46:35 -07001714 const nsecs_t now = systemTime();
1715 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001716
Dan Stoza9e56aa02015-11-02 13:00:03 -08001717 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1718 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001719 if (!displayDevice->isDisplayOn()) {
1720 continue;
1721 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 const auto hwcId = displayDevice->getHwcDisplayId();
1723 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001724 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001725 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001726 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001727 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1729 sp<Fence> releaseFence = Fence::NO_FENCE;
1730 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1731 releaseFence = displayDevice->getClientTargetAcquireFence();
1732 } else {
1733 auto hwcLayer = layer->getHwcLayer(hwcId);
1734 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001735 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 layer->onLayerDisplayed(releaseFence);
1737 }
1738 if (hwcId >= 0) {
1739 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001740 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001741 }
1742
Mathias Agopiana44b0412011-10-16 18:46:35 -07001743 mLastSwapBufferTime = systemTime() - now;
1744 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001745
1746 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1747 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1748 logFrameStats();
1749 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001750}
1751
Mathias Agopian87baae12012-07-31 12:38:26 -07001752void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001753{
Mathias Agopian841cde52012-03-01 15:44:37 -08001754 ATRACE_CALL();
1755
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001756 // here we keep a copy of the drawing state (that is the state that's
1757 // going to be overwritten by handleTransactionLocked()) outside of
1758 // mStateLock so that the side-effects of the State assignment
1759 // don't happen with mStateLock held (which can cause deadlocks).
1760 State drawingState(mDrawingState);
1761
Mathias Agopianca4d3602011-05-19 15:38:14 -07001762 Mutex::Autolock _l(mStateLock);
1763 const nsecs_t now = systemTime();
1764 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765
Mathias Agopianca4d3602011-05-19 15:38:14 -07001766 // Here we're guaranteed that some transaction flags are set
1767 // so we can call handleTransactionLocked() unconditionally.
1768 // We call getTransactionFlags(), which will also clear the flags,
1769 // with mStateLock held to guarantee that mCurrentState won't change
1770 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001771
Mathias Agopiane57f2922012-08-09 16:29:12 -07001772 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001773 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001774
Mathias Agopianca4d3602011-05-19 15:38:14 -07001775 mLastTransactionTime = systemTime() - now;
1776 mDebugInTransaction = 0;
1777 invalidateHwcGeometry();
1778 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001779}
1780
Mathias Agopian87baae12012-07-31 12:38:26 -07001781void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001782{
Dan Stoza7dde5992015-05-22 09:51:44 -07001783 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001784 mCurrentState.traverseInZOrder([](Layer* layer) {
1785 layer->notifyAvailableFrames();
1786 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001787
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788 /*
1789 * Traversal of the children
1790 * (perform the transaction for each of them if needed)
1791 */
1792
Mathias Agopian3559b072012-08-15 13:46:03 -07001793 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001794 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001796 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797
1798 const uint32_t flags = layer->doTransaction(0);
1799 if (flags & Layer::eVisibleRegion)
1800 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001801 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802 }
1803
1804 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001805 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806 */
1807
Mathias Agopiane57f2922012-08-09 16:29:12 -07001808 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001809 // here we take advantage of Vector's copy-on-write semantics to
1810 // improve performance by skipping the transaction entirely when
1811 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001812 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1813 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001814 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001816 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001817 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001818
1819 // find the displays that were removed
1820 // (ie: in drawing state but not in current state)
1821 // also handle displays that changed
1822 // (ie: displays that are in both lists)
1823 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001824 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1825 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001826 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001827 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001828 // Call makeCurrent() on the primary display so we can
1829 // be sure that nothing associated with this display
1830 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001831 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001832 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001833 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1834 if (hw != NULL)
1835 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001836 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001837 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001838 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 } else {
1840 ALOGW("trying to remove the main display");
1841 }
1842 } else {
1843 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001844 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001845 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001846 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1847 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001848 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001849 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001850 // recreating the DisplayDevice, so we just remove it
1851 // from the drawing state, so that it get re-added
1852 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001853 sp<DisplayDevice> hw(getDisplayDevice(display));
1854 if (hw != NULL)
1855 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001856 mDisplays.removeItem(display);
1857 mDrawingState.displays.removeItemsAt(i);
1858 dc--; i--;
1859 // at this point we must loop to the next item
1860 continue;
1861 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001862
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001863 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001864 if (disp != NULL) {
1865 if (state.layerStack != draw[i].layerStack) {
1866 disp->setLayerStack(state.layerStack);
1867 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001868 if ((state.orientation != draw[i].orientation)
1869 || (state.viewport != draw[i].viewport)
1870 || (state.frame != draw[i].frame))
1871 {
1872 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001873 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001874 }
Michael Lentine47e45402014-07-18 15:34:25 -07001875 if (state.width != draw[i].width || state.height != draw[i].height) {
1876 disp->setDisplaySize(state.width, state.height);
1877 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001878 }
1879 }
1880 }
1881
1882 // find displays that were added
1883 // (ie: in current state but not in drawing state)
1884 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001885 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001886 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001887
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001888 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001889 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001890 sp<IGraphicBufferProducer> bqProducer;
1891 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001892 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1893 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001894
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001896 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001897 // Virtual displays without a surface are dormant:
1898 // they have external state (layer stack, projection,
1899 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001900 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001901
Dan Stoza8cf150a2016-08-02 10:27:31 -07001902 if (mUseHwcVirtualDisplays) {
1903 int width = 0;
1904 int status = state.surface->query(
1905 NATIVE_WINDOW_WIDTH, &width);
1906 ALOGE_IF(status != NO_ERROR,
1907 "Unable to query width (%d)", status);
1908 int height = 0;
1909 status = state.surface->query(
1910 NATIVE_WINDOW_HEIGHT, &height);
1911 ALOGE_IF(status != NO_ERROR,
1912 "Unable to query height (%d)", status);
1913 int intFormat = 0;
1914 status = state.surface->query(
1915 NATIVE_WINDOW_FORMAT, &intFormat);
1916 ALOGE_IF(status != NO_ERROR,
1917 "Unable to query format (%d)", status);
1918 auto format = static_cast<android_pixel_format_t>(
1919 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001920
Dan Stoza8cf150a2016-08-02 10:27:31 -07001921 mHwc->allocateVirtualDisplay(width, height, &format,
1922 &hwcId);
1923 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924
Dan Stoza5cf424b2016-05-20 14:02:39 -07001925 // TODO: Plumb requested format back up to consumer
1926
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 sp<VirtualDisplaySurface> vds =
1928 new VirtualDisplaySurface(*mHwc,
1929 hwcId, state.surface, bqProducer,
1930 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001931
1932 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001933 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001934 }
1935 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001936 ALOGE_IF(state.surface!=NULL,
1937 "adding a supported display, but rendering "
1938 "surface is provided (%p), ignoring it",
1939 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001940
1941 hwcId = state.type;
1942 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1943 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001944 }
1945
1946 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001947 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001948 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 state.type, hwcId, state.isSecure, display,
1950 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001951 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001952 hw->setLayerStack(state.layerStack);
1953 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001954 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001955 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001956 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001958 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001959 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001960 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001961 }
1962 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001965
Mathias Agopian84300952012-11-21 16:02:13 -08001966 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1967 // The transform hint might have changed for some layers
1968 // (either because a display has changed, or because a layer
1969 // as changed).
1970 //
1971 // Walk through all the layers in currentLayers,
1972 // and update their transform hint.
1973 //
1974 // If a layer is visible only on a single display, then that
1975 // display is used to calculate the hint, otherwise we use the
1976 // default display.
1977 //
1978 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1979 // the hint is set before we acquire a buffer from the surface texture.
1980 //
1981 // NOTE: layer transactions have taken place already, so we use their
1982 // drawing state. However, SurfaceFlinger's own transaction has not
1983 // happened yet, so we must use the current state layer list
1984 // (soon to become the drawing state list).
1985 //
1986 sp<const DisplayDevice> disp;
1987 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001988 bool first = true;
1989 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001990 // NOTE: we rely on the fact that layers are sorted by
1991 // layerStack first (so we don't have to traverse the list
1992 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001993 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001994 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001995 currentlayerStack = layerStack;
1996 // figure out if this layerstack is mirrored
1997 // (more than one display) if so, pick the default display,
1998 // if not, pick the only display it's on.
1999 disp.clear();
2000 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2001 sp<const DisplayDevice> hw(mDisplays[dpy]);
2002 if (hw->getLayerStack() == currentlayerStack) {
2003 if (disp == NULL) {
2004 disp = hw;
2005 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002006 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002007 break;
2008 }
2009 }
2010 }
2011 }
Chet Haase91d25932013-04-11 15:24:55 -07002012 if (disp == NULL) {
2013 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2014 // redraw after transform hint changes. See bug 8508397.
2015
2016 // could be null when this layer is using a layerStack
2017 // that is not visible on any display. Also can occur at
2018 // screen off/on times.
2019 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002020 }
Chet Haase91d25932013-04-11 15:24:55 -07002021 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002022
2023 first = false;
2024 });
Mathias Agopian84300952012-11-21 16:02:13 -08002025 }
2026
2027
Mathias Agopian3559b072012-08-15 13:46:03 -07002028 /*
2029 * Perform our own transaction if needed
2030 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002031
2032 if (mLayersAdded) {
2033 mLayersAdded = false;
2034 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002035 mVisibleRegionsDirty = true;
2036 }
2037
2038 // some layers might have been removed, so
2039 // we need to update the regions they're exposing.
2040 if (mLayersRemoved) {
2041 mLayersRemoved = false;
2042 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002043 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002044 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002045 // this layer is not visible anymore
2046 // TODO: we could traverse the tree from front to back and
2047 // compute the actual visible region
2048 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002049 Region visibleReg;
2050 visibleReg.set(layer->computeScreenBounds());
2051 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002052 }
Robert Carr2047fae2016-11-28 14:09:09 -08002053 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002054 }
2055
2056 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002057
2058 updateCursorAsync();
2059}
2060
2061void SurfaceFlinger::updateCursorAsync()
2062{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2064 auto& displayDevice = mDisplays[displayId];
2065 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002066 continue;
2067 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068
2069 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2070 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002071 }
2072 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002073}
2074
2075void SurfaceFlinger::commitTransaction()
2076{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002077 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002078 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002079 for (const auto& l : mLayersPendingRemoval) {
2080 recordBufferingStats(l->getName().string(),
2081 l->getOccupancyHistory(true));
2082 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002083 }
2084 mLayersPendingRemoval.clear();
2085 }
2086
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002087 // If this transaction is part of a window animation then the next frame
2088 // we composite should be considered an animation as well.
2089 mAnimCompositionPending = mAnimTransactionPending;
2090
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092 mDrawingState.traverseInZOrder([](Layer* layer) {
2093 layer->commitChildList();
2094 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002095 mTransactionPending = false;
2096 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098}
2099
Robert Carr2047fae2016-11-28 14:09:09 -08002100void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002101 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106 Region aboveOpaqueLayers;
2107 Region aboveCoveredLayers;
2108 Region dirty;
2109
Mathias Agopian87baae12012-07-31 12:38:26 -07002110 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111
Robert Carr2047fae2016-11-28 14:09:09 -08002112 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002114 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115
Jesse Hall01e29052013-02-19 16:13:35 -08002116 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002117 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002118 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002119
Mathias Agopianab028732010-03-16 16:41:46 -07002120 /*
2121 * opaqueRegion: area of a surface that is fully opaque.
2122 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002124
2125 /*
2126 * visibleRegion: area of a surface that is visible on screen
2127 * and not fully transparent. This is essentially the layer's
2128 * footprint minus the opaque regions above it.
2129 * Areas covered by a translucent surface are considered visible.
2130 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002132
2133 /*
2134 * coveredRegion: area of a surface that is covered by all
2135 * visible regions above it (which includes the translucent areas).
2136 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002138
Jesse Halla8026d22012-09-25 13:25:04 -07002139 /*
2140 * transparentRegion: area of a surface that is hinted to be completely
2141 * transparent. This is only used to tell when the layer has no visible
2142 * non-transparent regions and can be removed from the layer list. It
2143 * does not affect the visibleRegion of this layer or any layers
2144 * beneath it. The hint may not be correct if apps don't respect the
2145 * SurfaceView restrictions (which, sadly, some don't).
2146 */
2147 Region transparentRegion;
2148
Mathias Agopianab028732010-03-16 16:41:46 -07002149
2150 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002151 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002152 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002153 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002155 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002156 if (!visibleRegion.isEmpty()) {
2157 // Remove the transparent area from the visible region
2158 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002159 if (tr.preserveRects()) {
2160 // transform the transparent region
2161 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002162 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002163 // transformation too complex, can't do the
2164 // transparent region optimization.
2165 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002166 }
Mathias Agopianab028732010-03-16 16:41:46 -07002167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168
Mathias Agopianab028732010-03-16 16:41:46 -07002169 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002170 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002172 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2173 // the opaque region is the layer's footprint
2174 opaqueRegion = visibleRegion;
2175 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002176 }
2177 }
2178
Mathias Agopianab028732010-03-16 16:41:46 -07002179 // Clip the covered region to the visible region
2180 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2181
2182 // Update aboveCoveredLayers for next (lower) layer
2183 aboveCoveredLayers.orSelf(visibleRegion);
2184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002185 // subtract the opaque region covered by the layers above us
2186 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002187
2188 // compute this layer's dirty region
2189 if (layer->contentDirty) {
2190 // we need to invalidate the whole region
2191 dirty = visibleRegion;
2192 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002193 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194 layer->contentDirty = false;
2195 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002196 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002197 * the exposed region consists of two components:
2198 * 1) what's VISIBLE now and was COVERED before
2199 * 2) what's EXPOSED now less what was EXPOSED before
2200 *
2201 * note that (1) is conservative, we start with the whole
2202 * visible region but only keep what used to be covered by
2203 * something -- which mean it may have been exposed.
2204 *
2205 * (2) handles areas that were not covered by anything but got
2206 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002207 */
Mathias Agopianab028732010-03-16 16:41:46 -07002208 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002209 const Region oldVisibleRegion = layer->visibleRegion;
2210 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002211 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2212 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213 }
2214 dirty.subtractSelf(aboveOpaqueLayers);
2215
2216 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002217 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218
Mathias Agopianab028732010-03-16 16:41:46 -07002219 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002221
Jesse Halla8026d22012-09-25 13:25:04 -07002222 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223 layer->setVisibleRegion(visibleRegion);
2224 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002225 layer->setVisibleNonTransparentRegion(
2226 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002227 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228
Mathias Agopian87baae12012-07-31 12:38:26 -07002229 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230}
2231
Mathias Agopian87baae12012-07-31 12:38:26 -07002232void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2233 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002234 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002235 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2236 if (hw->getLayerStack() == layerStack) {
2237 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002238 }
2239 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002240}
2241
Dan Stoza6b9454d2014-11-07 16:00:59 -08002242bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 ALOGV("handlePageFlip");
2245
Brian Andersond6927fb2016-07-23 23:37:30 -07002246 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247
Mathias Agopian4fec8732012-06-29 14:12:52 -07002248 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002249 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002250
2251 // Store the set of layers that need updates. This set must not change as
2252 // buffers are being latched, as this could result in a deadlock.
2253 // Example: Two producers share the same command stream and:
2254 // 1.) Layer 0 is latched
2255 // 2.) Layer 0 gets a new frame
2256 // 2.) Layer 1 gets a new frame
2257 // 3.) Layer 1 is latched.
2258 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2259 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002260 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002261 if (layer->hasQueuedFrame()) {
2262 frameQueued = true;
2263 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002264 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002265 } else {
2266 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002268 } else {
2269 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002270 }
Robert Carr2047fae2016-11-28 14:09:09 -08002271 });
2272
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002274 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002275 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002276 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002277 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002278
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002279 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002280
2281 // If we will need to wake up at some time in the future to deal with a
2282 // queued frame that shouldn't be displayed during this vsync period, wake
2283 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002284 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 signalLayerUpdate();
2286 }
2287
2288 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290}
2291
Mathias Agopianad456f92011-01-13 17:53:01 -08002292void SurfaceFlinger::invalidateHwcGeometry()
2293{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002295}
2296
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002297
Fabien Sanglard830b8472016-11-30 16:35:58 -08002298void SurfaceFlinger::doDisplayComposition(
2299 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002300 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301{
Dan Stoza71433162014-02-04 16:22:36 -08002302 // We only need to actually compose the display if:
2303 // 1) It is being handled by hardware composer, which may need this to
2304 // keep its virtual display state machine in sync, or
2305 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002306 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002307 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002308 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002309 return;
2310 }
2311
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 ALOGV("doDisplayComposition");
2313
Mathias Agopian87baae12012-07-31 12:38:26 -07002314 Region dirtyRegion(inDirtyRegion);
2315
Mathias Agopianb8a55602009-06-26 19:06:36 -07002316 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002317 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318
Fabien Sanglard830b8472016-11-30 16:35:58 -08002319 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002320 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002321 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2322 // takes a rectangle, we must make sure to update that whole
2323 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002324 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002325 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002326 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002327 // We need to redraw the rectangle that will be updated
2328 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002329 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002330 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002332 } else {
2333 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002334 dirtyRegion.set(displayDevice->bounds());
2335 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 }
2337 }
2338
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002341 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002343
2344 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002345 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346}
2347
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348bool SurfaceFlinger::doComposeSurfaces(
2349 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002350{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002351 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002352
Dan Stoza9e56aa02015-11-02 13:00:03 -08002353 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002354
2355 mat4 oldColorMatrix;
2356 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2357 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2358 if (applyColorMatrix) {
2359 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2360 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2361 }
2362
Dan Stoza9e56aa02015-11-02 13:00:03 -08002363 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2364 if (hasClientComposition) {
2365 ALOGV("hasClientComposition");
2366
2367 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002368 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002370 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2371 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2372 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2373 }
2374 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002375 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002376
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002377 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2379 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002380 // when using overlays, we assume a fully transparent framebuffer
2381 // NOTE: we could reduce how much we need to clear, for instance
2382 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002383 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002384 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002385 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002386 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002387 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002389
2390 // we remove the scissor part
2391 // we're left with the letterbox region
2392 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002394
2395 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002397
2398 // but limit it to the dirty region
2399 region.andSelf(dirty);
2400
Mathias Agopianb9494d52012-04-18 02:28:45 -07002401 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002402 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002403 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002405 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002406 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002407
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002409 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002410 // scissor on the main display. It should never be needed
2411 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 const Rect& bounds(displayDevice->getBounds());
2413 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002414 if (scissor != bounds) {
2415 // scissor doesn't match the screen's dimensions, so we
2416 // need to clear everything outside of it and enable
2417 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002418
Mathias Agopianf45c5102012-10-24 16:29:17 -07002419 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 const uint32_t height = displayDevice->getHeight();
2421 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002422 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002423 }
2424 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002425 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002426
Mathias Agopian85d751c2012-08-29 16:59:24 -07002427 /*
2428 * and then, render the layers targeted at the framebuffer
2429 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002430
Dan Stoza9e56aa02015-11-02 13:00:03 -08002431 ALOGV("Rendering client layers");
2432 const Transform& displayTransform = displayDevice->getTransform();
2433 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002434 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 bool firstLayer = true;
2436 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2437 const Region clip(dirty.intersect(
2438 displayTransform.transform(layer->visibleRegion)));
2439 ALOGV("Layer: %s", layer->getName().string());
2440 ALOGV(" Composition type: %s",
2441 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002442 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 switch (layer->getCompositionType(hwcId)) {
2444 case HWC2::Composition::Cursor:
2445 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002446 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002448 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002449 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2450 layer->isOpaque(state) && (state.alpha == 1.0f)
2451 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002452 // never clear the very first layer since we're
2453 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002454 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002455 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002456 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002457 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 case HWC2::Composition::Client: {
2459 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002460 break;
2461 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002463 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002464 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 } else {
2466 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002469 }
2470 } else {
2471 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002473 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002477 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002478 }
2479 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002480
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002481 if (applyColorMatrix) {
2482 getRenderEngine().setupColorTransform(oldColorMatrix);
2483 }
2484
Mathias Agopianf45c5102012-10-24 16:29:17 -07002485 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002487 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488}
2489
Fabien Sanglard830b8472016-11-30 16:35:58 -08002490void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2491 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002492 RenderEngine& engine(getRenderEngine());
2493 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494}
2495
Dan Stoza7d89d062015-04-30 13:29:25 -07002496status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002497 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002498 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002499 const sp<Layer>& lbc,
2500 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002501{
Dan Stoza7d89d062015-04-30 13:29:25 -07002502 // add this layer to the current state list
2503 {
2504 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002505 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002506 return NO_MEMORY;
2507 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002508 if (parent == nullptr) {
2509 mCurrentState.layersSortedByZ.add(lbc);
2510 } else {
2511 parent->addChild(lbc);
2512 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002513 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 mLayersAdded = true;
2515 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002516 }
2517
Mathias Agopian96f08192010-06-02 23:28:45 -07002518 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002519 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002520
Dan Stoza7d89d062015-04-30 13:29:25 -07002521 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002522}
2523
Robert Carr9524cb32017-02-13 11:32:32 -08002524status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002525 Mutex::Autolock _l(mStateLock);
2526
Robert Carr1f0a16a2016-10-24 16:27:39 -07002527 const auto& p = layer->getParent();
2528 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2529 mCurrentState.layersSortedByZ.remove(layer);
2530
Robert Carr136e2f62017-02-08 17:54:29 -08002531 // As a matter of normal operation, the LayerCleaner will produce a second
2532 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2533 // so we will succeed in promoting it, but it's already been removed
2534 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2535 // otherwise something has gone wrong and we are leaking the layer.
2536 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2538 layer->getName().string(),
2539 (p != nullptr) ? p->getName().string() : "no-parent");
2540 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002541 } else if (index < 0) {
2542 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002543 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544
2545 mLayersPendingRemoval.add(layer);
2546 mLayersRemoved = true;
2547 mNumLayers--;
2548 setTransactionFlags(eTransactionNeeded);
2549 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550}
2551
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002552uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002553 return android_atomic_release_load(&mTransactionFlags);
2554}
2555
Mathias Agopian3f844832013-08-07 21:24:32 -07002556uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2558}
2559
Mathias Agopian3f844832013-08-07 21:24:32 -07002560uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2562 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002563 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 }
2565 return old;
2566}
2567
Mathias Agopian8b33f032012-07-24 20:43:54 -07002568void SurfaceFlinger::setTransactionState(
2569 const Vector<ComposerState>& state,
2570 const Vector<DisplayState>& displays,
2571 uint32_t flags)
2572{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002573 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002574 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002575 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002576
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002577 if (flags & eAnimation) {
2578 // For window updates that are part of an animation we must wait for
2579 // previous animation "frames" to be handled.
2580 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002581 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 if (CC_UNLIKELY(err != NO_ERROR)) {
2583 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002584 // caller after a few seconds.
2585 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2586 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002587 mAnimTransactionPending = false;
2588 break;
2589 }
2590 }
2591 }
2592
Mathias Agopiane57f2922012-08-09 16:29:12 -07002593 size_t count = displays.size();
2594 for (size_t i=0 ; i<count ; i++) {
2595 const DisplayState& s(displays[i]);
2596 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002597 }
2598
Mathias Agopiane57f2922012-08-09 16:29:12 -07002599 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002600 for (size_t i=0 ; i<count ; i++) {
2601 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002602 // Here we need to check that the interface we're given is indeed
2603 // one of our own. A malicious client could give us a NULL
2604 // IInterface, or one of its own or even one of our own but a
2605 // different type. All these situations would cause us to crash.
2606 //
2607 // NOTE: it would be better to use RTTI as we could directly check
2608 // that we have a Client*. however, RTTI is disabled in Android.
2609 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002610 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002611 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002612 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002613 sp<Client> client( static_cast<Client *>(s.client.get()) );
2614 transactionFlags |= setClientStateLocked(client, s.state);
2615 }
2616 }
2617 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002618 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002619
Robert Carr2a7dbb42016-05-24 11:41:28 -07002620 // If a synchronous transaction is explicitly requested without any changes,
2621 // force a transaction anyway. This can be used as a flush mechanism for
2622 // previous async transactions.
2623 if (transactionFlags == 0 && (flags & eSynchronous)) {
2624 transactionFlags = eTransactionNeeded;
2625 }
2626
Mathias Agopian386aa982011-11-07 21:58:03 -08002627 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002628 if (mInterceptor.isEnabled()) {
2629 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2630 }
Irvel468051e2016-06-13 16:44:44 -07002631
Mathias Agopian386aa982011-11-07 21:58:03 -08002632 // this triggers the transaction
2633 setTransactionFlags(transactionFlags);
2634
2635 // if this is a synchronous transaction, wait for it to take effect
2636 // before returning.
2637 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002638 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002639 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002640 if (flags & eAnimation) {
2641 mAnimTransactionPending = true;
2642 }
2643 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002644 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2645 if (CC_UNLIKELY(err != NO_ERROR)) {
2646 // just in case something goes wrong in SF, return to the
2647 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002648 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2649 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 break;
2651 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 }
2654}
2655
Mathias Agopiane57f2922012-08-09 16:29:12 -07002656uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2657{
Jesse Hall9a143922012-10-04 16:29:19 -07002658 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2659 if (dpyIdx < 0)
2660 return 0;
2661
Mathias Agopiane57f2922012-08-09 16:29:12 -07002662 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002663 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002664 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002665 const uint32_t what = s.what;
2666 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002667 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002668 disp.surface = s.surface;
2669 flags |= eDisplayTransactionNeeded;
2670 }
2671 }
2672 if (what & DisplayState::eLayerStackChanged) {
2673 if (disp.layerStack != s.layerStack) {
2674 disp.layerStack = s.layerStack;
2675 flags |= eDisplayTransactionNeeded;
2676 }
2677 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002678 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679 if (disp.orientation != s.orientation) {
2680 disp.orientation = s.orientation;
2681 flags |= eDisplayTransactionNeeded;
2682 }
2683 if (disp.frame != s.frame) {
2684 disp.frame = s.frame;
2685 flags |= eDisplayTransactionNeeded;
2686 }
2687 if (disp.viewport != s.viewport) {
2688 disp.viewport = s.viewport;
2689 flags |= eDisplayTransactionNeeded;
2690 }
2691 }
Michael Lentine47e45402014-07-18 15:34:25 -07002692 if (what & DisplayState::eDisplaySizeChanged) {
2693 if (disp.width != s.width) {
2694 disp.width = s.width;
2695 flags |= eDisplayTransactionNeeded;
2696 }
2697 if (disp.height != s.height) {
2698 disp.height = s.height;
2699 flags |= eDisplayTransactionNeeded;
2700 }
2701 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002702 }
2703 return flags;
2704}
2705
2706uint32_t SurfaceFlinger::setClientStateLocked(
2707 const sp<Client>& client,
2708 const layer_state_t& s)
2709{
2710 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002711 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002712 if (layer != 0) {
2713 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002714 bool geometryAppliesWithResize =
2715 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002716 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002717 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002718 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002719 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002720 }
2721 if (what & layer_state_t::eLayerChanged) {
2722 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 const auto& p = layer->getParent();
2724 if (p == nullptr) {
2725 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2726 if (layer->setLayer(s.z) && idx >= 0) {
2727 mCurrentState.layersSortedByZ.removeAt(idx);
2728 mCurrentState.layersSortedByZ.add(layer);
2729 // we need traversal (state changed)
2730 // AND transaction (list changed)
2731 flags |= eTransactionNeeded|eTraversalNeeded;
2732 }
2733 } else {
2734 if (p->setChildLayer(layer, s.z)) {
2735 flags |= eTransactionNeeded|eTraversalNeeded;
2736 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002737 }
2738 }
2739 if (what & layer_state_t::eSizeChanged) {
2740 if (layer->setSize(s.w, s.h)) {
2741 flags |= eTraversalNeeded;
2742 }
2743 }
2744 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002746 flags |= eTraversalNeeded;
2747 }
2748 if (what & layer_state_t::eMatrixChanged) {
2749 if (layer->setMatrix(s.matrix))
2750 flags |= eTraversalNeeded;
2751 }
2752 if (what & layer_state_t::eTransparentRegionChanged) {
2753 if (layer->setTransparentRegionHint(s.transparentRegion))
2754 flags |= eTraversalNeeded;
2755 }
Dan Stoza23116082015-06-18 14:58:39 -07002756 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 if (layer->setFlags(s.flags, s.mask))
2758 flags |= eTraversalNeeded;
2759 }
2760 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002761 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002762 flags |= eTraversalNeeded;
2763 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002764 if (what & layer_state_t::eFinalCropChanged) {
2765 if (layer->setFinalCrop(s.finalCrop))
2766 flags |= eTraversalNeeded;
2767 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002768 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002769 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 // We only allow setting layer stacks for top level layers,
2771 // everything else inherits layer stack from its parent.
2772 if (layer->hasParent()) {
2773 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2774 layer->getName().string());
2775 } else if (idx < 0) {
2776 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2777 "that also does not appear in the top level layer list. Something"
2778 " has gone wrong.", layer->getName().string());
2779 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 mCurrentState.layersSortedByZ.removeAt(idx);
2781 mCurrentState.layersSortedByZ.add(layer);
2782 // we need traversal (state changed)
2783 // AND transaction (list changed)
2784 flags |= eTransactionNeeded|eTraversalNeeded;
2785 }
2786 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002787 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002788 if (s.barrierHandle != nullptr) {
2789 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2790 } else if (s.barrierGbp != nullptr) {
2791 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2792 if (authenticateSurfaceTextureLocked(gbp)) {
2793 const auto& otherLayer =
2794 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2795 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2796 } else {
2797 ALOGE("Attempt to defer transaction to to an"
2798 " unrecognized GraphicBufferProducer");
2799 }
2800 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002801 // We don't trigger a traversal here because if no other state is
2802 // changed, we don't want this to cause any more work
2803 }
Robert Carr1db73f62016-12-21 12:58:51 -08002804 if (what & layer_state_t::eReparentChildren) {
2805 if (layer->reparentChildren(s.reparentHandle)) {
2806 flags |= eTransactionNeeded|eTraversalNeeded;
2807 }
2808 }
Robert Carr9524cb32017-02-13 11:32:32 -08002809 if (what & layer_state_t::eDetachChildren) {
2810 layer->detachChildren();
2811 }
Robert Carrc3574f72016-03-24 12:19:32 -07002812 if (what & layer_state_t::eOverrideScalingModeChanged) {
2813 layer->setOverrideScalingMode(s.overrideScalingMode);
2814 // We don't trigger a traversal here because if no other state is
2815 // changed, we don't want this to cause any more work
2816 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002817 }
2818 return flags;
2819}
2820
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002821status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002822 const String8& name,
2823 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002824 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002825 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2826 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002828 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002829 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002830 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002831 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002832 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002833
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002834 status_t result = NO_ERROR;
2835
2836 sp<Layer> layer;
2837
Mathias Agopian3165cc22012-08-08 19:42:09 -07002838 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2839 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002840 result = createNormalLayer(client,
2841 name, w, h, flags, format,
2842 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002844 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002845 result = createDimLayer(client,
2846 name, w, h, flags,
2847 handle, gbp, &layer);
2848 break;
2849 default:
2850 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 break;
2852 }
2853
Dan Stoza7d89d062015-04-30 13:29:25 -07002854 if (result != NO_ERROR) {
2855 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002857
Albert Chaulk479c60c2017-01-27 14:21:34 -05002858 layer->setInfo(windowType, ownerUid);
2859
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002861 if (result != NO_ERROR) {
2862 return result;
2863 }
Irvelffc9efc2016-07-27 15:16:37 -07002864 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002865
2866 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002867 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868}
2869
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002870status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2871 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2872 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873{
2874 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002875 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 case PIXEL_FORMAT_TRANSPARENT:
2877 case PIXEL_FORMAT_TRANSLUCENT:
2878 format = PIXEL_FORMAT_RGBA_8888;
2879 break;
2880 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002881 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 break;
2883 }
2884
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002885 *outLayer = new Layer(this, client, name, w, h, flags);
2886 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2887 if (err == NO_ERROR) {
2888 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002889 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002891
2892 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2893 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894}
2895
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002896status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2897 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2898 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002900 *outLayer = new LayerDim(this, client, name, w, h, flags);
2901 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002902 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002903 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002904}
2905
Mathias Agopianac9fa422013-02-11 16:40:36 -08002906status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907{
Robert Carr9524cb32017-02-13 11:32:32 -08002908 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002909 status_t err = NO_ERROR;
2910 sp<Layer> l(client->getLayerUser(handle));
2911 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002912 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002913 err = removeLayer(l);
2914 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2915 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002916 }
2917 return err;
2918}
2919
Mathias Agopian13127d82013-03-05 17:47:11 -08002920status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002921{
Mathias Agopian67106042013-03-14 19:18:13 -07002922 // called by ~LayerCleaner() when all references to the IBinder (handle)
2923 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002924 sp<Layer> l = layer.promote();
2925 if (l == nullptr) {
2926 // The layer has already been removed, carry on
2927 return NO_ERROR;
2928 } if (l->getParent() != nullptr) {
2929 // If we have a parent, then we can continue to live as long as it does.
2930 return NO_ERROR;
2931 }
2932 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933}
2934
Mathias Agopianb60314a2012-04-10 22:09:54 -07002935// ---------------------------------------------------------------------------
2936
Andy McFadden13a082e2012-08-24 10:16:42 -07002937void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002938 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002939 Vector<ComposerState> state;
2940 Vector<DisplayState> displays;
2941 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002942 d.what = DisplayState::eDisplayProjectionChanged |
2943 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002944 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002945 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002946 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002947 d.frame.makeInvalid();
2948 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002949 d.width = 0;
2950 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002951 displays.add(d);
2952 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002953 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002954
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2956 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002957 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002958
Brian Andersond0010582017-03-07 13:20:31 -08002959 // Use phase of 0 since phase is not known.
2960 // Use latency of 0, which will snap to the ideal latency.
2961 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002962}
2963
2964void SurfaceFlinger::initializeDisplays() {
2965 class MessageScreenInitialized : public MessageBase {
2966 SurfaceFlinger* flinger;
2967 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002968 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002969 virtual bool handler() {
2970 flinger->onInitializeDisplays();
2971 return true;
2972 }
2973 };
2974 sp<MessageBase> msg = new MessageScreenInitialized(this);
2975 postMessageAsync(msg); // we may be called from main thread, use async message
2976}
2977
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002978void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2979 int mode) {
2980 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2981 this);
2982 int32_t type = hw->getDisplayType();
2983 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002984
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002985 if (mode == currentMode) {
2986 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002987 return;
2988 }
2989
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002990 hw->setPowerMode(mode);
2991 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2992 ALOGW("Trying to set power mode for virtual display");
2993 return;
2994 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002995
Irvelffc9efc2016-07-27 15:16:37 -07002996 if (mInterceptor.isEnabled()) {
2997 Mutex::Autolock _l(mStateLock);
2998 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2999 if (idx < 0) {
3000 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3001 return;
3002 }
3003 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3004 }
3005
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003007 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003008 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003009 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3010 // FIXME: eventthread only knows about the main display right now
3011 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003012 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003013 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003016 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003017 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003018
3019 struct sched_param param = {0};
3020 param.sched_priority = 1;
3021 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3022 ALOGW("Couldn't set SCHED_FIFO on display on");
3023 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003024 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003025 // Turn off the display
3026 struct sched_param param = {0};
3027 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3028 ALOGW("Couldn't set SCHED_OTHER on display off");
3029 }
3030
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003031 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003032 disableHardwareVsync(true); // also cancels any in-progress resync
3033
Mathias Agopiancde87a32012-09-13 14:09:01 -07003034 // FIXME: eventthread only knows about the main display right now
3035 mEventThread->onScreenReleased();
3036 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003037
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003038 getHwComposer().setPowerMode(type, mode);
3039 mVisibleRegionsDirty = true;
3040 // from this point on, SF will stop drawing on this display
3041 } else {
3042 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003043 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003044}
3045
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003046void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3047 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003048 SurfaceFlinger& mFlinger;
3049 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003050 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003051 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003052 MessageSetPowerMode(SurfaceFlinger& flinger,
3053 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3054 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003055 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003056 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003057 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003058 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003059 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003060 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003061 ALOGW("Attempt to set power mode = %d for virtual display",
3062 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003063 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003064 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003065 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003066 return true;
3067 }
3068 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003069 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003070 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003071}
3072
3073// ---------------------------------------------------------------------------
3074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3076{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003078
Mathias Agopianbd115332013-04-18 16:41:04 -07003079 IPCThreadState* ipc = IPCThreadState::self();
3080 const int pid = ipc->getCallingPid();
3081 const int uid = ipc->getCallingUid();
3082 if ((uid != AID_SHELL) &&
3083 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003084 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003085 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003087 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003088 // (this would indicate SF is stuck, but we want to be able to
3089 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003090 status_t err = mStateLock.timedLock(s2ns(1));
3091 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003092 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003093 result.appendFormat(
3094 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3095 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003096 }
3097
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003098 bool dumpAll = true;
3099 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003100 size_t numArgs = args.size();
3101 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003102 if ((index < numArgs) &&
3103 (args[index] == String16("--list"))) {
3104 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003105 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003106 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003107 }
3108
3109 if ((index < numArgs) &&
3110 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003111 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003112 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003113 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003114 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003115
3116 if ((index < numArgs) &&
3117 (args[index] == String16("--latency-clear"))) {
3118 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003119 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003120 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003121 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003122
3123 if ((index < numArgs) &&
3124 (args[index] == String16("--dispsync"))) {
3125 index++;
3126 mPrimaryDispSync.dump(result);
3127 dumpAll = false;
3128 }
Dan Stozab90cf072015-03-05 11:05:59 -08003129
3130 if ((index < numArgs) &&
3131 (args[index] == String16("--static-screen"))) {
3132 index++;
3133 dumpStaticScreenStats(result);
3134 dumpAll = false;
3135 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003136
3137 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003138 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003139 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003140 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003141 dumpAll = false;
3142 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003144
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003145 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003146 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003147 }
3148
Mathias Agopian9795c422009-08-26 16:36:26 -07003149 if (locked) {
3150 mStateLock.unlock();
3151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 write(fd, result.string(), result.size());
3154 return NO_ERROR;
3155}
3156
Dan Stozac7014012014-02-14 15:03:43 -08003157void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3158 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003159{
Robert Carr2047fae2016-11-28 14:09:09 -08003160 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003161 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003162 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003163}
3164
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003165void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003166 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003167{
3168 String8 name;
3169 if (index < args.size()) {
3170 name = String8(args[index]);
3171 index++;
3172 }
3173
Dan Stoza9e56aa02015-11-02 13:00:03 -08003174 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3175 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003176 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003177
3178 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003179 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003180 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003181 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003182 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003183 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003184 }
Robert Carr2047fae2016-11-28 14:09:09 -08003185 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003186 }
3187}
3188
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003189void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003190 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003191{
3192 String8 name;
3193 if (index < args.size()) {
3194 name = String8(args[index]);
3195 index++;
3196 }
3197
Robert Carr2047fae2016-11-28 14:09:09 -08003198 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003199 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003200 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003201 }
Robert Carr2047fae2016-11-28 14:09:09 -08003202 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003203
Svetoslavd85084b2014-03-20 10:28:31 -07003204 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003205}
3206
Jamie Gennis6547ff42013-07-16 20:12:42 -07003207// This should only be called from the main thread. Otherwise it would need
3208// the lock and should use mCurrentState rather than mDrawingState.
3209void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003211 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003212 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003213
3214 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3215}
3216
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003218{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003220 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3221
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003222 if (isLayerTripleBufferingDisabled())
3223 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003224
3225 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003226 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003227 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003228 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003229 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003230}
3231
Dan Stozab90cf072015-03-05 11:05:59 -08003232void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3233{
3234 result.appendFormat("Static screen stats:\n");
3235 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3236 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3237 float percent = 100.0f *
3238 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3239 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3240 b + 1, bucketTimeSec, percent);
3241 }
3242 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3243 float percent = 100.0f *
3244 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3245 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3246 NUM_BUCKETS - 1, bucketTimeSec, percent);
3247}
3248
Dan Stozae77c7662016-05-13 11:37:28 -07003249void SurfaceFlinger::recordBufferingStats(const char* layerName,
3250 std::vector<OccupancyTracker::Segment>&& history) {
3251 Mutex::Autolock lock(mBufferingStatsMutex);
3252 auto& stats = mBufferingStats[layerName];
3253 for (const auto& segment : history) {
3254 if (!segment.usedThirdBuffer) {
3255 stats.twoBufferTime += segment.totalTime;
3256 }
3257 if (segment.occupancyAverage < 1.0f) {
3258 stats.doubleBufferedTime += segment.totalTime;
3259 } else if (segment.occupancyAverage < 2.0f) {
3260 stats.tripleBufferedTime += segment.totalTime;
3261 }
3262 ++stats.numSegments;
3263 stats.totalTime += segment.totalTime;
3264 }
3265}
3266
Brian Andersond6927fb2016-07-23 23:37:30 -07003267void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3268 result.appendFormat("Layer frame timestamps:\n");
3269
3270 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3271 const size_t count = currentLayers.size();
3272 for (size_t i=0 ; i<count ; i++) {
3273 currentLayers[i]->dumpFrameEvents(result);
3274 }
3275}
3276
Dan Stozae77c7662016-05-13 11:37:28 -07003277void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3278 result.append("Buffering stats:\n");
3279 result.append(" [Layer name] <Active time> <Two buffer> "
3280 "<Double buffered> <Triple buffered>\n");
3281 Mutex::Autolock lock(mBufferingStatsMutex);
3282 typedef std::tuple<std::string, float, float, float> BufferTuple;
3283 std::map<float, BufferTuple, std::greater<float>> sorted;
3284 for (const auto& statsPair : mBufferingStats) {
3285 const char* name = statsPair.first.c_str();
3286 const BufferingStats& stats = statsPair.second;
3287 if (stats.numSegments == 0) {
3288 continue;
3289 }
3290 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3291 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3292 stats.totalTime;
3293 float doubleBufferRatio = static_cast<float>(
3294 stats.doubleBufferedTime) / stats.totalTime;
3295 float tripleBufferRatio = static_cast<float>(
3296 stats.tripleBufferedTime) / stats.totalTime;
3297 sorted.insert({activeTime, {name, twoBufferRatio,
3298 doubleBufferRatio, tripleBufferRatio}});
3299 }
3300 for (const auto& sortedPair : sorted) {
3301 float activeTime = sortedPair.first;
3302 const BufferTuple& values = sortedPair.second;
3303 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3304 std::get<0>(values).c_str(), activeTime,
3305 std::get<1>(values), std::get<2>(values),
3306 std::get<3>(values));
3307 }
3308 result.append("\n");
3309}
3310
3311
Mathias Agopian74d211a2013-04-22 16:55:35 +02003312void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3313 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003315 bool colorize = false;
3316 if (index < args.size()
3317 && (args[index] == String16("--color"))) {
3318 colorize = true;
3319 index++;
3320 }
3321
3322 Colorizer colorizer(colorize);
3323
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003324 // figure out if we're stuck somewhere
3325 const nsecs_t now = systemTime();
3326 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3327 const nsecs_t inTransaction(mDebugInTransaction);
3328 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3329 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3330
3331 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003332 * Dump library configuration.
3333 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003334
3335 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003336 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003337 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003338 appendSfConfigString(result);
3339 appendUiConfigString(result);
3340 appendGuiConfigString(result);
3341 result.append("\n");
3342
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003343 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003344 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003345 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003346 result.append(SyncFeatures::getInstance().toString());
3347 result.append("\n");
3348
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3350
Andy McFadden41d67d72014-04-25 16:58:34 -07003351 colorizer.bold(result);
3352 result.append("DispSync configuration: ");
3353 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003354 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003355 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003356 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003357 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003358 result.append("\n");
3359
Dan Stozab90cf072015-03-05 11:05:59 -08003360 // Dump static screen stats
3361 result.append("\n");
3362 dumpStaticScreenStats(result);
3363 result.append("\n");
3364
Dan Stozae77c7662016-05-13 11:37:28 -07003365 dumpBufferingStats(result);
3366
Andy McFadden4803b742012-09-24 19:07:20 -07003367 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003368 * Dump the visible layer list
3369 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003371 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003372 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003373 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003374 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003375 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003376
3377 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003378 * Dump Display state
3379 */
3380
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003382 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003384 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3385 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003386 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003387 }
3388
3389 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390 * Dump SurfaceFlinger global state
3391 */
3392
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003393 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003394 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003395 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003396
Mathias Agopian888c8222012-08-04 21:10:38 -07003397 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003398 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003399
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003400 colorizer.bold(result);
3401 result.appendFormat("EGL implementation : %s\n",
3402 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3403 colorizer.reset(result);
3404 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003405 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003406
Mathias Agopian875d8e12013-06-07 15:35:48 -07003407 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003408
Mathias Agopian42977342012-08-05 00:40:46 -07003409 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3411 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003412 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413 " last eglSwapBuffers() time: %f us\n"
3414 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003415 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003416 " refresh-rate : %f fps\n"
3417 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003418 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003419 " gpu_to_cpu_unsupported : %d\n"
3420 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421 mLastSwapBufferTime/1000.0,
3422 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003423 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003424 1e9 / activeConfig->getVsyncPeriod(),
3425 activeConfig->getDpiX(),
3426 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003427 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428
Mathias Agopian74d211a2013-04-22 16:55:35 +02003429 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003433 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003434
3435 /*
3436 * VSYNC state
3437 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003438 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003439 result.append("\n");
3440
3441 /*
3442 * HWC layer minidump
3443 */
3444 for (size_t d = 0; d < mDisplays.size(); d++) {
3445 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3446 int32_t hwcId = displayDevice->getHwcDisplayId();
3447 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3448 continue;
3449 }
3450
3451 result.appendFormat("Display %d HWC layers:\n", hwcId);
3452 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003453 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003454 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 });
Dan Stozae22aec72016-08-01 13:20:59 -07003456 result.append("\n");
3457 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458
3459 /*
3460 * Dump HWComposer state
3461 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003462 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003463 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003464 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003465 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003466 result.appendFormat(" h/w composer %s\n",
3467 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469
3470 /*
3471 * Dump gralloc state
3472 */
3473 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3474 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003475}
3476
Mathias Agopian13127d82013-03-05 17:47:11 -08003477const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003478SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003479 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003480 wp<IBinder> dpy;
3481 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3482 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3483 dpy = mDisplays.keyAt(i);
3484 break;
3485 }
3486 }
3487 if (dpy == NULL) {
3488 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3489 // Just use the primary display so we have something to return
3490 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3491 }
3492 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003493}
3494
Keun young Park63f165f2012-08-31 10:53:36 -07003495bool SurfaceFlinger::startDdmConnection()
3496{
3497 void* libddmconnection_dso =
3498 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3499 if (!libddmconnection_dso) {
3500 return false;
3501 }
3502 void (*DdmConnection_start)(const char* name);
3503 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003504 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003505 if (!DdmConnection_start) {
3506 dlclose(libddmconnection_dso);
3507 return false;
3508 }
3509 (*DdmConnection_start)(getServiceName());
3510 return true;
3511}
3512
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003513status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 switch (code) {
3515 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003516 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003518 case CLEAR_ANIMATION_FRAME_STATS:
3519 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003520 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003521 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 {
3523 // codes that require permission check
3524 IPCThreadState* ipc = IPCThreadState::self();
3525 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003526 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003527 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003528 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003529 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003530 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003532 break;
3533 }
Robert Carr1db73f62016-12-21 12:58:51 -08003534 /*
3535 * Calling setTransactionState is safe, because you need to have been
3536 * granted a reference to Client* and Handle* to do anything with it.
3537 *
3538 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3539 */
3540 case SET_TRANSACTION_STATE:
3541 case CREATE_SCOPED_CONNECTION:
3542 {
3543 return OK;
3544 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003545 case CAPTURE_SCREEN:
3546 {
3547 // codes that require permission check
3548 IPCThreadState* ipc = IPCThreadState::self();
3549 const int pid = ipc->getCallingPid();
3550 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003551 if ((uid != AID_GRAPHICS) &&
3552 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003553 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003554 return PERMISSION_DENIED;
3555 }
3556 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
3558 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003559 return OK;
3560}
3561
3562status_t SurfaceFlinger::onTransact(
3563 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3564{
3565 status_t credentialCheck = CheckTransactCodeCredentials(code);
3566 if (credentialCheck != OK) {
3567 return credentialCheck;
3568 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003569
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3571 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003572 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003573 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003574 IPCThreadState* ipc = IPCThreadState::self();
3575 const int pid = ipc->getCallingPid();
3576 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003577 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003578 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 return PERMISSION_DENIED;
3580 }
3581 int n;
3582 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003583 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003584 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 return NO_ERROR;
3586 case 1002: // SHOW_UPDATES
3587 n = data.readInt32();
3588 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003589 invalidateHwcGeometry();
3590 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003593 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003594 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003596 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003597 setTransactionFlags(
3598 eTransactionNeeded|
3599 eDisplayTransactionNeeded|
3600 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003601 return NO_ERROR;
3602 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003603 case 1006:{ // send empty update
3604 signalRefresh();
3605 return NO_ERROR;
3606 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003607 case 1008: // toggle use of hw composer
3608 n = data.readInt32();
3609 mDebugDisableHWC = n ? 1 : 0;
3610 invalidateHwcGeometry();
3611 repaintEverything();
3612 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003613 case 1009: // toggle use of transform hint
3614 n = data.readInt32();
3615 mDebugDisableTransformHint = n ? 1 : 0;
3616 invalidateHwcGeometry();
3617 repaintEverything();
3618 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003620 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621 reply->writeInt32(0);
3622 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003623 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003624 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625 return NO_ERROR;
3626 case 1013: {
3627 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003628 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3629 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003630 return NO_ERROR;
3631 }
3632 case 1014: {
3633 // daltonize
3634 n = data.readInt32();
3635 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003636 case 1:
3637 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3638 break;
3639 case 2:
3640 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3641 break;
3642 case 3:
3643 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3644 break;
3645 default:
3646 mDaltonizer.setType(ColorBlindnessType::None);
3647 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003648 }
3649 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003650 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003651 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003652 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003653 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003654 invalidateHwcGeometry();
3655 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003658 case 1015: {
3659 // apply a color matrix
3660 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003661 if (n) {
3662 // color matrix is sent as mat3 matrix followed by vec3
3663 // offset, then packed into a mat4 where the last row is
3664 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003665 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003666 for (size_t j = 0; j < 4; j++) {
3667 mColorMatrix[i][j] = data.readFloat();
3668 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003669 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003670 } else {
3671 mColorMatrix = mat4();
3672 }
3673 invalidateHwcGeometry();
3674 repaintEverything();
3675 return NO_ERROR;
3676 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003677 // This is an experimental interface
3678 // Needs to be shifted to proper binder interface when we productize
3679 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003680 n = data.readInt32();
3681 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003682 return NO_ERROR;
3683 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003684 case 1017: {
3685 n = data.readInt32();
3686 mForceFullDamage = static_cast<bool>(n);
3687 return NO_ERROR;
3688 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003689 case 1018: { // Modify Choreographer's phase offset
3690 n = data.readInt32();
3691 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3692 return NO_ERROR;
3693 }
3694 case 1019: { // Modify SurfaceFlinger's phase offset
3695 n = data.readInt32();
3696 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3697 return NO_ERROR;
3698 }
Irvel468051e2016-06-13 16:44:44 -07003699 case 1020: { // Layer updates interceptor
3700 n = data.readInt32();
3701 if (n) {
3702 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003703 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003704 }
3705 else{
3706 ALOGV("Interceptor disabled");
3707 mInterceptor.disable();
3708 }
3709 return NO_ERROR;
3710 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003711 case 1021: { // Disable HWC virtual displays
3712 n = data.readInt32();
3713 mUseHwcVirtualDisplays = !n;
3714 return NO_ERROR;
3715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 }
3717 }
3718 return err;
3719}
3720
Mathias Agopian53331da2011-08-22 21:44:41 -07003721void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003722 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003723 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003724}
3725
Mathias Agopian59119e62010-10-11 12:37:43 -07003726// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003727// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003728// ---------------------------------------------------------------------------
3729
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003730/* The code below is here to handle b/8734824
3731 *
3732 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003733 * from the surfaceflinger thread to the calling binder thread, where they
3734 * are executed. This allows the calling thread in the calling process to be
3735 * reused and not depend on having "enough" binder threads to handle the
3736 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003737 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003738class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003739 /* Parts of GraphicProducerWrapper are run on two different threads,
3740 * communicating by sending messages via Looper but also by shared member
3741 * data. Coherence maintenance is subtle and in places implicit (ugh).
3742 *
3743 * Don't rely on Looper's sendMessage/handleMessage providing
3744 * release/acquire semantics for any data not actually in the Message.
3745 * Data going from surfaceflinger to binder threads needs to be
3746 * synchronized explicitly.
3747 *
3748 * Barrier open/wait do provide release/acquire semantics. This provides
3749 * implicit synchronization for data coming back from binder to
3750 * surfaceflinger threads.
3751 */
3752
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753 sp<IGraphicBufferProducer> impl;
3754 sp<Looper> looper;
3755 status_t result;
3756 bool exitPending;
3757 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003758 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003759 uint32_t code;
3760 Parcel const* data;
3761 Parcel* reply;
3762
3763 enum {
3764 MSG_API_CALL,
3765 MSG_EXIT
3766 };
3767
3768 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003769 * Called on surfaceflinger thread. This is called by our "fake"
3770 * BpGraphicBufferProducer. We package the data and reply Parcel and
3771 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003772 */
3773 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003774 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003775 this->code = code;
3776 this->data = &data;
3777 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003778 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003779 // if we've exited, we run the message synchronously right here.
3780 // note (JH): as far as I can tell from looking at the code, this
3781 // never actually happens. if it does, i'm not sure if it happens
3782 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 handleMessage(Message(MSG_API_CALL));
3784 } else {
3785 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003786 // Prevent stores to this->{code, data, reply} from being
3787 // reordered later than the construction of Message.
3788 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003789 looper->sendMessage(this, Message(MSG_API_CALL));
3790 barrier.wait();
3791 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003792 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 }
3794
3795 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003796 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 * call the real BpGraphicBufferProducer.
3798 */
3799 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003800 int what = message.what;
3801 // Prevent reads below from happening before the read from Message
3802 atomic_thread_fence(memory_order_acquire);
3803 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003804 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003805 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003806 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003807 exitRequested = true;
3808 }
3809 }
3810
3811public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003812 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003813 : impl(impl),
3814 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003815 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003816 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003817 exitRequested(false),
3818 code(0),
3819 data(NULL),
3820 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003821 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822
Jesse Hallb154c422014-07-13 12:47:02 -07003823 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 status_t waitForResponse() {
3825 do {
3826 looper->pollOnce(-1);
3827 } while (!exitRequested);
3828 return result;
3829 }
3830
Jesse Hallb154c422014-07-13 12:47:02 -07003831 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003832 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003833 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003834 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003835 // Ensure this->result is visible to the binder thread before it
3836 // handles the message.
3837 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003838 looper->sendMessage(this, Message(MSG_EXIT));
3839 }
3840};
3841
3842
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003843status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3844 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003845 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003846 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003847 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003848
3849 if (CC_UNLIKELY(display == 0))
3850 return BAD_VALUE;
3851
3852 if (CC_UNLIKELY(producer == 0))
3853 return BAD_VALUE;
3854
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003855 // if we have secure windows on this display, never allow the screen capture
3856 // unless the producer interface is local (i.e.: we can take a screenshot for
3857 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003858 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003859
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003860 // Convert to surfaceflinger's internal rotation type.
3861 Transform::orientation_flags rotationFlags;
3862 switch (rotation) {
3863 case ISurfaceComposer::eRotateNone:
3864 rotationFlags = Transform::ROT_0;
3865 break;
3866 case ISurfaceComposer::eRotate90:
3867 rotationFlags = Transform::ROT_90;
3868 break;
3869 case ISurfaceComposer::eRotate180:
3870 rotationFlags = Transform::ROT_180;
3871 break;
3872 case ISurfaceComposer::eRotate270:
3873 rotationFlags = Transform::ROT_270;
3874 break;
3875 default:
3876 rotationFlags = Transform::ROT_0;
3877 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3878 break;
3879 }
3880
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003881 class MessageCaptureScreen : public MessageBase {
3882 SurfaceFlinger* flinger;
3883 sp<IBinder> display;
3884 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003885 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003886 uint32_t reqWidth, reqHeight;
3887 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003888 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003889 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003890 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003891 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003892 public:
3893 MessageCaptureScreen(SurfaceFlinger* flinger,
3894 const sp<IBinder>& display,
3895 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003896 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003897 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003898 bool useIdentityTransform,
3899 Transform::orientation_flags rotation,
3900 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003902 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003904 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003905 rotation(rotation), result(PERMISSION_DENIED),
3906 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 {
3908 }
3909 status_t getResult() const {
3910 return result;
3911 }
3912 virtual bool handler() {
3913 Mutex::Autolock _l(flinger->mStateLock);
3914 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003915 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003916 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003917 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003918 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003919 return true;
3920 }
3921 };
3922
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003923 // this creates a "fake" BBinder which will serve as a "fake" remote
3924 // binder to receive the marshaled calls and forward them to the
3925 // real remote (a BpGraphicBufferProducer)
3926 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3927
3928 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3929 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003931 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003932 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003933 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003934
3935 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003936 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003937 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003938 }
3939 return res;
3940}
3941
Mathias Agopian180f10d2013-04-10 22:55:41 -07003942
3943void SurfaceFlinger::renderScreenImplLocked(
3944 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003945 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003946 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003947 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003948{
3949 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003950 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003951
3952 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003953 const int32_t hw_w = hw->getWidth();
3954 const int32_t hw_h = hw->getHeight();
3955 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003956 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003957
Dan Stozac1879002014-05-22 15:59:05 -07003958 // if a default or invalid sourceCrop is passed in, set reasonable values
3959 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3960 !sourceCrop.isValid()) {
3961 sourceCrop.setLeftTop(Point(0, 0));
3962 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3963 }
3964
3965 // ensure that sourceCrop is inside screen
3966 if (sourceCrop.left < 0) {
3967 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3968 }
Dan Stozabe31f442014-06-11 11:20:54 -07003969 if (sourceCrop.right > hw_w) {
3970 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003971 }
3972 if (sourceCrop.top < 0) {
3973 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3974 }
Dan Stozabe31f442014-06-11 11:20:54 -07003975 if (sourceCrop.bottom > hw_h) {
3976 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003977 }
3978
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003980 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003981
3982 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003983 engine.setViewportAndProjection(
3984 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003985 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003986
3987 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003988 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003989
Robert Carr1f0a16a2016-10-24 16:27:39 -07003990 // We loop through the first level of layers without traversing,
3991 // as we need to interpret min/max layer Z in the top level Z space.
3992 for (const auto& layer : mDrawingState.layersSortedByZ) {
3993 if (layer->getLayerStack() != hw->getLayerStack()) {
3994 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003996 const Layer::State& state(layer->getDrawingState());
3997 if (state.z < minLayerZ || state.z > maxLayerZ) {
3998 continue;
3999 }
4000 layer->traverseInZOrder([&](Layer* layer) {
4001 if (!layer->isVisible()) {
4002 return;
4003 }
4004 if (filtering) layer->setFiltering(true);
4005 layer->draw(hw, useIdentityTransform);
4006 if (filtering) layer->setFiltering(false);
4007 });
4008 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004009
Mathias Agopian931bda12013-08-28 18:11:46 -07004010 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004011}
4012
4013
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004014status_t SurfaceFlinger::captureScreenImplLocked(
4015 const sp<const DisplayDevice>& hw,
4016 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004017 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004018 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004019 bool useIdentityTransform, Transform::orientation_flags rotation,
4020 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021{
4022 ATRACE_CALL();
4023
Mathias Agopian180f10d2013-04-10 22:55:41 -07004024 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004025 uint32_t hw_w = hw->getWidth();
4026 uint32_t hw_h = hw->getHeight();
4027
4028 if (rotation & Transform::ROT_90) {
4029 std::swap(hw_w, hw_h);
4030 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004031
Mathias Agopian180f10d2013-04-10 22:55:41 -07004032 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4033 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4034 reqWidth, reqHeight, hw_w, hw_h);
4035 return BAD_VALUE;
4036 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004037
Mathias Agopian180f10d2013-04-10 22:55:41 -07004038 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4039 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4040
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004041 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004042 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004043 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004044 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4045 (state.z < minLayerZ || state.z > maxLayerZ)) {
4046 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004047 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004048 layer->traverseInZOrder([&](Layer *layer) {
4049 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4050 layer->isSecure());
4051 });
4052 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004053
4054 if (!isLocalScreenshot && secureLayerIsVisible) {
4055 ALOGW("FB is protected: PERMISSION_DENIED");
4056 return PERMISSION_DENIED;
4057 }
4058
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004059 // create a surface (because we're a producer, and we need to
4060 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004061 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004062
4063 // Put the screenshot Surface into async mode so that
4064 // Layer::headFenceHasSignaled will always return true and we'll latch the
4065 // first buffer regardless of whether or not its acquire fence has
4066 // signaled. This is needed to avoid a race condition in the rotation
4067 // animation. See b/30209608
4068 sur->setAsyncMode(true);
4069
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004071
Michael Lentine5a16a622015-05-21 13:48:24 -07004072 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4073 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004074 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4075 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004076
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004077 int err = 0;
4078 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004079 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004080 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4081 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004082
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004083 if (err == NO_ERROR) {
4084 ANativeWindowBuffer* buffer;
4085 /* TODO: Once we have the sync framework everywhere this can use
4086 * server-side waits on the fence that dequeueBuffer returns.
4087 */
4088 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4089 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004090 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004091 // create an EGLImage from the buffer so we can later
4092 // turn it into a texture
4093 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4094 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4095 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004096 // this binds the given EGLImage as a framebuffer for the
4097 // duration of this scope.
4098 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4099 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004100 // this will in fact render into our dequeued buffer
4101 // via an FBO, which means we didn't have to create
4102 // an EGLSurface and therefore we're not
4103 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004104 renderScreenImplLocked(
4105 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4106 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004107
Riley Andrews86639902014-08-15 12:27:24 -07004108 // Attempt to create a sync khr object that can produce a sync point. If that
4109 // isn't available, create a non-dupable sync object in the fallback path and
4110 // wait on it directly.
4111 EGLSyncKHR sync;
4112 if (!DEBUG_SCREENSHOTS) {
4113 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004114 // native fence fd will not be populated until flush() is done.
4115 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004116 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004117 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004118 }
Riley Andrews86639902014-08-15 12:27:24 -07004119 if (sync != EGL_NO_SYNC_KHR) {
4120 // get the sync fd
4121 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4122 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4123 ALOGW("captureScreen: failed to dup sync khr object");
4124 syncFd = -1;
4125 }
4126 eglDestroySyncKHR(mEGLDisplay, sync);
4127 } else {
4128 // fallback path
4129 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4130 if (sync != EGL_NO_SYNC_KHR) {
4131 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4132 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4133 EGLint eglErr = eglGetError();
4134 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4135 ALOGW("captureScreen: fence wait timed out");
4136 } else {
4137 ALOGW_IF(eglErr != EGL_SUCCESS,
4138 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4139 }
4140 eglDestroySyncKHR(mEGLDisplay, sync);
4141 } else {
4142 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4143 }
4144 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004145 if (DEBUG_SCREENSHOTS) {
4146 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4147 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4148 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4149 hw, minLayerZ, maxLayerZ);
4150 delete [] pixels;
4151 }
4152
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004153 } else {
4154 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4155 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004156 window->cancelBuffer(window, buffer, syncFd);
4157 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004158 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004159 // destroy our image
4160 eglDestroyImageKHR(mEGLDisplay, image);
4161 } else {
4162 result = BAD_VALUE;
4163 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004164 if (buffer) {
4165 // queueBuffer takes ownership of syncFd
4166 result = window->queueBuffer(window, buffer, syncFd);
4167 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004168 }
4169 } else {
4170 result = BAD_VALUE;
4171 }
4172 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4173 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004174
Mathias Agopian74c40c02010-09-29 13:02:36 -07004175 return result;
4176}
4177
Mathias Agopiand5556842013-09-19 17:08:37 -07004178void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004179 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004180 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004181 for (size_t y=0 ; y<h ; y++) {
4182 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4183 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004184 if (p[x] != 0xFF000000) return;
4185 }
4186 }
4187 ALOGE("*** we just took a black screenshot ***\n"
4188 "requested minz=%d, maxz=%d, layerStack=%d",
4189 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004190
Robert Carr2047fae2016-11-28 14:09:09 -08004191 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004192 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004193 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004194 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4195 state.z <= maxLayerZ) {
4196 layer->traverseInZOrder([&](Layer* layer) {
4197 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4198 layer->isVisible() ? '+' : '-',
4199 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004200 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 i++;
4202 });
4203 }
4204 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004205 }
4206}
4207
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004208// ---------------------------------------------------------------------------
4209
Robert Carr2047fae2016-11-28 14:09:09 -08004210void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4211 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004212}
4213
Robert Carr2047fae2016-11-28 14:09:09 -08004214void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4215 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004216}
4217
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004219
4220
4221#if defined(__gl_h_)
4222#error "don't include gl/gl.h in this file"
4223#endif
4224
4225#if defined(__gl2_h_)
4226#error "don't include gl2/gl2.h in this file"
4227#endif