blob: 0aaab0c0315138e35c6cfc25d9e89ffc094ff1f4 [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
Brian Anderson069b3652016-07-22 10:32:47 -0700645status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700646 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700647 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700648 FrameEvent::REQUESTED_PRESENT,
649 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700650 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700651 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700652 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700653 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700654 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700655 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700656 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700657 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700658 };
659 return NO_ERROR;
660}
661
Dan Stoza7f7da322014-05-02 15:26:25 -0700662status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
663 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700664 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700665 return BAD_VALUE;
666 }
667
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500668 if (!display.get())
669 return NAME_NOT_FOUND;
670
Jesse Hall692c7232012-11-08 15:41:56 -0800671 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700672 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800673 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700674 type = i;
675 break;
676 }
677 }
678
679 if (type < 0) {
680 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700681 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700682
Mathias Agopian8b736f12012-08-13 17:54:26 -0700683 // TODO: Not sure if display density should handled by SF any longer
684 class Density {
685 static int getDensityFromProperty(char const* propName) {
686 char property[PROPERTY_VALUE_MAX];
687 int density = 0;
688 if (property_get(propName, property, NULL) > 0) {
689 density = atoi(property);
690 }
691 return density;
692 }
693 public:
694 static int getEmuDensity() {
695 return getDensityFromProperty("qemu.sf.lcd_density"); }
696 static int getBuildDensity() {
697 return getDensityFromProperty("ro.sf.lcd_density"); }
698 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700699
Dan Stoza7f7da322014-05-02 15:26:25 -0700700 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700701
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700703 DisplayInfo info = DisplayInfo();
704
Dan Stoza9e56aa02015-11-02 13:00:03 -0800705 float xdpi = hwConfig->getDpiX();
706 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700707
708 if (type == DisplayDevice::DISPLAY_PRIMARY) {
709 // The density of the device is provided by a build property
710 float density = Density::getBuildDensity() / 160.0f;
711 if (density == 0) {
712 // the build doesn't provide a density -- this is wrong!
713 // use xdpi instead
714 ALOGE("ro.sf.lcd_density must be defined as a build property");
715 density = xdpi / 160.0f;
716 }
717 if (Density::getEmuDensity()) {
718 // if "qemu.sf.lcd_density" is specified, it overrides everything
719 xdpi = ydpi = density = Density::getEmuDensity();
720 density /= 160.0f;
721 }
722 info.density = density;
723
724 // TODO: this needs to go away (currently needed only by webkit)
725 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
726 info.orientation = hw->getOrientation();
727 } else {
728 // TODO: where should this value come from?
729 static const int TV_DENSITY = 213;
730 info.density = TV_DENSITY / 160.0f;
731 info.orientation = 0;
732 }
733
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734 info.w = hwConfig->getWidth();
735 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700736 info.xdpi = xdpi;
737 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900739 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740
Andy McFadden91b2ca82014-06-13 14:04:23 -0700741 // This is how far in advance a buffer must be queued for
742 // presentation at a given time. If you want a buffer to appear
743 // on the screen at time N, you must submit the buffer before
744 // (N - presentationDeadline).
745 //
746 // Normally it's one full refresh period (to give SF a chance to
747 // latch the buffer), but this can be reduced by configuring a
748 // DispSync offset. Any additional delays introduced by the hardware
749 // composer or panel must be accounted for here.
750 //
751 // We add an additional 1ms to allow for processing time and
752 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800754 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700755
756 // All non-virtual displays are currently considered secure.
757 info.secure = true;
758
Michael Wright28f24d02016-07-12 13:30:53 -0700759 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 }
761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 return NO_ERROR;
763}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700764
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800765status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700766 DisplayStatInfo* stats) {
767 if (stats == NULL) {
768 return BAD_VALUE;
769 }
770
771 // FIXME for now we always return stats for the primary display
772 memset(stats, 0, sizeof(*stats));
773 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
774 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
775 return NO_ERROR;
776}
777
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700778int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800779 if (display == NULL) {
780 ALOGE("%s : display is NULL", __func__);
781 return BAD_VALUE;
782 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700783 sp<DisplayDevice> device(getDisplayDevice(display));
784 if (device != NULL) {
785 return device->getActiveConfig();
786 }
787 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700788}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700789
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700790void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
791 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
792 this);
793 int32_t type = hw->getDisplayType();
794 int currentMode = hw->getActiveConfig();
795
796 if (mode == currentMode) {
797 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
798 return;
799 }
800
801 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
802 ALOGW("Trying to set config for virtual display");
803 return;
804 }
805
806 hw->setActiveConfig(mode);
807 getHwComposer().setActiveConfig(type, mode);
808}
809
810status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
811 class MessageSetActiveConfig: public MessageBase {
812 SurfaceFlinger& mFlinger;
813 sp<IBinder> mDisplay;
814 int mMode;
815 public:
816 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
817 int mode) :
818 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
819 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700820 Vector<DisplayInfo> configs;
821 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700822 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700823 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700824 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700825 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700826 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700827 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
828 if (hw == NULL) {
829 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700830 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700831 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
832 ALOGW("Attempt to set active config = %d for virtual display",
833 mMode);
834 } else {
835 mFlinger.setActiveConfigInternal(hw, mMode);
836 }
837 return true;
838 }
839 };
840 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
841 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700842 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700843}
Michael Wright28f24d02016-07-12 13:30:53 -0700844status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
845 Vector<android_color_mode_t>* outColorModes) {
846 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
847 return BAD_VALUE;
848 }
849
850 if (!display.get()) {
851 return NAME_NOT_FOUND;
852 }
853
854 int32_t type = NAME_NOT_FOUND;
855 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
856 if (display == mBuiltinDisplays[i]) {
857 type = i;
858 break;
859 }
860 }
861
862 if (type < 0) {
863 return type;
864 }
865
866 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
867 outColorModes->clear();
868 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
869
870 return NO_ERROR;
871}
872
873android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
874 sp<DisplayDevice> device(getDisplayDevice(display));
875 if (device != nullptr) {
876 return device->getActiveColorMode();
877 }
878 return static_cast<android_color_mode_t>(BAD_VALUE);
879}
880
881void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
882 android_color_mode_t mode) {
883 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
884 this);
885 int32_t type = hw->getDisplayType();
886 android_color_mode_t currentMode = hw->getActiveColorMode();
887
888 if (mode == currentMode) {
889 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
890 return;
891 }
892
893 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
894 ALOGW("Trying to set config for virtual display");
895 return;
896 }
897
898 hw->setActiveColorMode(mode);
899 getHwComposer().setActiveColorMode(type, mode);
900}
901
902
903status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
904 android_color_mode_t colorMode) {
905 class MessageSetActiveColorMode: public MessageBase {
906 SurfaceFlinger& mFlinger;
907 sp<IBinder> mDisplay;
908 android_color_mode_t mMode;
909 public:
910 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
911 android_color_mode_t mode) :
912 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
913 virtual bool handler() {
914 Vector<android_color_mode_t> modes;
915 mFlinger.getDisplayColorModes(mDisplay, &modes);
916 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
917 if (mMode < 0 || !exists) {
918 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
919 mDisplay.get());
920 return true;
921 }
922 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
923 if (hw == nullptr) {
924 ALOGE("Attempt to set active color mode = %d for null display %p",
925 mMode, mDisplay.get());
926 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
927 ALOGW("Attempt to set active color mode= %d for virtual display",
928 mMode);
929 } else {
930 mFlinger.setActiveColorModeInternal(hw, mMode);
931 }
932 return true;
933 }
934 };
935 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
936 postMessageSync(msg);
937 return NO_ERROR;
938}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700939
Svetoslavd85084b2014-03-20 10:28:31 -0700940status_t SurfaceFlinger::clearAnimationFrameStats() {
941 Mutex::Autolock _l(mStateLock);
942 mAnimFrameTracker.clearStats();
943 return NO_ERROR;
944}
945
946status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
947 Mutex::Autolock _l(mStateLock);
948 mAnimFrameTracker.getStats(outStats);
949 return NO_ERROR;
950}
951
Dan Stozac4f471e2016-03-24 09:31:08 -0700952status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
953 HdrCapabilities* outCapabilities) const {
954 Mutex::Autolock _l(mStateLock);
955
956 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
957 if (displayDevice == nullptr) {
958 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
959 return BAD_VALUE;
960 }
961
962 std::unique_ptr<HdrCapabilities> capabilities =
963 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
964 if (capabilities) {
965 std::swap(*outCapabilities, *capabilities);
966 } else {
967 return BAD_VALUE;
968 }
969
970 return NO_ERROR;
971}
972
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700973status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
974 if (enable == mInjectVSyncs) {
975 return NO_ERROR;
976 }
977
978 if (enable) {
979 mInjectVSyncs = enable;
980 ALOGV("VSync Injections enabled");
981 if (mVSyncInjector.get() == nullptr) {
982 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700983 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700984 }
985 mEventQueue.setEventThread(mInjectorEventThread);
986 } else {
987 mInjectVSyncs = enable;
988 ALOGV("VSync Injections disabled");
989 mEventQueue.setEventThread(mSFEventThread);
990 mVSyncInjector.clear();
991 }
992 return NO_ERROR;
993}
994
995status_t SurfaceFlinger::injectVSync(nsecs_t when) {
996 if (!mInjectVSyncs) {
997 ALOGE("VSync Injections not enabled");
998 return BAD_VALUE;
999 }
1000 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1001 ALOGV("Injecting VSync inside SurfaceFlinger");
1002 mVSyncInjector->onInjectSyncEvent(when);
1003 }
1004 return NO_ERROR;
1005}
1006
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001007// ----------------------------------------------------------------------------
1008
1009sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001010 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001011}
1012
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001014
1015void SurfaceFlinger::waitForEvent() {
1016 mEventQueue.waitMessage();
1017}
1018
1019void SurfaceFlinger::signalTransaction() {
1020 mEventQueue.invalidate();
1021}
1022
1023void SurfaceFlinger::signalLayerUpdate() {
1024 mEventQueue.invalidate();
1025}
1026
1027void SurfaceFlinger::signalRefresh() {
1028 mEventQueue.refresh();
1029}
1030
1031status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001032 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001033 return mEventQueue.postMessage(msg, reltime);
1034}
1035
1036status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001037 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001038 status_t res = mEventQueue.postMessage(msg, reltime);
1039 if (res == NO_ERROR) {
1040 msg->wait();
1041 }
1042 return res;
1043}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001044
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001045void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001046 do {
1047 waitForEvent();
1048 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001049}
1050
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001051void SurfaceFlinger::enableHardwareVsync() {
1052 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001053 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001054 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1056 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001058 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059}
1060
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001062 Mutex::Autolock _l(mHWVsyncLock);
1063
Jesse Hall948fe0c2013-10-14 12:56:09 -07001064 if (makeAvailable) {
1065 mHWVsyncAvailable = true;
1066 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001067 // Hardware vsync is not currently available, so abort the resync
1068 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069 return;
1070 }
1071
Dan Stoza9e56aa02015-11-02 13:00:03 -08001072 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1073 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074
1075 mPrimaryDispSync.reset();
1076 mPrimaryDispSync.setPeriod(period);
1077
1078 if (!mPrimaryHWVsyncEnabled) {
1079 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001080 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1081 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 mPrimaryHWVsyncEnabled = true;
1083 }
1084}
1085
Jesse Hall948fe0c2013-10-14 12:56:09 -07001086void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087 Mutex::Autolock _l(mHWVsyncLock);
1088 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001089 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1090 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001091 mPrimaryDispSync.endResync();
1092 mPrimaryHWVsyncEnabled = false;
1093 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001094 if (makeUnavailable) {
1095 mHWVsyncAvailable = false;
1096 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001097}
1098
Tim Murray4a4e4a22016-04-19 16:29:23 +00001099void SurfaceFlinger::resyncWithRateLimit() {
1100 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1101 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001102 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001103 }
1104}
1105
Steven Thomas3cfac282017-02-06 12:29:30 -08001106void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1107 nsecs_t timestamp) {
1108 Mutex::Autolock lock(mStateLock);
1109 // Ignore any vsyncs from the non-active hardware composer.
1110 if (composer != mHwc) {
1111 return;
1112 }
1113
Jamie Gennisd1700752013-10-14 12:22:52 -07001114 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115
Jamie Gennisd1700752013-10-14 12:22:52 -07001116 { // Scope for the lock
1117 Mutex::Autolock _l(mHWVsyncLock);
1118 if (type == 0 && mPrimaryHWVsyncEnabled) {
1119 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001120 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001121 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001122
1123 if (needsHwVsync) {
1124 enableHardwareVsync();
1125 } else {
1126 disableHardwareVsync(false);
1127 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001128}
1129
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001130void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001131 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001132 *compositorTiming = mCompositorTiming;
1133}
1134
Dan Stoza9e56aa02015-11-02 13:00:03 -08001135void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1136 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1137 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1138 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001139
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140 // All non-virtual displays are currently considered secure.
1141 bool isSecure = true;
1142
1143 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001144
1145 // When we're using the vr composer, the assumption is that we've
1146 // already created the IBinder object for the primary display.
1147 if (!mHwc->isUsingVrComposer()) {
1148 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1149 }
1150
Dan Stoza9e56aa02015-11-02 13:00:03 -08001151 wp<IBinder> token = mBuiltinDisplays[type];
1152
1153 sp<IGraphicBufferProducer> producer;
1154 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001155 BufferQueue::createBufferQueue(&producer, &consumer,
1156 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001157
1158 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1159 DisplayDevice::DISPLAY_PRIMARY, consumer);
1160 sp<DisplayDevice> hw = new DisplayDevice(this,
1161 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1162 producer, mRenderEngine->getEGLConfig());
1163 mDisplays.add(token, hw);
1164 } else {
1165 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001166 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001167 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001168 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001169 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001170 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1171 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001172 }
1173 setTransactionFlags(eDisplayTransactionNeeded);
1174
Andy McFadden9e9689c2012-10-10 18:17:51 -07001175 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001176 }
Mathias Agopian86303202012-07-24 22:46:10 -07001177}
1178
Steven Thomas3cfac282017-02-06 12:29:30 -08001179void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1180 Mutex::Autolock lock(mStateLock);
1181 if (composer == mHwc) {
1182 repaintEverything();
1183 } else {
1184 // This isn't from our current hardware composer. If it's a callback
1185 // from the real composer, forward the refresh request to vr
1186 // flinger. Otherwise ignore it.
1187 if (!composer->isUsingVrComposer()) {
1188 mVrFlinger->OnHardwareComposerRefresh();
1189 }
1190 }
1191}
1192
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001195 getHwComposer().setVsyncEnabled(disp,
1196 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001197}
1198
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001199void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1200 for (size_t i = 0; i < layers.size(); ++i) {
1201 layers[i]->clearHwcLayers();
1202 }
1203}
1204
1205void SurfaceFlinger::resetHwc() {
1206 disableHardwareVsync(true);
1207 clearHwcLayers(mDrawingState.layersSortedByZ);
1208 clearHwcLayers(mCurrentState.layersSortedByZ);
1209 // Clear the drawing state so that the logic inside of
1210 // handleTransactionLocked will fire. It will determine the delta between
1211 // mCurrentState and mDrawingState and re-apply all changes when we make the
1212 // transition.
1213 mDrawingState.displays.clear();
1214 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001215 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001216}
1217
Steven Thomas050b2c82017-03-06 11:45:16 -08001218void SurfaceFlinger::updateVrFlinger() {
1219 if (!mVrFlinger)
1220 return;
1221 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1222 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001223 return;
1224 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001225 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001226 // Construct new HWComposer without holding any locks.
1227 mVrHwc = new HWComposer(true);
1228 ALOGV("Vr HWC created");
1229 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001230 {
1231 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001232
Steven Thomas050b2c82017-03-06 11:45:16 -08001233 if (vrFlingerRequestsDisplay) {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001234 resetHwc();
1235
1236 mHwc = mVrHwc;
Steven Thomas050b2c82017-03-06 11:45:16 -08001237 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001238 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -08001239 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001240
1241 resetHwc();
1242
1243 mHwc = mRealHwc;
1244 enableHardwareVsync();
1245 }
1246
1247 mVisibleRegionsDirty = true;
1248 invalidateHwcGeometry();
1249 android_atomic_or(1, &mRepaintEverything);
1250 setTransactionFlags(eDisplayTransactionNeeded);
1251 }
1252 if (mVrHwc) {
1253 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1254 }
1255}
1256
Mathias Agopian4fec8732012-06-29 14:12:52 -07001257void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001258 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001261 bool frameMissed = !mHadClientComposition &&
1262 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001263 (mPreviousPresentFence->getSignalTime() ==
1264 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001265 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001266 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001267 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001268 signalLayerUpdate();
1269 break;
1270 }
1271
Steven Thomas050b2c82017-03-06 11:45:16 -08001272 // Now that we're going to make it to the handleMessageTransaction()
1273 // call below it's safe to call updateVrFlinger(), which will
1274 // potentially trigger a display handoff.
1275 updateVrFlinger();
1276
Dan Stoza6b9454d2014-11-07 16:00:59 -08001277 bool refreshNeeded = handleMessageTransaction();
1278 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001279 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001280 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001281 // Signal a refresh if a transaction modified the window state,
1282 // a new buffer was latched, or if HWC has requested a full
1283 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001284 signalRefresh();
1285 }
1286 break;
1287 }
1288 case MessageQueue::REFRESH: {
1289 handleMessageRefresh();
1290 break;
1291 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001292 }
1293}
1294
Dan Stoza6b9454d2014-11-07 16:00:59 -08001295bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001296 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001297 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001298 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001300 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001301 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001302}
1303
Dan Stoza6b9454d2014-11-07 16:00:59 -08001304bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001305 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001306 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001307}
1308
1309void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001310 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001311
Pablo Ceballos40845df2016-01-25 17:41:15 -08001312 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001313
Brian Andersond6927fb2016-07-23 23:37:30 -07001314 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001315 rebuildLayerStacks();
1316 setUpHWComposer();
1317 doDebugFlashRegions();
1318 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001319 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001320
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001321 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001322
1323 mHadClientComposition = false;
1324 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1325 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1326 mHadClientComposition = mHadClientComposition ||
1327 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1328 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001329
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001331}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001332
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333void SurfaceFlinger::doDebugFlashRegions()
1334{
1335 // is debugging enabled
1336 if (CC_LIKELY(!mDebugRegion))
1337 return;
1338
1339 const bool repaintEverything = mRepaintEverything;
1340 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1341 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001342 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001343 // transform the dirty region into this screen's coordinate space
1344 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1345 if (!dirtyRegion.isEmpty()) {
1346 // redraw the whole screen
1347 doComposeSurfaces(hw, Region(hw->bounds()));
1348
1349 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001350 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001351 RenderEngine& engine(getRenderEngine());
1352 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1353
Mathias Agopianda27af92012-09-13 18:17:13 -07001354 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001355 }
1356 }
1357 }
1358
1359 postFramebuffer();
1360
1361 if (mDebugRegion > 1) {
1362 usleep(mDebugRegion * 1000);
1363 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001364
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001366 auto& displayDevice = mDisplays[displayId];
1367 if (!displayDevice->isDisplayOn()) {
1368 continue;
1369 }
1370
1371 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1373 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001374 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001375}
1376
Brian Andersond6927fb2016-07-23 23:37:30 -07001377void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001378{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001379 ATRACE_CALL();
1380 ALOGV("preComposition");
1381
Mathias Agopiancd60f992012-08-16 16:28:27 -07001382 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001383 mDrawingState.traverseInZOrder([&](Layer* layer) {
1384 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385 needExtraInvalidate = true;
1386 }
Robert Carr2047fae2016-11-28 14:09:09 -08001387 });
1388
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389 if (needExtraInvalidate) {
1390 signalLayerUpdate();
1391 }
1392}
1393
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394void SurfaceFlinger::updateCompositorTiming(
1395 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1396 std::shared_ptr<FenceTime>& presentFenceTime) {
1397 // Update queue of past composite+present times and determine the
1398 // most recently known composite to present latency.
1399 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1400 nsecs_t compositeToPresentLatency = -1;
1401 while (!mCompositePresentTimes.empty()) {
1402 CompositePresentTime& cpt = mCompositePresentTimes.front();
1403 // Cached values should have been updated before calling this method,
1404 // which helps avoid duplicate syscalls.
1405 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1406 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1407 break;
1408 }
1409 compositeToPresentLatency = displayTime - cpt.composite;
1410 mCompositePresentTimes.pop();
1411 }
1412
1413 // Don't let mCompositePresentTimes grow unbounded, just in case.
1414 while (mCompositePresentTimes.size() > 16) {
1415 mCompositePresentTimes.pop();
1416 }
1417
Brian Andersond0010582017-03-07 13:20:31 -08001418 setCompositorTimingSnapped(
1419 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1420}
1421
1422void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1423 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424 // Integer division and modulo round toward 0 not -inf, so we need to
1425 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001426 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001427 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1428 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1429
Brian Andersond0010582017-03-07 13:20:31 -08001430 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1431 if (idealLatency <= 0) {
1432 idealLatency = vsyncInterval;
1433 }
1434
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 // Snap the latency to a value that removes scheduling jitter from the
1436 // composition and present times, which often have >1ms of jitter.
1437 // Reducing jitter is important if an app attempts to extrapolate
1438 // something (such as user input) to an accurate diasplay time.
1439 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1440 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001441 nsecs_t bias = vsyncInterval / 2;
1442 int64_t extraVsyncs =
1443 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1444 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1445 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446
Brian Andersond0010582017-03-07 13:20:31 -08001447 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001448 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1449 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001450 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001451}
1452
1453void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 ATRACE_CALL();
1456 ALOGV("postComposition");
1457
Brian Anderson3546a3f2016-07-14 11:51:14 -07001458 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001459 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001460 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001461 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001462 }
1463
Brian Andersond6927fb2016-07-23 23:37:30 -07001464 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001465
1466 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1467 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1468 glCompositionDoneFenceTime =
1469 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1470 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1471 } else {
1472 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1473 }
1474 mGlCompositionDoneTimeline.updateSignalTimes();
1475
1476 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1477 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1478 mDisplayTimeline.push(displayFenceTime);
1479 mDisplayTimeline.updateSignalTimes();
1480
1481 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1482 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1483 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1484 presentFenceTime = &displayFenceTime;
1485 } else {
1486 retireFenceTime = &displayFenceTime;
1487 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001488
1489 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1490 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1491
1492 // We use the refreshStartTime which might be sampled a little later than
1493 // when we started doing work for this frame, but that should be okay
1494 // since updateCompositorTiming has snapping logic.
1495 updateCompositorTiming(
1496 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001497 CompositorTiming compositorTiming;
1498 {
1499 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1500 compositorTiming = mCompositorTiming;
1501 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001502
Robert Carr2047fae2016-11-28 14:09:09 -08001503 mDrawingState.traverseInZOrder([&](Layer* layer) {
1504 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Andersond0010582017-03-07 13:20:31 -08001505 *presentFenceTime, *retireFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001506 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001507 recordBufferingStats(layer->getName().string(),
1508 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001509 }
Robert Carr2047fae2016-11-28 14:09:09 -08001510 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001511
Brian Anderson3d4039d2016-09-23 16:31:30 -07001512 if (displayFence->isValid()) {
1513 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001514 enableHardwareVsync();
1515 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001516 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001517 }
1518 }
1519
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001520 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001521 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001522 enableHardwareVsync();
1523 }
1524 }
1525
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001526 if (mAnimCompositionPending) {
1527 mAnimCompositionPending = false;
1528
Brian Anderson3d4039d2016-09-23 16:31:30 -07001529 if (displayFenceTime->isValid()) {
1530 mAnimFrameTracker.setActualPresentFence(
1531 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001532 } else {
1533 // The HWC doesn't support present fences, so use the refresh
1534 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 nsecs_t presentTime =
1536 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001537 mAnimFrameTracker.setActualPresentTime(presentTime);
1538 }
1539 mAnimFrameTracker.advanceFrame();
1540 }
Dan Stozab90cf072015-03-05 11:05:59 -08001541
1542 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1543 return;
1544 }
1545
1546 nsecs_t currentTime = systemTime();
1547 if (mHasPoweredOff) {
1548 mHasPoweredOff = false;
1549 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001550 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001552 if (numPeriods < NUM_BUCKETS - 1) {
1553 mFrameBuckets[numPeriods] += elapsedTime;
1554 } else {
1555 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1556 }
1557 mTotalTime += elapsedTime;
1558 }
1559 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560}
1561
1562void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001563 ATRACE_CALL();
1564 ALOGV("rebuildLayerStacks");
1565
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001567 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1568 ATRACE_CALL();
1569 mVisibleRegionsDirty = false;
1570 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001571
Jeff Sharkey76488112017-02-27 14:15:18 -07001572 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1573 Region opaqueRegion;
1574 Region dirtyRegion;
1575 Vector<sp<Layer>> layersSortedByZ;
1576 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1577 const Transform& tr(displayDevice->getTransform());
1578 const Rect bounds(displayDevice->getBounds());
1579 if (displayDevice->isDisplayOn()) {
1580 computeVisibleRegions(
1581 displayDevice->getLayerStack(), dirtyRegion,
1582 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001583
Jeff Sharkey76488112017-02-27 14:15:18 -07001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1586 Region drawRegion(tr.transform(
1587 layer->visibleNonTransparentRegion));
1588 drawRegion.andSelf(bounds);
1589 if (!drawRegion.isEmpty()) {
1590 layersSortedByZ.add(layer);
1591 } else {
1592 // Clear out the HWC layer if this layer was
1593 // previously visible, but no longer is
1594 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1595 nullptr);
1596 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001597 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001598 // WM changes displayDevice->layerStack upon sleep/awake.
1599 // Here we make sure we delete the HWC layers even if
1600 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001601 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1602 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001603 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001604 });
1605 }
1606 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1607 displayDevice->undefinedRegion.set(bounds);
1608 displayDevice->undefinedRegion.subtractSelf(
1609 tr.transform(opaqueRegion));
1610 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001611 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001612 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001614
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001616 ATRACE_CALL();
1617 ALOGV("setUpHWComposer");
1618
Jesse Hall028dc8f2013-08-20 16:35:32 -07001619 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001620 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1621 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1622 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1623
1624 // If nothing has changed (!dirty), don't recompose.
1625 // If something changed, but we don't currently have any visible layers,
1626 // and didn't when we last did a composition, then skip it this time.
1627 // The second rule does two things:
1628 // - When all layers are removed from a display, we'll emit one black
1629 // frame, then nothing more until we get new layers.
1630 // - When a display is created with a private layer stack, we won't
1631 // emit any black frames until a layer is added to the layer stack.
1632 bool mustRecompose = dirty && !(empty && wasEmpty);
1633
1634 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1635 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1636 mustRecompose ? "doing" : "skipping",
1637 dirty ? "+" : "-",
1638 empty ? "+" : "-",
1639 wasEmpty ? "+" : "-");
1640
Dan Stoza71433162014-02-04 16:22:36 -08001641 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001642
1643 if (mustRecompose) {
1644 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1645 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001646 }
1647
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 // build the h/w work list
1649 if (CC_UNLIKELY(mGeometryInvalid)) {
1650 mGeometryInvalid = false;
1651 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1652 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1653 const auto hwcId = displayDevice->getHwcDisplayId();
1654 if (hwcId >= 0) {
1655 const Vector<sp<Layer>>& currentLayers(
1656 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001657 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001658 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 if (!layer->hasHwcLayer(hwcId)) {
1660 auto hwcLayer = mHwc->createLayer(hwcId);
1661 if (hwcLayer) {
1662 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1663 } else {
1664 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001665 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001666 }
1667 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001668
Robert Carrae060832016-11-28 10:51:00 -08001669 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001670 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001672 }
1673 }
1674 }
1675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001676 }
Riley Andrews03414a12014-07-01 14:22:59 -07001677
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001678
1679 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1680
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 // Set the per-frame data
1682 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1683 auto& displayDevice = mDisplays[displayId];
1684 const auto hwcId = displayDevice->getHwcDisplayId();
1685 if (hwcId < 0) {
1686 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001687 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001688 if (colorMatrix != mPreviousColorMatrix) {
1689 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1690 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1691 "display %zd: %d", displayId, result);
1692 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1694 layer->setPerFrameData(displayDevice);
1695 }
1696 }
1697
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001698 mPreviousColorMatrix = colorMatrix;
1699
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001701 auto& displayDevice = mDisplays[displayId];
1702 if (!displayDevice->isDisplayOn()) {
1703 continue;
1704 }
1705
1706 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1708 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001709 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001711
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712void SurfaceFlinger::doComposition() {
1713 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001714 ALOGV("doComposition");
1715
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001716 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001717 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001718 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001719 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001720 // transform the dirty region into this screen's coordinate space
1721 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001722
1723 // repaint the framebuffer (if needed)
1724 doDisplayComposition(hw, dirtyRegion);
1725
Mathias Agopiancd60f992012-08-16 16:28:27 -07001726 hw->dirtyRegion.clear();
1727 hw->flip(hw->swapRegion);
1728 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001729 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001730 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001731 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001732}
1733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001734void SurfaceFlinger::postFramebuffer()
1735{
Mathias Agopian841cde52012-03-01 15:44:37 -08001736 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001738
Mathias Agopiana44b0412011-10-16 18:46:35 -07001739 const nsecs_t now = systemTime();
1740 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001741
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1743 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001744 if (!displayDevice->isDisplayOn()) {
1745 continue;
1746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 const auto hwcId = displayDevice->getHwcDisplayId();
1748 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001749 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001750 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001751 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001752 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1754 sp<Fence> releaseFence = Fence::NO_FENCE;
1755 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1756 releaseFence = displayDevice->getClientTargetAcquireFence();
1757 } else {
1758 auto hwcLayer = layer->getHwcLayer(hwcId);
1759 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001760 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 layer->onLayerDisplayed(releaseFence);
1762 }
1763 if (hwcId >= 0) {
1764 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001765 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001766 }
1767
Mathias Agopiana44b0412011-10-16 18:46:35 -07001768 mLastSwapBufferTime = systemTime() - now;
1769 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001770
1771 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1772 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1773 logFrameStats();
1774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001775}
1776
Mathias Agopian87baae12012-07-31 12:38:26 -07001777void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001778{
Mathias Agopian841cde52012-03-01 15:44:37 -08001779 ATRACE_CALL();
1780
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001781 // here we keep a copy of the drawing state (that is the state that's
1782 // going to be overwritten by handleTransactionLocked()) outside of
1783 // mStateLock so that the side-effects of the State assignment
1784 // don't happen with mStateLock held (which can cause deadlocks).
1785 State drawingState(mDrawingState);
1786
Mathias Agopianca4d3602011-05-19 15:38:14 -07001787 Mutex::Autolock _l(mStateLock);
1788 const nsecs_t now = systemTime();
1789 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790
Mathias Agopianca4d3602011-05-19 15:38:14 -07001791 // Here we're guaranteed that some transaction flags are set
1792 // so we can call handleTransactionLocked() unconditionally.
1793 // We call getTransactionFlags(), which will also clear the flags,
1794 // with mStateLock held to guarantee that mCurrentState won't change
1795 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001796
Mathias Agopiane57f2922012-08-09 16:29:12 -07001797 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001798 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001799
Mathias Agopianca4d3602011-05-19 15:38:14 -07001800 mLastTransactionTime = systemTime() - now;
1801 mDebugInTransaction = 0;
1802 invalidateHwcGeometry();
1803 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001804}
1805
Mathias Agopian87baae12012-07-31 12:38:26 -07001806void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001807{
Dan Stoza7dde5992015-05-22 09:51:44 -07001808 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001809 mCurrentState.traverseInZOrder([](Layer* layer) {
1810 layer->notifyAvailableFrames();
1811 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813 /*
1814 * Traversal of the children
1815 * (perform the transaction for each of them if needed)
1816 */
1817
Mathias Agopian3559b072012-08-15 13:46:03 -07001818 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001819 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001821 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822
1823 const uint32_t flags = layer->doTransaction(0);
1824 if (flags & Layer::eVisibleRegion)
1825 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001826 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001827 }
1828
1829 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001830 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 */
1832
Mathias Agopiane57f2922012-08-09 16:29:12 -07001833 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 // here we take advantage of Vector's copy-on-write semantics to
1835 // improve performance by skipping the transaction entirely when
1836 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001837 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1838 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001840 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001841 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001842 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001843
1844 // find the displays that were removed
1845 // (ie: in drawing state but not in current state)
1846 // also handle displays that changed
1847 // (ie: displays that are in both lists)
1848 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001849 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1850 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001851 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001852 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001853 // Call makeCurrent() on the primary display so we can
1854 // be sure that nothing associated with this display
1855 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001856 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001857 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001858 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1859 if (hw != NULL)
1860 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001861 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001862 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001863 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001864 } else {
1865 ALOGW("trying to remove the main display");
1866 }
1867 } else {
1868 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001869 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001870 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001871 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1872 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001873 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001874 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001875 // recreating the DisplayDevice, so we just remove it
1876 // from the drawing state, so that it get re-added
1877 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001878 sp<DisplayDevice> hw(getDisplayDevice(display));
1879 if (hw != NULL)
1880 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001881 mDisplays.removeItem(display);
1882 mDrawingState.displays.removeItemsAt(i);
1883 dc--; i--;
1884 // at this point we must loop to the next item
1885 continue;
1886 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001887
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001888 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001889 if (disp != NULL) {
1890 if (state.layerStack != draw[i].layerStack) {
1891 disp->setLayerStack(state.layerStack);
1892 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001893 if ((state.orientation != draw[i].orientation)
1894 || (state.viewport != draw[i].viewport)
1895 || (state.frame != draw[i].frame))
1896 {
1897 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001898 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001899 }
Michael Lentine47e45402014-07-18 15:34:25 -07001900 if (state.width != draw[i].width || state.height != draw[i].height) {
1901 disp->setDisplaySize(state.width, state.height);
1902 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001903 }
1904 }
1905 }
1906
1907 // find displays that were added
1908 // (ie: in current state but not in drawing state)
1909 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001910 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001911 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001912
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001913 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001914 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001915 sp<IGraphicBufferProducer> bqProducer;
1916 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001917 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1918 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001919
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001921 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001922 // Virtual displays without a surface are dormant:
1923 // they have external state (layer stack, projection,
1924 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001925 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001926
Dan Stoza8cf150a2016-08-02 10:27:31 -07001927 if (mUseHwcVirtualDisplays) {
1928 int width = 0;
1929 int status = state.surface->query(
1930 NATIVE_WINDOW_WIDTH, &width);
1931 ALOGE_IF(status != NO_ERROR,
1932 "Unable to query width (%d)", status);
1933 int height = 0;
1934 status = state.surface->query(
1935 NATIVE_WINDOW_HEIGHT, &height);
1936 ALOGE_IF(status != NO_ERROR,
1937 "Unable to query height (%d)", status);
1938 int intFormat = 0;
1939 status = state.surface->query(
1940 NATIVE_WINDOW_FORMAT, &intFormat);
1941 ALOGE_IF(status != NO_ERROR,
1942 "Unable to query format (%d)", status);
1943 auto format = static_cast<android_pixel_format_t>(
1944 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001945
Dan Stoza8cf150a2016-08-02 10:27:31 -07001946 mHwc->allocateVirtualDisplay(width, height, &format,
1947 &hwcId);
1948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949
Dan Stoza5cf424b2016-05-20 14:02:39 -07001950 // TODO: Plumb requested format back up to consumer
1951
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 sp<VirtualDisplaySurface> vds =
1953 new VirtualDisplaySurface(*mHwc,
1954 hwcId, state.surface, bqProducer,
1955 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001956
1957 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001958 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001959 }
1960 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001961 ALOGE_IF(state.surface!=NULL,
1962 "adding a supported display, but rendering "
1963 "surface is provided (%p), ignoring it",
1964 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001965
1966 hwcId = state.type;
1967 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1968 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001969 }
1970
1971 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001972 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001973 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 state.type, hwcId, state.isSecure, display,
1975 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001976 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001977 hw->setLayerStack(state.layerStack);
1978 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001979 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001980 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001981 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001983 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001984 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001985 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001986 }
1987 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001989 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990
Mathias Agopian84300952012-11-21 16:02:13 -08001991 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1992 // The transform hint might have changed for some layers
1993 // (either because a display has changed, or because a layer
1994 // as changed).
1995 //
1996 // Walk through all the layers in currentLayers,
1997 // and update their transform hint.
1998 //
1999 // If a layer is visible only on a single display, then that
2000 // display is used to calculate the hint, otherwise we use the
2001 // default display.
2002 //
2003 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2004 // the hint is set before we acquire a buffer from the surface texture.
2005 //
2006 // NOTE: layer transactions have taken place already, so we use their
2007 // drawing state. However, SurfaceFlinger's own transaction has not
2008 // happened yet, so we must use the current state layer list
2009 // (soon to become the drawing state list).
2010 //
2011 sp<const DisplayDevice> disp;
2012 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002013 bool first = true;
2014 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002015 // NOTE: we rely on the fact that layers are sorted by
2016 // layerStack first (so we don't have to traverse the list
2017 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002018 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002019 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002020 currentlayerStack = layerStack;
2021 // figure out if this layerstack is mirrored
2022 // (more than one display) if so, pick the default display,
2023 // if not, pick the only display it's on.
2024 disp.clear();
2025 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2026 sp<const DisplayDevice> hw(mDisplays[dpy]);
2027 if (hw->getLayerStack() == currentlayerStack) {
2028 if (disp == NULL) {
2029 disp = hw;
2030 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002031 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002032 break;
2033 }
2034 }
2035 }
2036 }
Chet Haase91d25932013-04-11 15:24:55 -07002037 if (disp == NULL) {
2038 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2039 // redraw after transform hint changes. See bug 8508397.
2040
2041 // could be null when this layer is using a layerStack
2042 // that is not visible on any display. Also can occur at
2043 // screen off/on times.
2044 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002045 }
Chet Haase91d25932013-04-11 15:24:55 -07002046 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002047
2048 first = false;
2049 });
Mathias Agopian84300952012-11-21 16:02:13 -08002050 }
2051
2052
Mathias Agopian3559b072012-08-15 13:46:03 -07002053 /*
2054 * Perform our own transaction if needed
2055 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002056
2057 if (mLayersAdded) {
2058 mLayersAdded = false;
2059 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002060 mVisibleRegionsDirty = true;
2061 }
2062
2063 // some layers might have been removed, so
2064 // we need to update the regions they're exposing.
2065 if (mLayersRemoved) {
2066 mLayersRemoved = false;
2067 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002068 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002069 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002070 // this layer is not visible anymore
2071 // TODO: we could traverse the tree from front to back and
2072 // compute the actual visible region
2073 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002074 Region visibleReg;
2075 visibleReg.set(layer->computeScreenBounds());
2076 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002077 }
Robert Carr2047fae2016-11-28 14:09:09 -08002078 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079 }
2080
2081 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002082
2083 updateCursorAsync();
2084}
2085
2086void SurfaceFlinger::updateCursorAsync()
2087{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2089 auto& displayDevice = mDisplays[displayId];
2090 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002091 continue;
2092 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093
2094 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2095 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002096 }
2097 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098}
2099
2100void SurfaceFlinger::commitTransaction()
2101{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002102 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002104 for (const auto& l : mLayersPendingRemoval) {
2105 recordBufferingStats(l->getName().string(),
2106 l->getOccupancyHistory(true));
2107 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002108 }
2109 mLayersPendingRemoval.clear();
2110 }
2111
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002112 // If this transaction is part of a window animation then the next frame
2113 // we composite should be considered an animation as well.
2114 mAnimCompositionPending = mAnimTransactionPending;
2115
Mathias Agopian4fec8732012-06-29 14:12:52 -07002116 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002117 mDrawingState.traverseInZOrder([](Layer* layer) {
2118 layer->commitChildList();
2119 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002120 mTransactionPending = false;
2121 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002122 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123}
2124
Robert Carr2047fae2016-11-28 14:09:09 -08002125void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002126 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002127{
Mathias Agopian841cde52012-03-01 15:44:37 -08002128 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 Region aboveOpaqueLayers;
2132 Region aboveCoveredLayers;
2133 Region dirty;
2134
Mathias Agopian87baae12012-07-31 12:38:26 -07002135 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136
Robert Carr2047fae2016-11-28 14:09:09 -08002137 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002139 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140
Jesse Hall01e29052013-02-19 16:13:35 -08002141 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002142 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002143 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002144
Mathias Agopianab028732010-03-16 16:41:46 -07002145 /*
2146 * opaqueRegion: area of a surface that is fully opaque.
2147 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002149
2150 /*
2151 * visibleRegion: area of a surface that is visible on screen
2152 * and not fully transparent. This is essentially the layer's
2153 * footprint minus the opaque regions above it.
2154 * Areas covered by a translucent surface are considered visible.
2155 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002157
2158 /*
2159 * coveredRegion: area of a surface that is covered by all
2160 * visible regions above it (which includes the translucent areas).
2161 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002163
Jesse Halla8026d22012-09-25 13:25:04 -07002164 /*
2165 * transparentRegion: area of a surface that is hinted to be completely
2166 * transparent. This is only used to tell when the layer has no visible
2167 * non-transparent regions and can be removed from the layer list. It
2168 * does not affect the visibleRegion of this layer or any layers
2169 * beneath it. The hint may not be correct if apps don't respect the
2170 * SurfaceView restrictions (which, sadly, some don't).
2171 */
2172 Region transparentRegion;
2173
Mathias Agopianab028732010-03-16 16:41:46 -07002174
2175 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002176 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002177 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002178 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002180 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002181 if (!visibleRegion.isEmpty()) {
2182 // Remove the transparent area from the visible region
2183 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002184 if (tr.preserveRects()) {
2185 // transform the transparent region
2186 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002187 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002188 // transformation too complex, can't do the
2189 // transparent region optimization.
2190 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002191 }
Mathias Agopianab028732010-03-16 16:41:46 -07002192 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
Mathias Agopianab028732010-03-16 16:41:46 -07002194 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002195 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002197 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2198 // the opaque region is the layer's footprint
2199 opaqueRegion = visibleRegion;
2200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201 }
2202 }
2203
Mathias Agopianab028732010-03-16 16:41:46 -07002204 // Clip the covered region to the visible region
2205 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2206
2207 // Update aboveCoveredLayers for next (lower) layer
2208 aboveCoveredLayers.orSelf(visibleRegion);
2209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210 // subtract the opaque region covered by the layers above us
2211 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212
2213 // compute this layer's dirty region
2214 if (layer->contentDirty) {
2215 // we need to invalidate the whole region
2216 dirty = visibleRegion;
2217 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002218 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219 layer->contentDirty = false;
2220 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002221 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002222 * the exposed region consists of two components:
2223 * 1) what's VISIBLE now and was COVERED before
2224 * 2) what's EXPOSED now less what was EXPOSED before
2225 *
2226 * note that (1) is conservative, we start with the whole
2227 * visible region but only keep what used to be covered by
2228 * something -- which mean it may have been exposed.
2229 *
2230 * (2) handles areas that were not covered by anything but got
2231 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002232 */
Mathias Agopianab028732010-03-16 16:41:46 -07002233 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002234 const Region oldVisibleRegion = layer->visibleRegion;
2235 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002236 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2237 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 }
2239 dirty.subtractSelf(aboveOpaqueLayers);
2240
2241 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002242 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Mathias Agopianab028732010-03-16 16:41:46 -07002244 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002246
Jesse Halla8026d22012-09-25 13:25:04 -07002247 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248 layer->setVisibleRegion(visibleRegion);
2249 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002250 layer->setVisibleNonTransparentRegion(
2251 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002252 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopian87baae12012-07-31 12:38:26 -07002254 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255}
2256
Mathias Agopian87baae12012-07-31 12:38:26 -07002257void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2258 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002259 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002260 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2261 if (hw->getLayerStack() == layerStack) {
2262 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002263 }
2264 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002265}
2266
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 ALOGV("handlePageFlip");
2270
Brian Andersond6927fb2016-07-23 23:37:30 -07002271 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272
Mathias Agopian4fec8732012-06-29 14:12:52 -07002273 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002274 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002275
2276 // Store the set of layers that need updates. This set must not change as
2277 // buffers are being latched, as this could result in a deadlock.
2278 // Example: Two producers share the same command stream and:
2279 // 1.) Layer 0 is latched
2280 // 2.) Layer 0 gets a new frame
2281 // 2.) Layer 1 gets a new frame
2282 // 3.) Layer 1 is latched.
2283 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2284 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002285 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286 if (layer->hasQueuedFrame()) {
2287 frameQueued = true;
2288 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002289 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002290 } else {
2291 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002292 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002293 } else {
2294 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002295 }
Robert Carr2047fae2016-11-28 14:09:09 -08002296 });
2297
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002299 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002300 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002302 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002303
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002304 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002305
2306 // If we will need to wake up at some time in the future to deal with a
2307 // queued frame that shouldn't be displayed during this vsync period, wake
2308 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002310 signalLayerUpdate();
2311 }
2312
2313 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315}
2316
Mathias Agopianad456f92011-01-13 17:53:01 -08002317void SurfaceFlinger::invalidateHwcGeometry()
2318{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002319 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002320}
2321
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002322
Fabien Sanglard830b8472016-11-30 16:35:58 -08002323void SurfaceFlinger::doDisplayComposition(
2324 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002325 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326{
Dan Stoza71433162014-02-04 16:22:36 -08002327 // We only need to actually compose the display if:
2328 // 1) It is being handled by hardware composer, which may need this to
2329 // keep its virtual display state machine in sync, or
2330 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002332 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002333 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002334 return;
2335 }
2336
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 ALOGV("doDisplayComposition");
2338
Mathias Agopian87baae12012-07-31 12:38:26 -07002339 Region dirtyRegion(inDirtyRegion);
2340
Mathias Agopianb8a55602009-06-26 19:06:36 -07002341 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343
Fabien Sanglard830b8472016-11-30 16:35:58 -08002344 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002345 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002346 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2347 // takes a rectangle, we must make sure to update that whole
2348 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002350 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002351 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002352 // We need to redraw the rectangle that will be updated
2353 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002354 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002355 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002356 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002357 } else {
2358 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002359 dirtyRegion.set(displayDevice->bounds());
2360 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 }
2362 }
2363
Fabien Sanglard830b8472016-11-30 16:35:58 -08002364 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002366 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002367 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002368
2369 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002370 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371}
2372
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373bool SurfaceFlinger::doComposeSurfaces(
2374 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002377
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002379
2380 mat4 oldColorMatrix;
2381 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2382 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2383 if (applyColorMatrix) {
2384 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2385 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2386 }
2387
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2389 if (hasClientComposition) {
2390 ALOGV("hasClientComposition");
2391
2392 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002393 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002395 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2396 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2397 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2398 }
2399 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002400 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002401
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2404 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002405 // when using overlays, we assume a fully transparent framebuffer
2406 // NOTE: we could reduce how much we need to clear, for instance
2407 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002408 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002411 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002412 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002414
2415 // we remove the scissor part
2416 // we're left with the letterbox region
2417 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002419
2420 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002422
2423 // but limit it to the dirty region
2424 region.andSelf(dirty);
2425
Mathias Agopianb9494d52012-04-18 02:28:45 -07002426 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002427 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002428 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002430 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002431 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002432
Dan Stoza9e56aa02015-11-02 13:00:03 -08002433 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002434 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002435 // scissor on the main display. It should never be needed
2436 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 const Rect& bounds(displayDevice->getBounds());
2438 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002439 if (scissor != bounds) {
2440 // scissor doesn't match the screen's dimensions, so we
2441 // need to clear everything outside of it and enable
2442 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002443
Mathias Agopianf45c5102012-10-24 16:29:17 -07002444 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 const uint32_t height = displayDevice->getHeight();
2446 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002447 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002448 }
2449 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002450 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002451
Mathias Agopian85d751c2012-08-29 16:59:24 -07002452 /*
2453 * and then, render the layers targeted at the framebuffer
2454 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002455
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 ALOGV("Rendering client layers");
2457 const Transform& displayTransform = displayDevice->getTransform();
2458 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002459 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 bool firstLayer = true;
2461 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2462 const Region clip(dirty.intersect(
2463 displayTransform.transform(layer->visibleRegion)));
2464 ALOGV("Layer: %s", layer->getName().string());
2465 ALOGV(" Composition type: %s",
2466 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002467 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 switch (layer->getCompositionType(hwcId)) {
2469 case HWC2::Composition::Cursor:
2470 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002471 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002473 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2475 layer->isOpaque(state) && (state.alpha == 1.0f)
2476 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002477 // never clear the very first layer since we're
2478 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002479 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002480 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 case HWC2::Composition::Client: {
2484 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002485 break;
2486 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002488 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002489 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 } else {
2491 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002492 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002494 }
2495 } else {
2496 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002498 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002500 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002502 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002503 }
2504 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002505
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002506 if (applyColorMatrix) {
2507 getRenderEngine().setupColorTransform(oldColorMatrix);
2508 }
2509
Mathias Agopianf45c5102012-10-24 16:29:17 -07002510 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002512 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513}
2514
Fabien Sanglard830b8472016-11-30 16:35:58 -08002515void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2516 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002517 RenderEngine& engine(getRenderEngine());
2518 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519}
2520
Dan Stoza7d89d062015-04-30 13:29:25 -07002521status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002522 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002523 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 const sp<Layer>& lbc,
2525 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002526{
Dan Stoza7d89d062015-04-30 13:29:25 -07002527 // add this layer to the current state list
2528 {
2529 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002531 return NO_MEMORY;
2532 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002533 if (parent == nullptr) {
2534 mCurrentState.layersSortedByZ.add(lbc);
2535 } else {
2536 parent->addChild(lbc);
2537 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002538 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 mLayersAdded = true;
2540 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002541 }
2542
Mathias Agopian96f08192010-06-02 23:28:45 -07002543 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002544 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002545
Dan Stoza7d89d062015-04-30 13:29:25 -07002546 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002547}
2548
Robert Carr9524cb32017-02-13 11:32:32 -08002549status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002550 Mutex::Autolock _l(mStateLock);
2551
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552 const auto& p = layer->getParent();
2553 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2554 mCurrentState.layersSortedByZ.remove(layer);
2555
Robert Carr136e2f62017-02-08 17:54:29 -08002556 // As a matter of normal operation, the LayerCleaner will produce a second
2557 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2558 // so we will succeed in promoting it, but it's already been removed
2559 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2560 // otherwise something has gone wrong and we are leaking the layer.
2561 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2563 layer->getName().string(),
2564 (p != nullptr) ? p->getName().string() : "no-parent");
2565 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002566 } else if (index < 0) {
2567 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002568 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002569
2570 mLayersPendingRemoval.add(layer);
2571 mLayersRemoved = true;
2572 mNumLayers--;
2573 setTransactionFlags(eTransactionNeeded);
2574 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575}
2576
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002577uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002578 return android_atomic_release_load(&mTransactionFlags);
2579}
2580
Mathias Agopian3f844832013-08-07 21:24:32 -07002581uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2583}
2584
Mathias Agopian3f844832013-08-07 21:24:32 -07002585uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2587 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002588 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 }
2590 return old;
2591}
2592
Mathias Agopian8b33f032012-07-24 20:43:54 -07002593void SurfaceFlinger::setTransactionState(
2594 const Vector<ComposerState>& state,
2595 const Vector<DisplayState>& displays,
2596 uint32_t flags)
2597{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002598 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002599 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002600 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002601
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002602 if (flags & eAnimation) {
2603 // For window updates that are part of an animation we must wait for
2604 // previous animation "frames" to be handled.
2605 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002606 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002607 if (CC_UNLIKELY(err != NO_ERROR)) {
2608 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002609 // caller after a few seconds.
2610 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2611 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002612 mAnimTransactionPending = false;
2613 break;
2614 }
2615 }
2616 }
2617
Mathias Agopiane57f2922012-08-09 16:29:12 -07002618 size_t count = displays.size();
2619 for (size_t i=0 ; i<count ; i++) {
2620 const DisplayState& s(displays[i]);
2621 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002622 }
2623
Mathias Agopiane57f2922012-08-09 16:29:12 -07002624 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002625 for (size_t i=0 ; i<count ; i++) {
2626 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002627 // Here we need to check that the interface we're given is indeed
2628 // one of our own. A malicious client could give us a NULL
2629 // IInterface, or one of its own or even one of our own but a
2630 // different type. All these situations would cause us to crash.
2631 //
2632 // NOTE: it would be better to use RTTI as we could directly check
2633 // that we have a Client*. however, RTTI is disabled in Android.
2634 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002635 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002636 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002637 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002638 sp<Client> client( static_cast<Client *>(s.client.get()) );
2639 transactionFlags |= setClientStateLocked(client, s.state);
2640 }
2641 }
2642 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002643 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002644
Robert Carr2a7dbb42016-05-24 11:41:28 -07002645 // If a synchronous transaction is explicitly requested without any changes,
2646 // force a transaction anyway. This can be used as a flush mechanism for
2647 // previous async transactions.
2648 if (transactionFlags == 0 && (flags & eSynchronous)) {
2649 transactionFlags = eTransactionNeeded;
2650 }
2651
Mathias Agopian386aa982011-11-07 21:58:03 -08002652 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002653 if (mInterceptor.isEnabled()) {
2654 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2655 }
Irvel468051e2016-06-13 16:44:44 -07002656
Mathias Agopian386aa982011-11-07 21:58:03 -08002657 // this triggers the transaction
2658 setTransactionFlags(transactionFlags);
2659
2660 // if this is a synchronous transaction, wait for it to take effect
2661 // before returning.
2662 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002663 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002664 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002665 if (flags & eAnimation) {
2666 mAnimTransactionPending = true;
2667 }
2668 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002669 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2670 if (CC_UNLIKELY(err != NO_ERROR)) {
2671 // just in case something goes wrong in SF, return to the
2672 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002673 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2674 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002675 break;
2676 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002677 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 }
2679}
2680
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2682{
Jesse Hall9a143922012-10-04 16:29:19 -07002683 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2684 if (dpyIdx < 0)
2685 return 0;
2686
Mathias Agopiane57f2922012-08-09 16:29:12 -07002687 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002688 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002689 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002690 const uint32_t what = s.what;
2691 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002692 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002693 disp.surface = s.surface;
2694 flags |= eDisplayTransactionNeeded;
2695 }
2696 }
2697 if (what & DisplayState::eLayerStackChanged) {
2698 if (disp.layerStack != s.layerStack) {
2699 disp.layerStack = s.layerStack;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002703 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002704 if (disp.orientation != s.orientation) {
2705 disp.orientation = s.orientation;
2706 flags |= eDisplayTransactionNeeded;
2707 }
2708 if (disp.frame != s.frame) {
2709 disp.frame = s.frame;
2710 flags |= eDisplayTransactionNeeded;
2711 }
2712 if (disp.viewport != s.viewport) {
2713 disp.viewport = s.viewport;
2714 flags |= eDisplayTransactionNeeded;
2715 }
2716 }
Michael Lentine47e45402014-07-18 15:34:25 -07002717 if (what & DisplayState::eDisplaySizeChanged) {
2718 if (disp.width != s.width) {
2719 disp.width = s.width;
2720 flags |= eDisplayTransactionNeeded;
2721 }
2722 if (disp.height != s.height) {
2723 disp.height = s.height;
2724 flags |= eDisplayTransactionNeeded;
2725 }
2726 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002727 }
2728 return flags;
2729}
2730
2731uint32_t SurfaceFlinger::setClientStateLocked(
2732 const sp<Client>& client,
2733 const layer_state_t& s)
2734{
2735 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002736 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002737 if (layer != 0) {
2738 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002739 bool geometryAppliesWithResize =
2740 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002742 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002744 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002745 }
2746 if (what & layer_state_t::eLayerChanged) {
2747 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002748 const auto& p = layer->getParent();
2749 if (p == nullptr) {
2750 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2751 if (layer->setLayer(s.z) && idx >= 0) {
2752 mCurrentState.layersSortedByZ.removeAt(idx);
2753 mCurrentState.layersSortedByZ.add(layer);
2754 // we need traversal (state changed)
2755 // AND transaction (list changed)
2756 flags |= eTransactionNeeded|eTraversalNeeded;
2757 }
2758 } else {
2759 if (p->setChildLayer(layer, s.z)) {
2760 flags |= eTransactionNeeded|eTraversalNeeded;
2761 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002762 }
2763 }
2764 if (what & layer_state_t::eSizeChanged) {
2765 if (layer->setSize(s.w, s.h)) {
2766 flags |= eTraversalNeeded;
2767 }
2768 }
2769 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002771 flags |= eTraversalNeeded;
2772 }
2773 if (what & layer_state_t::eMatrixChanged) {
2774 if (layer->setMatrix(s.matrix))
2775 flags |= eTraversalNeeded;
2776 }
2777 if (what & layer_state_t::eTransparentRegionChanged) {
2778 if (layer->setTransparentRegionHint(s.transparentRegion))
2779 flags |= eTraversalNeeded;
2780 }
Dan Stoza23116082015-06-18 14:58:39 -07002781 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 if (layer->setFlags(s.flags, s.mask))
2783 flags |= eTraversalNeeded;
2784 }
2785 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002786 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002787 flags |= eTraversalNeeded;
2788 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002789 if (what & layer_state_t::eFinalCropChanged) {
2790 if (layer->setFinalCrop(s.finalCrop))
2791 flags |= eTraversalNeeded;
2792 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 // We only allow setting layer stacks for top level layers,
2796 // everything else inherits layer stack from its parent.
2797 if (layer->hasParent()) {
2798 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2799 layer->getName().string());
2800 } else if (idx < 0) {
2801 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2802 "that also does not appear in the top level layer list. Something"
2803 " has gone wrong.", layer->getName().string());
2804 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002805 mCurrentState.layersSortedByZ.removeAt(idx);
2806 mCurrentState.layersSortedByZ.add(layer);
2807 // we need traversal (state changed)
2808 // AND transaction (list changed)
2809 flags |= eTransactionNeeded|eTraversalNeeded;
2810 }
2811 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002812 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002813 if (s.barrierHandle != nullptr) {
2814 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2815 } else if (s.barrierGbp != nullptr) {
2816 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2817 if (authenticateSurfaceTextureLocked(gbp)) {
2818 const auto& otherLayer =
2819 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2820 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2821 } else {
2822 ALOGE("Attempt to defer transaction to to an"
2823 " unrecognized GraphicBufferProducer");
2824 }
2825 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002826 // We don't trigger a traversal here because if no other state is
2827 // changed, we don't want this to cause any more work
2828 }
Robert Carr1db73f62016-12-21 12:58:51 -08002829 if (what & layer_state_t::eReparentChildren) {
2830 if (layer->reparentChildren(s.reparentHandle)) {
2831 flags |= eTransactionNeeded|eTraversalNeeded;
2832 }
2833 }
Robert Carr9524cb32017-02-13 11:32:32 -08002834 if (what & layer_state_t::eDetachChildren) {
2835 layer->detachChildren();
2836 }
Robert Carrc3574f72016-03-24 12:19:32 -07002837 if (what & layer_state_t::eOverrideScalingModeChanged) {
2838 layer->setOverrideScalingMode(s.overrideScalingMode);
2839 // We don't trigger a traversal here because if no other state is
2840 // changed, we don't want this to cause any more work
2841 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002842 }
2843 return flags;
2844}
2845
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002846status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002847 const String8& name,
2848 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002849 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002850 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2851 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002853 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002854 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002855 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002856 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002857 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002858
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002859 status_t result = NO_ERROR;
2860
2861 sp<Layer> layer;
2862
Mathias Agopian3165cc22012-08-08 19:42:09 -07002863 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2864 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002865 result = createNormalLayer(client,
2866 name, w, h, flags, format,
2867 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002869 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002870 result = createDimLayer(client,
2871 name, w, h, flags,
2872 handle, gbp, &layer);
2873 break;
2874 default:
2875 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 break;
2877 }
2878
Dan Stoza7d89d062015-04-30 13:29:25 -07002879 if (result != NO_ERROR) {
2880 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002882
Albert Chaulk479c60c2017-01-27 14:21:34 -05002883 layer->setInfo(windowType, ownerUid);
2884
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002886 if (result != NO_ERROR) {
2887 return result;
2888 }
Irvelffc9efc2016-07-27 15:16:37 -07002889 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002890
2891 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002892 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893}
2894
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002895status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2896 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2897 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898{
2899 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002900 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 case PIXEL_FORMAT_TRANSPARENT:
2902 case PIXEL_FORMAT_TRANSLUCENT:
2903 format = PIXEL_FORMAT_RGBA_8888;
2904 break;
2905 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002906 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 break;
2908 }
2909
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002910 *outLayer = new Layer(this, client, name, w, h, flags);
2911 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2912 if (err == NO_ERROR) {
2913 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002914 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002916
2917 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2918 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919}
2920
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002921status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2922 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2923 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002925 *outLayer = new LayerDim(this, client, name, w, h, flags);
2926 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002927 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002928 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002929}
2930
Mathias Agopianac9fa422013-02-11 16:40:36 -08002931status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932{
Robert Carr9524cb32017-02-13 11:32:32 -08002933 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002934 status_t err = NO_ERROR;
2935 sp<Layer> l(client->getLayerUser(handle));
2936 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002937 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002938 err = removeLayer(l);
2939 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2940 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002941 }
2942 return err;
2943}
2944
Mathias Agopian13127d82013-03-05 17:47:11 -08002945status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002946{
Mathias Agopian67106042013-03-14 19:18:13 -07002947 // called by ~LayerCleaner() when all references to the IBinder (handle)
2948 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002949 sp<Layer> l = layer.promote();
2950 if (l == nullptr) {
2951 // The layer has already been removed, carry on
2952 return NO_ERROR;
2953 } if (l->getParent() != nullptr) {
2954 // If we have a parent, then we can continue to live as long as it does.
2955 return NO_ERROR;
2956 }
2957 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Mathias Agopianb60314a2012-04-10 22:09:54 -07002960// ---------------------------------------------------------------------------
2961
Andy McFadden13a082e2012-08-24 10:16:42 -07002962void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002963 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002964 Vector<ComposerState> state;
2965 Vector<DisplayState> displays;
2966 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002967 d.what = DisplayState::eDisplayProjectionChanged |
2968 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002969 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002970 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002971 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002972 d.frame.makeInvalid();
2973 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002974 d.width = 0;
2975 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002976 displays.add(d);
2977 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002978 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2981 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002982 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002983
Brian Andersond0010582017-03-07 13:20:31 -08002984 // Use phase of 0 since phase is not known.
2985 // Use latency of 0, which will snap to the ideal latency.
2986 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002987}
2988
2989void SurfaceFlinger::initializeDisplays() {
2990 class MessageScreenInitialized : public MessageBase {
2991 SurfaceFlinger* flinger;
2992 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002993 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002994 virtual bool handler() {
2995 flinger->onInitializeDisplays();
2996 return true;
2997 }
2998 };
2999 sp<MessageBase> msg = new MessageScreenInitialized(this);
3000 postMessageAsync(msg); // we may be called from main thread, use async message
3001}
3002
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003003void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3004 int mode) {
3005 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3006 this);
3007 int32_t type = hw->getDisplayType();
3008 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003009
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003010 if (mode == currentMode) {
3011 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003012 return;
3013 }
3014
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 hw->setPowerMode(mode);
3016 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3017 ALOGW("Trying to set power mode for virtual display");
3018 return;
3019 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003020
Irvelffc9efc2016-07-27 15:16:37 -07003021 if (mInterceptor.isEnabled()) {
3022 Mutex::Autolock _l(mStateLock);
3023 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3024 if (idx < 0) {
3025 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3026 return;
3027 }
3028 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3029 }
3030
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003031 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003032 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003033 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003034 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3035 // FIXME: eventthread only knows about the main display right now
3036 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003037 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003041 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003042 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003043
3044 struct sched_param param = {0};
3045 param.sched_priority = 1;
3046 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3047 ALOGW("Couldn't set SCHED_FIFO on display on");
3048 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003049 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003050 // Turn off the display
3051 struct sched_param param = {0};
3052 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3053 ALOGW("Couldn't set SCHED_OTHER on display off");
3054 }
3055
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003057 disableHardwareVsync(true); // also cancels any in-progress resync
3058
Mathias Agopiancde87a32012-09-13 14:09:01 -07003059 // FIXME: eventthread only knows about the main display right now
3060 mEventThread->onScreenReleased();
3061 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003062
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003063 getHwComposer().setPowerMode(type, mode);
3064 mVisibleRegionsDirty = true;
3065 // from this point on, SF will stop drawing on this display
3066 } else {
3067 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003068 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003069}
3070
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003071void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3072 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003073 SurfaceFlinger& mFlinger;
3074 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003075 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003076 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003077 MessageSetPowerMode(SurfaceFlinger& flinger,
3078 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3079 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003080 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003081 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003082 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003083 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003084 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003085 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003086 ALOGW("Attempt to set power mode = %d for virtual display",
3087 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003088 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003089 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003090 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003091 return true;
3092 }
3093 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003094 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003095 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003096}
3097
3098// ---------------------------------------------------------------------------
3099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3101{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003103
Mathias Agopianbd115332013-04-18 16:41:04 -07003104 IPCThreadState* ipc = IPCThreadState::self();
3105 const int pid = ipc->getCallingPid();
3106 const int uid = ipc->getCallingUid();
3107 if ((uid != AID_SHELL) &&
3108 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003109 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003110 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003112 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003113 // (this would indicate SF is stuck, but we want to be able to
3114 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003115 status_t err = mStateLock.timedLock(s2ns(1));
3116 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003117 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003118 result.appendFormat(
3119 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3120 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003121 }
3122
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003123 bool dumpAll = true;
3124 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003125 size_t numArgs = args.size();
3126 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003127 if ((index < numArgs) &&
3128 (args[index] == String16("--list"))) {
3129 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003130 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003131 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003132 }
3133
3134 if ((index < numArgs) &&
3135 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003136 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003137 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003138 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003139 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003140
3141 if ((index < numArgs) &&
3142 (args[index] == String16("--latency-clear"))) {
3143 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003144 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003145 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003146 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003147
3148 if ((index < numArgs) &&
3149 (args[index] == String16("--dispsync"))) {
3150 index++;
3151 mPrimaryDispSync.dump(result);
3152 dumpAll = false;
3153 }
Dan Stozab90cf072015-03-05 11:05:59 -08003154
3155 if ((index < numArgs) &&
3156 (args[index] == String16("--static-screen"))) {
3157 index++;
3158 dumpStaticScreenStats(result);
3159 dumpAll = false;
3160 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003161
3162 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003163 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003164 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003165 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003166 dumpAll = false;
3167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003169
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003171 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003172 }
3173
Mathias Agopian9795c422009-08-26 16:36:26 -07003174 if (locked) {
3175 mStateLock.unlock();
3176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 }
3178 write(fd, result.string(), result.size());
3179 return NO_ERROR;
3180}
3181
Dan Stozac7014012014-02-14 15:03:43 -08003182void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3183 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003184{
Robert Carr2047fae2016-11-28 14:09:09 -08003185 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003187 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003188}
3189
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003190void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003191 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003192{
3193 String8 name;
3194 if (index < args.size()) {
3195 name = String8(args[index]);
3196 index++;
3197 }
3198
Dan Stoza9e56aa02015-11-02 13:00:03 -08003199 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3200 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003201 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003202
3203 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003204 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003205 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003206 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003207 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003208 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003209 }
Robert Carr2047fae2016-11-28 14:09:09 -08003210 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003211 }
3212}
3213
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003214void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003215 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003216{
3217 String8 name;
3218 if (index < args.size()) {
3219 name = String8(args[index]);
3220 index++;
3221 }
3222
Robert Carr2047fae2016-11-28 14:09:09 -08003223 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003224 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003225 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003226 }
Robert Carr2047fae2016-11-28 14:09:09 -08003227 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003228
Svetoslavd85084b2014-03-20 10:28:31 -07003229 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003230}
3231
Jamie Gennis6547ff42013-07-16 20:12:42 -07003232// This should only be called from the main thread. Otherwise it would need
3233// the lock and should use mCurrentState rather than mDrawingState.
3234void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003235 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003236 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003237 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003238
3239 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3240}
3241
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003242void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003243{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003244 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003245 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3246
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003247 if (isLayerTripleBufferingDisabled())
3248 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003249
3250 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003251 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003252 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003253 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003254 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003255}
3256
Dan Stozab90cf072015-03-05 11:05:59 -08003257void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3258{
3259 result.appendFormat("Static screen stats:\n");
3260 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3261 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3262 float percent = 100.0f *
3263 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3264 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3265 b + 1, bucketTimeSec, percent);
3266 }
3267 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3268 float percent = 100.0f *
3269 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3270 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3271 NUM_BUCKETS - 1, bucketTimeSec, percent);
3272}
3273
Dan Stozae77c7662016-05-13 11:37:28 -07003274void SurfaceFlinger::recordBufferingStats(const char* layerName,
3275 std::vector<OccupancyTracker::Segment>&& history) {
3276 Mutex::Autolock lock(mBufferingStatsMutex);
3277 auto& stats = mBufferingStats[layerName];
3278 for (const auto& segment : history) {
3279 if (!segment.usedThirdBuffer) {
3280 stats.twoBufferTime += segment.totalTime;
3281 }
3282 if (segment.occupancyAverage < 1.0f) {
3283 stats.doubleBufferedTime += segment.totalTime;
3284 } else if (segment.occupancyAverage < 2.0f) {
3285 stats.tripleBufferedTime += segment.totalTime;
3286 }
3287 ++stats.numSegments;
3288 stats.totalTime += segment.totalTime;
3289 }
3290}
3291
Brian Andersond6927fb2016-07-23 23:37:30 -07003292void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3293 result.appendFormat("Layer frame timestamps:\n");
3294
3295 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3296 const size_t count = currentLayers.size();
3297 for (size_t i=0 ; i<count ; i++) {
3298 currentLayers[i]->dumpFrameEvents(result);
3299 }
3300}
3301
Dan Stozae77c7662016-05-13 11:37:28 -07003302void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3303 result.append("Buffering stats:\n");
3304 result.append(" [Layer name] <Active time> <Two buffer> "
3305 "<Double buffered> <Triple buffered>\n");
3306 Mutex::Autolock lock(mBufferingStatsMutex);
3307 typedef std::tuple<std::string, float, float, float> BufferTuple;
3308 std::map<float, BufferTuple, std::greater<float>> sorted;
3309 for (const auto& statsPair : mBufferingStats) {
3310 const char* name = statsPair.first.c_str();
3311 const BufferingStats& stats = statsPair.second;
3312 if (stats.numSegments == 0) {
3313 continue;
3314 }
3315 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3316 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3317 stats.totalTime;
3318 float doubleBufferRatio = static_cast<float>(
3319 stats.doubleBufferedTime) / stats.totalTime;
3320 float tripleBufferRatio = static_cast<float>(
3321 stats.tripleBufferedTime) / stats.totalTime;
3322 sorted.insert({activeTime, {name, twoBufferRatio,
3323 doubleBufferRatio, tripleBufferRatio}});
3324 }
3325 for (const auto& sortedPair : sorted) {
3326 float activeTime = sortedPair.first;
3327 const BufferTuple& values = sortedPair.second;
3328 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3329 std::get<0>(values).c_str(), activeTime,
3330 std::get<1>(values), std::get<2>(values),
3331 std::get<3>(values));
3332 }
3333 result.append("\n");
3334}
3335
3336
Mathias Agopian74d211a2013-04-22 16:55:35 +02003337void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3338 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003339{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003340 bool colorize = false;
3341 if (index < args.size()
3342 && (args[index] == String16("--color"))) {
3343 colorize = true;
3344 index++;
3345 }
3346
3347 Colorizer colorizer(colorize);
3348
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003349 // figure out if we're stuck somewhere
3350 const nsecs_t now = systemTime();
3351 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3352 const nsecs_t inTransaction(mDebugInTransaction);
3353 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3354 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3355
3356 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003357 * Dump library configuration.
3358 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003359
3360 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003361 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003363 appendSfConfigString(result);
3364 appendUiConfigString(result);
3365 appendGuiConfigString(result);
3366 result.append("\n");
3367
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003368 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003369 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003371 result.append(SyncFeatures::getInstance().toString());
3372 result.append("\n");
3373
Dan Stoza9e56aa02015-11-02 13:00:03 -08003374 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3375
Andy McFadden41d67d72014-04-25 16:58:34 -07003376 colorizer.bold(result);
3377 result.append("DispSync configuration: ");
3378 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003379 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003380 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003381 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003382 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003383 result.append("\n");
3384
Dan Stozab90cf072015-03-05 11:05:59 -08003385 // Dump static screen stats
3386 result.append("\n");
3387 dumpStaticScreenStats(result);
3388 result.append("\n");
3389
Dan Stozae77c7662016-05-13 11:37:28 -07003390 dumpBufferingStats(result);
3391
Andy McFadden4803b742012-09-24 19:07:20 -07003392 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003393 * Dump the visible layer list
3394 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003395 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003396 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003398 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003399 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003400 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003401
3402 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003403 * Dump Display state
3404 */
3405
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003406 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003407 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003408 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3410 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003411 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003412 }
3413
3414 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003415 * Dump SurfaceFlinger global state
3416 */
3417
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003418 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003420 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421
Mathias Agopian888c8222012-08-04 21:10:38 -07003422 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003423 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003424
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003425 colorizer.bold(result);
3426 result.appendFormat("EGL implementation : %s\n",
3427 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3428 colorizer.reset(result);
3429 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003430 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003431
Mathias Agopian875d8e12013-06-07 15:35:48 -07003432 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003433
Mathias Agopian42977342012-08-05 00:40:46 -07003434 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003435 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3436 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003437 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438 " last eglSwapBuffers() time: %f us\n"
3439 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003440 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003441 " refresh-rate : %f fps\n"
3442 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003443 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003444 " gpu_to_cpu_unsupported : %d\n"
3445 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003446 mLastSwapBufferTime/1000.0,
3447 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003448 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003449 1e9 / activeConfig->getVsyncPeriod(),
3450 activeConfig->getDpiX(),
3451 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003452 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003453
Mathias Agopian74d211a2013-04-22 16:55:35 +02003454 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003455 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456
Mathias Agopian74d211a2013-04-22 16:55:35 +02003457 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459
3460 /*
3461 * VSYNC state
3462 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003463 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003464 result.append("\n");
3465
3466 /*
3467 * HWC layer minidump
3468 */
3469 for (size_t d = 0; d < mDisplays.size(); d++) {
3470 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3471 int32_t hwcId = displayDevice->getHwcDisplayId();
3472 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3473 continue;
3474 }
3475
3476 result.appendFormat("Display %d HWC layers:\n", hwcId);
3477 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003479 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 });
Dan Stozae22aec72016-08-01 13:20:59 -07003481 result.append("\n");
3482 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003483
3484 /*
3485 * Dump HWComposer state
3486 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003487 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003488 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003489 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003490 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003491 result.appendFormat(" h/w composer %s\n",
3492 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003493 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003494
3495 /*
3496 * Dump gralloc state
3497 */
3498 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3499 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003500}
3501
Mathias Agopian13127d82013-03-05 17:47:11 -08003502const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003503SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003504 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003505 wp<IBinder> dpy;
3506 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3507 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3508 dpy = mDisplays.keyAt(i);
3509 break;
3510 }
3511 }
3512 if (dpy == NULL) {
3513 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3514 // Just use the primary display so we have something to return
3515 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3516 }
3517 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003518}
3519
Keun young Park63f165f2012-08-31 10:53:36 -07003520bool SurfaceFlinger::startDdmConnection()
3521{
3522 void* libddmconnection_dso =
3523 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3524 if (!libddmconnection_dso) {
3525 return false;
3526 }
3527 void (*DdmConnection_start)(const char* name);
3528 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003529 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003530 if (!DdmConnection_start) {
3531 dlclose(libddmconnection_dso);
3532 return false;
3533 }
3534 (*DdmConnection_start)(getServiceName());
3535 return true;
3536}
3537
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003538status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003539 switch (code) {
3540 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003541 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003543 case CLEAR_ANIMATION_FRAME_STATS:
3544 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003545 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003546 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 {
3548 // codes that require permission check
3549 IPCThreadState* ipc = IPCThreadState::self();
3550 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003551 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003552 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003553 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003554 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003555 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003557 break;
3558 }
Robert Carr1db73f62016-12-21 12:58:51 -08003559 /*
3560 * Calling setTransactionState is safe, because you need to have been
3561 * granted a reference to Client* and Handle* to do anything with it.
3562 *
3563 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3564 */
3565 case SET_TRANSACTION_STATE:
3566 case CREATE_SCOPED_CONNECTION:
3567 {
3568 return OK;
3569 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003570 case CAPTURE_SCREEN:
3571 {
3572 // codes that require permission check
3573 IPCThreadState* ipc = IPCThreadState::self();
3574 const int pid = ipc->getCallingPid();
3575 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003576 if ((uid != AID_GRAPHICS) &&
3577 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003578 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003579 return PERMISSION_DENIED;
3580 }
3581 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 }
3583 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003584 return OK;
3585}
3586
3587status_t SurfaceFlinger::onTransact(
3588 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3589{
3590 status_t credentialCheck = CheckTransactCodeCredentials(code);
3591 if (credentialCheck != OK) {
3592 return credentialCheck;
3593 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003594
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3596 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003597 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003598 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003599 IPCThreadState* ipc = IPCThreadState::self();
3600 const int pid = ipc->getCallingPid();
3601 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003602 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003603 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 return PERMISSION_DENIED;
3605 }
3606 int n;
3607 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003608 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003609 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 return NO_ERROR;
3611 case 1002: // SHOW_UPDATES
3612 n = data.readInt32();
3613 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003614 invalidateHwcGeometry();
3615 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003618 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003619 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003620 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003621 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003622 setTransactionFlags(
3623 eTransactionNeeded|
3624 eDisplayTransactionNeeded|
3625 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003626 return NO_ERROR;
3627 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003628 case 1006:{ // send empty update
3629 signalRefresh();
3630 return NO_ERROR;
3631 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003632 case 1008: // toggle use of hw composer
3633 n = data.readInt32();
3634 mDebugDisableHWC = n ? 1 : 0;
3635 invalidateHwcGeometry();
3636 repaintEverything();
3637 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003638 case 1009: // toggle use of transform hint
3639 n = data.readInt32();
3640 mDebugDisableTransformHint = n ? 1 : 0;
3641 invalidateHwcGeometry();
3642 repaintEverything();
3643 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003645 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 reply->writeInt32(0);
3647 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003648 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003649 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 return NO_ERROR;
3651 case 1013: {
3652 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003653 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3654 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003655 return NO_ERROR;
3656 }
3657 case 1014: {
3658 // daltonize
3659 n = data.readInt32();
3660 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003661 case 1:
3662 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3663 break;
3664 case 2:
3665 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3666 break;
3667 case 3:
3668 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3669 break;
3670 default:
3671 mDaltonizer.setType(ColorBlindnessType::None);
3672 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003673 }
3674 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003675 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003676 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003677 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003678 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003679 invalidateHwcGeometry();
3680 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003681 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003683 case 1015: {
3684 // apply a color matrix
3685 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003686 if (n) {
3687 // color matrix is sent as mat3 matrix followed by vec3
3688 // offset, then packed into a mat4 where the last row is
3689 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003690 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003691 for (size_t j = 0; j < 4; j++) {
3692 mColorMatrix[i][j] = data.readFloat();
3693 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003694 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003695 } else {
3696 mColorMatrix = mat4();
3697 }
3698 invalidateHwcGeometry();
3699 repaintEverything();
3700 return NO_ERROR;
3701 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003702 // This is an experimental interface
3703 // Needs to be shifted to proper binder interface when we productize
3704 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003705 n = data.readInt32();
3706 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003707 return NO_ERROR;
3708 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003709 case 1017: {
3710 n = data.readInt32();
3711 mForceFullDamage = static_cast<bool>(n);
3712 return NO_ERROR;
3713 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003714 case 1018: { // Modify Choreographer's phase offset
3715 n = data.readInt32();
3716 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3717 return NO_ERROR;
3718 }
3719 case 1019: { // Modify SurfaceFlinger's phase offset
3720 n = data.readInt32();
3721 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3722 return NO_ERROR;
3723 }
Irvel468051e2016-06-13 16:44:44 -07003724 case 1020: { // Layer updates interceptor
3725 n = data.readInt32();
3726 if (n) {
3727 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003728 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003729 }
3730 else{
3731 ALOGV("Interceptor disabled");
3732 mInterceptor.disable();
3733 }
3734 return NO_ERROR;
3735 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003736 case 1021: { // Disable HWC virtual displays
3737 n = data.readInt32();
3738 mUseHwcVirtualDisplays = !n;
3739 return NO_ERROR;
3740 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741 }
3742 }
3743 return err;
3744}
3745
Mathias Agopian53331da2011-08-22 21:44:41 -07003746void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003747 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003748 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003749}
3750
Mathias Agopian59119e62010-10-11 12:37:43 -07003751// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003752// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003753// ---------------------------------------------------------------------------
3754
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003755/* The code below is here to handle b/8734824
3756 *
3757 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003758 * from the surfaceflinger thread to the calling binder thread, where they
3759 * are executed. This allows the calling thread in the calling process to be
3760 * reused and not depend on having "enough" binder threads to handle the
3761 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003762 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003763class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003764 /* Parts of GraphicProducerWrapper are run on two different threads,
3765 * communicating by sending messages via Looper but also by shared member
3766 * data. Coherence maintenance is subtle and in places implicit (ugh).
3767 *
3768 * Don't rely on Looper's sendMessage/handleMessage providing
3769 * release/acquire semantics for any data not actually in the Message.
3770 * Data going from surfaceflinger to binder threads needs to be
3771 * synchronized explicitly.
3772 *
3773 * Barrier open/wait do provide release/acquire semantics. This provides
3774 * implicit synchronization for data coming back from binder to
3775 * surfaceflinger threads.
3776 */
3777
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003778 sp<IGraphicBufferProducer> impl;
3779 sp<Looper> looper;
3780 status_t result;
3781 bool exitPending;
3782 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003783 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003784 uint32_t code;
3785 Parcel const* data;
3786 Parcel* reply;
3787
3788 enum {
3789 MSG_API_CALL,
3790 MSG_EXIT
3791 };
3792
3793 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003794 * Called on surfaceflinger thread. This is called by our "fake"
3795 * BpGraphicBufferProducer. We package the data and reply Parcel and
3796 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 */
3798 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003799 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003800 this->code = code;
3801 this->data = &data;
3802 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003803 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003804 // if we've exited, we run the message synchronously right here.
3805 // note (JH): as far as I can tell from looking at the code, this
3806 // never actually happens. if it does, i'm not sure if it happens
3807 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003808 handleMessage(Message(MSG_API_CALL));
3809 } else {
3810 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003811 // Prevent stores to this->{code, data, reply} from being
3812 // reordered later than the construction of Message.
3813 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 looper->sendMessage(this, Message(MSG_API_CALL));
3815 barrier.wait();
3816 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003817 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003818 }
3819
3820 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003821 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 * call the real BpGraphicBufferProducer.
3823 */
3824 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003825 int what = message.what;
3826 // Prevent reads below from happening before the read from Message
3827 atomic_thread_fence(memory_order_acquire);
3828 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003829 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003830 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003831 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003832 exitRequested = true;
3833 }
3834 }
3835
3836public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003837 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003838 : impl(impl),
3839 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003840 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003841 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003842 exitRequested(false),
3843 code(0),
3844 data(NULL),
3845 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003846 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003847
Jesse Hallb154c422014-07-13 12:47:02 -07003848 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849 status_t waitForResponse() {
3850 do {
3851 looper->pollOnce(-1);
3852 } while (!exitRequested);
3853 return result;
3854 }
3855
Jesse Hallb154c422014-07-13 12:47:02 -07003856 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003857 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003858 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003859 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003860 // Ensure this->result is visible to the binder thread before it
3861 // handles the message.
3862 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003863 looper->sendMessage(this, Message(MSG_EXIT));
3864 }
3865};
3866
3867
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003868status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3869 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003870 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003871 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003872 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003873
3874 if (CC_UNLIKELY(display == 0))
3875 return BAD_VALUE;
3876
3877 if (CC_UNLIKELY(producer == 0))
3878 return BAD_VALUE;
3879
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003880 // if we have secure windows on this display, never allow the screen capture
3881 // unless the producer interface is local (i.e.: we can take a screenshot for
3882 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003883 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003884
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003885 // Convert to surfaceflinger's internal rotation type.
3886 Transform::orientation_flags rotationFlags;
3887 switch (rotation) {
3888 case ISurfaceComposer::eRotateNone:
3889 rotationFlags = Transform::ROT_0;
3890 break;
3891 case ISurfaceComposer::eRotate90:
3892 rotationFlags = Transform::ROT_90;
3893 break;
3894 case ISurfaceComposer::eRotate180:
3895 rotationFlags = Transform::ROT_180;
3896 break;
3897 case ISurfaceComposer::eRotate270:
3898 rotationFlags = Transform::ROT_270;
3899 break;
3900 default:
3901 rotationFlags = Transform::ROT_0;
3902 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3903 break;
3904 }
3905
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003906 class MessageCaptureScreen : public MessageBase {
3907 SurfaceFlinger* flinger;
3908 sp<IBinder> display;
3909 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003910 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003911 uint32_t reqWidth, reqHeight;
3912 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003913 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003914 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003915 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003916 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003917 public:
3918 MessageCaptureScreen(SurfaceFlinger* flinger,
3919 const sp<IBinder>& display,
3920 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003921 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003922 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003923 bool useIdentityTransform,
3924 Transform::orientation_flags rotation,
3925 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003927 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003929 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003930 rotation(rotation), result(PERMISSION_DENIED),
3931 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003932 {
3933 }
3934 status_t getResult() const {
3935 return result;
3936 }
3937 virtual bool handler() {
3938 Mutex::Autolock _l(flinger->mStateLock);
3939 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003940 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003941 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003942 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003943 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003944 return true;
3945 }
3946 };
3947
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003948 // this creates a "fake" BBinder which will serve as a "fake" remote
3949 // binder to receive the marshaled calls and forward them to the
3950 // real remote (a BpGraphicBufferProducer)
3951 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3952
3953 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3954 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003955 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003956 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003957 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003958 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003959
3960 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003961 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003962 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003963 }
3964 return res;
3965}
3966
Mathias Agopian180f10d2013-04-10 22:55:41 -07003967
3968void SurfaceFlinger::renderScreenImplLocked(
3969 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003970 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003971 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003972 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003973{
3974 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003975 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976
3977 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003978 const int32_t hw_w = hw->getWidth();
3979 const int32_t hw_h = hw->getHeight();
3980 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003981 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003982
Dan Stozac1879002014-05-22 15:59:05 -07003983 // if a default or invalid sourceCrop is passed in, set reasonable values
3984 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3985 !sourceCrop.isValid()) {
3986 sourceCrop.setLeftTop(Point(0, 0));
3987 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3988 }
3989
3990 // ensure that sourceCrop is inside screen
3991 if (sourceCrop.left < 0) {
3992 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3993 }
Dan Stozabe31f442014-06-11 11:20:54 -07003994 if (sourceCrop.right > hw_w) {
3995 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003996 }
3997 if (sourceCrop.top < 0) {
3998 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3999 }
Dan Stozabe31f442014-06-11 11:20:54 -07004000 if (sourceCrop.bottom > hw_h) {
4001 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004002 }
4003
Mathias Agopian180f10d2013-04-10 22:55:41 -07004004 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004005 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004006
4007 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004008 engine.setViewportAndProjection(
4009 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004010 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004011
4012 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004013 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004014
Robert Carr1f0a16a2016-10-24 16:27:39 -07004015 // We loop through the first level of layers without traversing,
4016 // as we need to interpret min/max layer Z in the top level Z space.
4017 for (const auto& layer : mDrawingState.layersSortedByZ) {
4018 if (layer->getLayerStack() != hw->getLayerStack()) {
4019 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004020 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004021 const Layer::State& state(layer->getDrawingState());
4022 if (state.z < minLayerZ || state.z > maxLayerZ) {
4023 continue;
4024 }
4025 layer->traverseInZOrder([&](Layer* layer) {
4026 if (!layer->isVisible()) {
4027 return;
4028 }
4029 if (filtering) layer->setFiltering(true);
4030 layer->draw(hw, useIdentityTransform);
4031 if (filtering) layer->setFiltering(false);
4032 });
4033 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004034
Mathias Agopian931bda12013-08-28 18:11:46 -07004035 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004036}
4037
4038
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004039status_t SurfaceFlinger::captureScreenImplLocked(
4040 const sp<const DisplayDevice>& hw,
4041 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004042 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004043 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004044 bool useIdentityTransform, Transform::orientation_flags rotation,
4045 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004046{
4047 ATRACE_CALL();
4048
Mathias Agopian180f10d2013-04-10 22:55:41 -07004049 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004050 uint32_t hw_w = hw->getWidth();
4051 uint32_t hw_h = hw->getHeight();
4052
4053 if (rotation & Transform::ROT_90) {
4054 std::swap(hw_w, hw_h);
4055 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004056
Mathias Agopian180f10d2013-04-10 22:55:41 -07004057 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4058 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4059 reqWidth, reqHeight, hw_w, hw_h);
4060 return BAD_VALUE;
4061 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004062
Mathias Agopian180f10d2013-04-10 22:55:41 -07004063 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4064 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4065
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004066 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004067 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004068 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004069 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4070 (state.z < minLayerZ || state.z > maxLayerZ)) {
4071 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004072 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004073 layer->traverseInZOrder([&](Layer *layer) {
4074 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4075 layer->isSecure());
4076 });
4077 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004078
4079 if (!isLocalScreenshot && secureLayerIsVisible) {
4080 ALOGW("FB is protected: PERMISSION_DENIED");
4081 return PERMISSION_DENIED;
4082 }
4083
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004084 // create a surface (because we're a producer, and we need to
4085 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004086 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004087
4088 // Put the screenshot Surface into async mode so that
4089 // Layer::headFenceHasSignaled will always return true and we'll latch the
4090 // first buffer regardless of whether or not its acquire fence has
4091 // signaled. This is needed to avoid a race condition in the rotation
4092 // animation. See b/30209608
4093 sur->setAsyncMode(true);
4094
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004095 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004096
Michael Lentine5a16a622015-05-21 13:48:24 -07004097 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4098 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004099 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4100 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004101
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004102 int err = 0;
4103 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004104 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004105 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4106 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004107
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004108 if (err == NO_ERROR) {
4109 ANativeWindowBuffer* buffer;
4110 /* TODO: Once we have the sync framework everywhere this can use
4111 * server-side waits on the fence that dequeueBuffer returns.
4112 */
4113 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4114 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004115 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004116 // create an EGLImage from the buffer so we can later
4117 // turn it into a texture
4118 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4119 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4120 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004121 // this binds the given EGLImage as a framebuffer for the
4122 // duration of this scope.
4123 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4124 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004125 // this will in fact render into our dequeued buffer
4126 // via an FBO, which means we didn't have to create
4127 // an EGLSurface and therefore we're not
4128 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004129 renderScreenImplLocked(
4130 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4131 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004132
Riley Andrews86639902014-08-15 12:27:24 -07004133 // Attempt to create a sync khr object that can produce a sync point. If that
4134 // isn't available, create a non-dupable sync object in the fallback path and
4135 // wait on it directly.
4136 EGLSyncKHR sync;
4137 if (!DEBUG_SCREENSHOTS) {
4138 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004139 // native fence fd will not be populated until flush() is done.
4140 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004141 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004142 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004143 }
Riley Andrews86639902014-08-15 12:27:24 -07004144 if (sync != EGL_NO_SYNC_KHR) {
4145 // get the sync fd
4146 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4147 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4148 ALOGW("captureScreen: failed to dup sync khr object");
4149 syncFd = -1;
4150 }
4151 eglDestroySyncKHR(mEGLDisplay, sync);
4152 } else {
4153 // fallback path
4154 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4155 if (sync != EGL_NO_SYNC_KHR) {
4156 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4157 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4158 EGLint eglErr = eglGetError();
4159 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4160 ALOGW("captureScreen: fence wait timed out");
4161 } else {
4162 ALOGW_IF(eglErr != EGL_SUCCESS,
4163 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4164 }
4165 eglDestroySyncKHR(mEGLDisplay, sync);
4166 } else {
4167 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4168 }
4169 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004170 if (DEBUG_SCREENSHOTS) {
4171 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4172 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4173 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4174 hw, minLayerZ, maxLayerZ);
4175 delete [] pixels;
4176 }
4177
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004178 } else {
4179 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4180 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004181 window->cancelBuffer(window, buffer, syncFd);
4182 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004183 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004184 // destroy our image
4185 eglDestroyImageKHR(mEGLDisplay, image);
4186 } else {
4187 result = BAD_VALUE;
4188 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004189 if (buffer) {
4190 // queueBuffer takes ownership of syncFd
4191 result = window->queueBuffer(window, buffer, syncFd);
4192 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004193 }
4194 } else {
4195 result = BAD_VALUE;
4196 }
4197 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4198 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004199
Mathias Agopian74c40c02010-09-29 13:02:36 -07004200 return result;
4201}
4202
Mathias Agopiand5556842013-09-19 17:08:37 -07004203void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004204 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004205 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004206 for (size_t y=0 ; y<h ; y++) {
4207 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4208 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004209 if (p[x] != 0xFF000000) return;
4210 }
4211 }
4212 ALOGE("*** we just took a black screenshot ***\n"
4213 "requested minz=%d, maxz=%d, layerStack=%d",
4214 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004215
Robert Carr2047fae2016-11-28 14:09:09 -08004216 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004217 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004218 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004219 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4220 state.z <= maxLayerZ) {
4221 layer->traverseInZOrder([&](Layer* layer) {
4222 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4223 layer->isVisible() ? '+' : '-',
4224 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004225 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004226 i++;
4227 });
4228 }
4229 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004230 }
4231}
4232
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004233// ---------------------------------------------------------------------------
4234
Robert Carr2047fae2016-11-28 14:09:09 -08004235void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4236 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004237}
4238
Robert Carr2047fae2016-11-28 14:09:09 -08004239void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4240 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004241}
4242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004244
4245
4246#if defined(__gl_h_)
4247#error "don't include gl/gl.h in this file"
4248#endif
4249
4250#if defined(__gl2_h_)
4251#error "don't include gl2/gl2.h in this file"
4252#endif