blob: ad3b3406e2ee016a7d3614ba191758860307dc4d [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"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080076#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
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),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800139 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700141 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700142 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700143 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700144 mDebugInSwapBuffers(0),
145 mLastSwapBufferTime(0),
146 mDebugInTransaction(0),
147 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700148 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700149 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800150 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000151 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700152 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700153 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800154 mHasColorMatrix(false),
155 mHasPoweredOff(false),
156 mFrameBuckets(),
157 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700158 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800159 mNumLayers(0)
160#ifdef USE_HWC2
161 ,mEnterVrMode(false)
162#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187 // debugging stuff...
188 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700189
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800190 // TODO (urbanus): remove once b/35319396 is fixed.
191 property_get("ro.boot.vr", value, "0");
192 mVrModeSupported = atoi(value);
193
Mathias Agopianb4b17302013-03-20 18:36:41 -0700194 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700195 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 property_get("debug.sf.showupdates", value, "0");
198 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200 property_get("debug.sf.ddms", value, "0");
201 mDebugDDMS = atoi(value);
202 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700203 if (!startDdmConnection()) {
204 // start failed, and DDMS debugging not enabled
205 mDebugDDMS = 0;
206 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700208 ALOGI_IF(mDebugRegion, "showupdates enabled");
209 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700210
211 property_get("debug.sf.disable_backpressure", value, "0");
212 mPropagateBackpressure = !atoi(value);
213 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700214
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800215 property_get("debug.sf.enable_hwc_vds", value, "0");
216 mUseHwcVirtualDisplays = atoi(value);
217 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800218
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800219 property_get("ro.sf.disable_triple_buffer", value, "1");
220 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800221 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222}
223
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224void SurfaceFlinger::onFirstRef()
225{
226 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800227}
228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229SurfaceFlinger::~SurfaceFlinger()
230{
Mathias Agopiana4912602012-07-12 14:25:33 -0700231 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
232 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
233 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800234
235 if (mVrStateCallbacks.get()) {
236 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
237 defaultServiceManager()->checkService(String16("vrmanager")));
238 if (vrManagerService.get()) {
239 vrManagerService->unregisterListener(mVrStateCallbacks);
240 }
241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242}
243
Dan Stozac7014012014-02-14 15:03:43 -0800244void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245{
246 // the window manager died on us. prepare its eulogy.
247
Andy McFadden13a082e2012-08-24 10:16:42 -0700248 // restore initial conditions (default device unblank, etc)
249 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250
251 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700252 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253}
254
Robert Carr1db73f62016-12-21 12:58:51 -0800255static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700256 status_t err = client->initCheck();
257 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 }
Robert Carr1db73f62016-12-21 12:58:51 -0800260 return nullptr;
261}
262
263sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
264 return initClient(new Client(this));
265}
266
267sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
268 const sp<IGraphicBufferProducer>& gbp) {
269 if (authenticateSurfaceTexture(gbp) == false) {
270 return nullptr;
271 }
272 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
273 if (layer == nullptr) {
274 return nullptr;
275 }
276
277 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700280sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
281 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700282{
283 class DisplayToken : public BBinder {
284 sp<SurfaceFlinger> flinger;
285 virtual ~DisplayToken() {
286 // no more references, this display must be terminated
287 Mutex::Autolock _l(flinger->mStateLock);
288 flinger->mCurrentState.displays.removeItem(this);
289 flinger->setTransactionFlags(eDisplayTransactionNeeded);
290 }
291 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700292 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293 : flinger(flinger) {
294 }
295 };
296
297 sp<BBinder> token = new DisplayToken(this);
298
299 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700300 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700301 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700303 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700304 return token;
305}
306
Jesse Hall6c913be2013-08-08 12:15:49 -0700307void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
308 Mutex::Autolock _l(mStateLock);
309
310 ssize_t idx = mCurrentState.displays.indexOfKey(display);
311 if (idx < 0) {
312 ALOGW("destroyDisplay: invalid display token");
313 return;
314 }
315
316 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
317 if (!info.isVirtualDisplay()) {
318 ALOGE("destroyDisplay called for non-virtual display");
319 return;
320 }
Irvelffc9efc2016-07-27 15:16:37 -0700321 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700322 mCurrentState.displays.removeItemsAt(idx);
323 setTransactionFlags(eDisplayTransactionNeeded);
324}
325
Jesse Hall692c7232012-11-08 15:41:56 -0800326void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800327 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800328 ALOGW_IF(mBuiltinDisplays[type],
329 "Overwriting display token for display type %d", type);
330 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800331 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700332 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800333 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700334 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800335}
336
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700338 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
340 return NULL;
341 }
Jesse Hall692c7232012-11-08 15:41:56 -0800342 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343}
344
Romain Guyf8b4ca52017-03-16 18:39:20 +0000345sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
346{
347 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
348 return gba;
349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351void SurfaceFlinger::bootFinished()
352{
Wei Wangb254fa32017-01-31 17:43:23 -0800353 if (mStartBootAnimThread->join() != NO_ERROR) {
354 ALOGE("Join StartBootAnimThread failed!");
355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 const nsecs_t now = systemTime();
357 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000358 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700359 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700360
361 // wait patiently for the window manager death
362 const String16 name("window");
363 sp<IBinder> window(defaultServiceManager()->getService(name));
364 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700365 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700366 }
367
368 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700369 // formerly we would just kill the process, but we now ask it to exit so it
370 // can choose where to stop the animation.
371 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700372
373 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
374 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
375 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800376
377 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
378 defaultServiceManager()->checkService(String16("vrmanager")));
379 if (vrManagerService.get()) {
380 mVrStateCallbacks = new VrStateCallbacks(*this);
381 vrManagerService->registerListener(mVrStateCallbacks);
382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian3f844832013-08-07 21:24:32 -0700385void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 RenderEngine& engine;
388 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
391 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 }
393 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700394 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 return true;
396 }
397 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700399}
400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401class DispSyncSource : public VSyncSource, private DispSync::Callback {
402public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700403 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 const char* name) :
405 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700406 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700407 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
409 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700410 mDispSync(dispSync),
411 mCallbackMutex(),
412 mCallback(),
413 mVsyncMutex(),
414 mPhaseOffset(phaseOffset),
415 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700416
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 virtual ~DispSyncSource() {}
418
419 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000422 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error registering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 } else {
430 status_t err = mDispSync->removeEventListener(
431 static_cast<DispSync::Callback*>(this));
432 if (err != NO_ERROR) {
433 ALOGE("error unregistering vsync callback: %s (%d)",
434 strerror(-err), err);
435 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 }
440
441 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 mCallback = callback;
444 }
445
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 virtual void setPhaseOffset(nsecs_t phaseOffset) {
447 Mutex::Autolock lock(mVsyncMutex);
448
449 // Normalize phaseOffset to [0, period)
450 auto period = mDispSync->getPeriod();
451 phaseOffset %= period;
452 if (phaseOffset < 0) {
453 // If we're here, then phaseOffset is in (-period, 0). After this
454 // operation, it will be in (0, period)
455 phaseOffset += period;
456 }
457 mPhaseOffset = phaseOffset;
458
459 // If we're not enabled, we don't need to mess with the listeners
460 if (!mEnabled) {
461 return;
462 }
463
464 // Remove the listener with the old offset
465 status_t err = mDispSync->removeEventListener(
466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error unregistering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471
472 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
479 }
480
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481private:
482 virtual void onDispSyncEvent(nsecs_t when) {
483 sp<VSyncSource::Callback> callback;
484 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 callback = mCallback;
487
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 if (mTraceVsync) {
489 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700490 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492 }
493
494 if (callback != NULL) {
495 callback->onVSyncEvent(when);
496 }
497 }
498
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 const char* const mName;
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 int mValue;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700504 const String8 mVsyncOnLabel;
505 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508
509 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511
512 Mutex mVsyncMutex; // Protects the following
513 nsecs_t mPhaseOffset;
514 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515};
516
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700517class InjectVSyncSource : public VSyncSource {
518public:
519 InjectVSyncSource() {}
520
521 virtual ~InjectVSyncSource() {}
522
523 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback = callback;
526 }
527
528 virtual void onInjectSyncEvent(nsecs_t when) {
529 std::lock_guard<std::mutex> lock(mCallbackMutex);
530 mCallback->onVSyncEvent(when);
531 }
532
533 virtual void setVSyncEnabled(bool) {}
534 virtual void setPhaseOffset(nsecs_t) {}
535
536private:
537 std::mutex mCallbackMutex; // Protects the following
538 sp<VSyncSource::Callback> mCallback;
539};
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700542 ALOGI( "SurfaceFlinger's main thread ready to run. "
543 "Initializing graphics H/W...");
544
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900545 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 { // Autolock scope
548 Mutex::Autolock _l(mStateLock);
549
550 // initialize EGL for the default display
551 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
552 eglInitialize(mEGLDisplay, NULL, NULL);
553
554 // start the EventThread
555 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
556 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700557 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
559 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700560 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 mEventQueue.setEventThread(mSFEventThread);
562
Tim Murrayacff43d2016-07-29 13:57:24 -0700563 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700564 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700565 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700566 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
567 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
568 }
569
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 // Get a RenderEngine for the given display / config (can't fail)
571 mRenderEngine = RenderEngine::create(mEGLDisplay,
572 HAL_PIXEL_FORMAT_RGBA_8888);
573 }
574
575 // Drop the state lock while we initialize the hardware composer. We drop
576 // the lock because on creation, it will call back into SurfaceFlinger to
577 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800578 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800579 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800580 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
582
Jesse Hall692c7232012-11-08 15:41:56 -0800583 Mutex::Autolock _l(mStateLock);
584
Mathias Agopian875d8e12013-06-07 15:35:48 -0700585 // retrieve the EGL context that was selected/created
586 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700587
Mathias Agopianda27af92012-09-13 18:17:13 -0700588 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
589 "couldn't create EGLContext");
590
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591 // make the GLContext current so that we can create textures when creating
592 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700593 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
594
Jamie Gennisd1700752013-10-14 12:22:52 -0700595 mEventControlThread = new EventControlThread(this);
596 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
597
Mathias Agopian92a979a2012-08-02 18:32:23 -0700598 // initialize our drawing state
599 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700600
Andy McFadden13a082e2012-08-24 10:16:42 -0700601 // set initial conditions (e.g. unblank default device)
602 initializeDisplays();
603
Dan Stoza4e637772016-07-28 13:31:51 -0700604 mRenderEngine->primeCache();
605
Wei Wangb254fa32017-01-31 17:43:23 -0800606 mStartBootAnimThread = new StartBootAnimThread();
607 if (mStartBootAnimThread->Start() != NO_ERROR) {
608 ALOGE("Run StartBootAnimThread failed!");
609 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800610
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700612}
613
Mathias Agopiana67e4182012-06-19 17:26:12 -0700614void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800615 // Start boot animation service by setting a property mailbox
616 // if property setting thread is already running, Start() will be just a NOP
617 mStartBootAnimThread->Start();
618 // Wait until property was set
619 if (mStartBootAnimThread->join() != NO_ERROR) {
620 ALOGE("Join StartBootAnimThread failed!");
621 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700622}
623
Mathias Agopian875d8e12013-06-07 15:35:48 -0700624size_t SurfaceFlinger::getMaxTextureSize() const {
625 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700626}
627
Mathias Agopian875d8e12013-06-07 15:35:48 -0700628size_t SurfaceFlinger::getMaxViewportDims() const {
629 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700630}
631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800632// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800633
Jamie Gennis582270d2011-08-17 18:19:00 -0700634bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800635 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800636 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800637 return authenticateSurfaceTextureLocked(bufferProducer);
638}
639
640bool SurfaceFlinger::authenticateSurfaceTextureLocked(
641 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800642 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700643 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800644}
645
Brian Anderson069b3652016-07-22 10:32:47 -0700646status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700647 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700648 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700649 FrameEvent::REQUESTED_PRESENT,
650 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700651 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700652 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700653 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700654 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700655 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700656 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700657 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700658 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700659 };
660 return NO_ERROR;
661}
662
Dan Stoza7f7da322014-05-02 15:26:25 -0700663status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
664 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700665 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700666 return BAD_VALUE;
667 }
668
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500669 if (!display.get())
670 return NAME_NOT_FOUND;
671
Jesse Hall692c7232012-11-08 15:41:56 -0800672 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700673 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800674 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700675 type = i;
676 break;
677 }
678 }
679
680 if (type < 0) {
681 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700682 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700683
Mathias Agopian8b736f12012-08-13 17:54:26 -0700684 // TODO: Not sure if display density should handled by SF any longer
685 class Density {
686 static int getDensityFromProperty(char const* propName) {
687 char property[PROPERTY_VALUE_MAX];
688 int density = 0;
689 if (property_get(propName, property, NULL) > 0) {
690 density = atoi(property);
691 }
692 return density;
693 }
694 public:
695 static int getEmuDensity() {
696 return getDensityFromProperty("qemu.sf.lcd_density"); }
697 static int getBuildDensity() {
698 return getDensityFromProperty("ro.sf.lcd_density"); }
699 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700700
Dan Stoza7f7da322014-05-02 15:26:25 -0700701 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700702
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700704 DisplayInfo info = DisplayInfo();
705
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706 float xdpi = hwConfig->getDpiX();
707 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700708
709 if (type == DisplayDevice::DISPLAY_PRIMARY) {
710 // The density of the device is provided by a build property
711 float density = Density::getBuildDensity() / 160.0f;
712 if (density == 0) {
713 // the build doesn't provide a density -- this is wrong!
714 // use xdpi instead
715 ALOGE("ro.sf.lcd_density must be defined as a build property");
716 density = xdpi / 160.0f;
717 }
718 if (Density::getEmuDensity()) {
719 // if "qemu.sf.lcd_density" is specified, it overrides everything
720 xdpi = ydpi = density = Density::getEmuDensity();
721 density /= 160.0f;
722 }
723 info.density = density;
724
725 // TODO: this needs to go away (currently needed only by webkit)
726 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
727 info.orientation = hw->getOrientation();
728 } else {
729 // TODO: where should this value come from?
730 static const int TV_DENSITY = 213;
731 info.density = TV_DENSITY / 160.0f;
732 info.orientation = 0;
733 }
734
Dan Stoza9e56aa02015-11-02 13:00:03 -0800735 info.w = hwConfig->getWidth();
736 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 info.xdpi = xdpi;
738 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900740 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741
Andy McFadden91b2ca82014-06-13 14:04:23 -0700742 // This is how far in advance a buffer must be queued for
743 // presentation at a given time. If you want a buffer to appear
744 // on the screen at time N, you must submit the buffer before
745 // (N - presentationDeadline).
746 //
747 // Normally it's one full refresh period (to give SF a chance to
748 // latch the buffer), but this can be reduced by configuring a
749 // DispSync offset. Any additional delays introduced by the hardware
750 // composer or panel must be accounted for here.
751 //
752 // We add an additional 1ms to allow for processing time and
753 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800755 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700756
757 // All non-virtual displays are currently considered secure.
758 info.secure = true;
759
Michael Wright28f24d02016-07-12 13:30:53 -0700760 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 }
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763 return NO_ERROR;
764}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700765
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800766status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700767 DisplayStatInfo* stats) {
768 if (stats == NULL) {
769 return BAD_VALUE;
770 }
771
772 // FIXME for now we always return stats for the primary display
773 memset(stats, 0, sizeof(*stats));
774 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
775 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
776 return NO_ERROR;
777}
778
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700779int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800780 if (display == NULL) {
781 ALOGE("%s : display is NULL", __func__);
782 return BAD_VALUE;
783 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700784 sp<DisplayDevice> device(getDisplayDevice(display));
785 if (device != NULL) {
786 return device->getActiveConfig();
787 }
788 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700789}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700790
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700791void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
792 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
793 this);
794 int32_t type = hw->getDisplayType();
795 int currentMode = hw->getActiveConfig();
796
797 if (mode == currentMode) {
798 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
799 return;
800 }
801
802 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
803 ALOGW("Trying to set config for virtual display");
804 return;
805 }
806
807 hw->setActiveConfig(mode);
808 getHwComposer().setActiveConfig(type, mode);
809}
810
811status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
812 class MessageSetActiveConfig: public MessageBase {
813 SurfaceFlinger& mFlinger;
814 sp<IBinder> mDisplay;
815 int mMode;
816 public:
817 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
818 int mode) :
819 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
820 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700821 Vector<DisplayInfo> configs;
822 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700823 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700824 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700825 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700826 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700827 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700828 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
829 if (hw == NULL) {
830 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700831 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700832 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
833 ALOGW("Attempt to set active config = %d for virtual display",
834 mMode);
835 } else {
836 mFlinger.setActiveConfigInternal(hw, mMode);
837 }
838 return true;
839 }
840 };
841 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
842 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700843 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700844}
Michael Wright28f24d02016-07-12 13:30:53 -0700845status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
846 Vector<android_color_mode_t>* outColorModes) {
847 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
848 return BAD_VALUE;
849 }
850
851 if (!display.get()) {
852 return NAME_NOT_FOUND;
853 }
854
855 int32_t type = NAME_NOT_FOUND;
856 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
857 if (display == mBuiltinDisplays[i]) {
858 type = i;
859 break;
860 }
861 }
862
863 if (type < 0) {
864 return type;
865 }
866
867 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
868 outColorModes->clear();
869 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
870
871 return NO_ERROR;
872}
873
874android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
875 sp<DisplayDevice> device(getDisplayDevice(display));
876 if (device != nullptr) {
877 return device->getActiveColorMode();
878 }
879 return static_cast<android_color_mode_t>(BAD_VALUE);
880}
881
882void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
883 android_color_mode_t mode) {
884 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
885 this);
886 int32_t type = hw->getDisplayType();
887 android_color_mode_t currentMode = hw->getActiveColorMode();
888
889 if (mode == currentMode) {
890 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
891 return;
892 }
893
894 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
895 ALOGW("Trying to set config for virtual display");
896 return;
897 }
898
899 hw->setActiveColorMode(mode);
900 getHwComposer().setActiveColorMode(type, mode);
901}
902
903
904status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
905 android_color_mode_t colorMode) {
906 class MessageSetActiveColorMode: public MessageBase {
907 SurfaceFlinger& mFlinger;
908 sp<IBinder> mDisplay;
909 android_color_mode_t mMode;
910 public:
911 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
912 android_color_mode_t mode) :
913 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
914 virtual bool handler() {
915 Vector<android_color_mode_t> modes;
916 mFlinger.getDisplayColorModes(mDisplay, &modes);
917 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
918 if (mMode < 0 || !exists) {
919 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
920 mDisplay.get());
921 return true;
922 }
923 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
924 if (hw == nullptr) {
925 ALOGE("Attempt to set active color mode = %d for null display %p",
926 mMode, mDisplay.get());
927 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
928 ALOGW("Attempt to set active color mode= %d for virtual display",
929 mMode);
930 } else {
931 mFlinger.setActiveColorModeInternal(hw, mMode);
932 }
933 return true;
934 }
935 };
936 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
937 postMessageSync(msg);
938 return NO_ERROR;
939}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700940
Svetoslavd85084b2014-03-20 10:28:31 -0700941status_t SurfaceFlinger::clearAnimationFrameStats() {
942 Mutex::Autolock _l(mStateLock);
943 mAnimFrameTracker.clearStats();
944 return NO_ERROR;
945}
946
947status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
948 Mutex::Autolock _l(mStateLock);
949 mAnimFrameTracker.getStats(outStats);
950 return NO_ERROR;
951}
952
Dan Stozac4f471e2016-03-24 09:31:08 -0700953status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
954 HdrCapabilities* outCapabilities) const {
955 Mutex::Autolock _l(mStateLock);
956
957 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
958 if (displayDevice == nullptr) {
959 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
960 return BAD_VALUE;
961 }
962
963 std::unique_ptr<HdrCapabilities> capabilities =
964 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
965 if (capabilities) {
966 std::swap(*outCapabilities, *capabilities);
967 } else {
968 return BAD_VALUE;
969 }
970
971 return NO_ERROR;
972}
973
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700974status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
975 if (enable == mInjectVSyncs) {
976 return NO_ERROR;
977 }
978
979 if (enable) {
980 mInjectVSyncs = enable;
981 ALOGV("VSync Injections enabled");
982 if (mVSyncInjector.get() == nullptr) {
983 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700984 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700985 }
986 mEventQueue.setEventThread(mInjectorEventThread);
987 } else {
988 mInjectVSyncs = enable;
989 ALOGV("VSync Injections disabled");
990 mEventQueue.setEventThread(mSFEventThread);
991 mVSyncInjector.clear();
992 }
993 return NO_ERROR;
994}
995
996status_t SurfaceFlinger::injectVSync(nsecs_t when) {
997 if (!mInjectVSyncs) {
998 ALOGE("VSync Injections not enabled");
999 return BAD_VALUE;
1000 }
1001 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1002 ALOGV("Injecting VSync inside SurfaceFlinger");
1003 mVSyncInjector->onInjectSyncEvent(when);
1004 }
1005 return NO_ERROR;
1006}
1007
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001008// ----------------------------------------------------------------------------
1009
1010sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001011 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001012}
1013
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001014// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001015
1016void SurfaceFlinger::waitForEvent() {
1017 mEventQueue.waitMessage();
1018}
1019
1020void SurfaceFlinger::signalTransaction() {
1021 mEventQueue.invalidate();
1022}
1023
1024void SurfaceFlinger::signalLayerUpdate() {
1025 mEventQueue.invalidate();
1026}
1027
1028void SurfaceFlinger::signalRefresh() {
1029 mEventQueue.refresh();
1030}
1031
1032status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001033 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001034 return mEventQueue.postMessage(msg, reltime);
1035}
1036
1037status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001038 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001039 status_t res = mEventQueue.postMessage(msg, reltime);
1040 if (res == NO_ERROR) {
1041 msg->wait();
1042 }
1043 return res;
1044}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001046void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001047 do {
1048 waitForEvent();
1049 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001050}
1051
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001052void SurfaceFlinger::enableHardwareVsync() {
1053 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001054 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001056 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1057 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001058 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001059 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001060}
1061
Jesse Hall948fe0c2013-10-14 12:56:09 -07001062void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001063 Mutex::Autolock _l(mHWVsyncLock);
1064
Jesse Hall948fe0c2013-10-14 12:56:09 -07001065 if (makeAvailable) {
1066 mHWVsyncAvailable = true;
1067 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001068 // Hardware vsync is not currently available, so abort the resync
1069 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001070 return;
1071 }
1072
Dan Stoza9e56aa02015-11-02 13:00:03 -08001073 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1074 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075
1076 mPrimaryDispSync.reset();
1077 mPrimaryDispSync.setPeriod(period);
1078
1079 if (!mPrimaryHWVsyncEnabled) {
1080 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001081 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1082 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 mPrimaryHWVsyncEnabled = true;
1084 }
1085}
1086
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 Mutex::Autolock _l(mHWVsyncLock);
1089 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001090 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1091 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092 mPrimaryDispSync.endResync();
1093 mPrimaryHWVsyncEnabled = false;
1094 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001095 if (makeUnavailable) {
1096 mHWVsyncAvailable = false;
1097 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098}
1099
Tim Murray4a4e4a22016-04-19 16:29:23 +00001100void SurfaceFlinger::resyncWithRateLimit() {
1101 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1102 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001103 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001104 }
1105}
1106
Steven Thomas3cfac282017-02-06 12:29:30 -08001107void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1108 nsecs_t timestamp) {
1109 Mutex::Autolock lock(mStateLock);
1110 // Ignore any vsyncs from the non-active hardware composer.
1111 if (composer != mHwc) {
1112 return;
1113 }
1114
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116
Jamie Gennisd1700752013-10-14 12:22:52 -07001117 { // Scope for the lock
1118 Mutex::Autolock _l(mHWVsyncLock);
1119 if (type == 0 && mPrimaryHWVsyncEnabled) {
1120 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001122 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001123
1124 if (needsHwVsync) {
1125 enableHardwareVsync();
1126 } else {
1127 disableHardwareVsync(false);
1128 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001129}
1130
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001131void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1132 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1133 *compositorTiming = mCompositorTiming;
1134}
1135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1137 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1138 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1139 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001140
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 // All non-virtual displays are currently considered secure.
1142 bool isSecure = true;
1143
1144 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001145
1146 // When we're using the vr composer, the assumption is that we've
1147 // already created the IBinder object for the primary display.
1148 if (!mHwc->isUsingVrComposer()) {
1149 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1150 }
1151
Dan Stoza9e56aa02015-11-02 13:00:03 -08001152 wp<IBinder> token = mBuiltinDisplays[type];
1153
1154 sp<IGraphicBufferProducer> producer;
1155 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001156 BufferQueue::createBufferQueue(&producer, &consumer,
1157 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001158
1159 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1160 DisplayDevice::DISPLAY_PRIMARY, consumer);
1161 sp<DisplayDevice> hw = new DisplayDevice(this,
1162 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1163 producer, mRenderEngine->getEGLConfig());
1164 mDisplays.add(token, hw);
1165 } else {
1166 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001167 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001168 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001169 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001170 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001171 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1172 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001173 }
1174 setTransactionFlags(eDisplayTransactionNeeded);
1175
Andy McFadden9e9689c2012-10-10 18:17:51 -07001176 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001177 }
Mathias Agopian86303202012-07-24 22:46:10 -07001178}
1179
Steven Thomas3cfac282017-02-06 12:29:30 -08001180void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1181 Mutex::Autolock lock(mStateLock);
1182 if (composer == mHwc) {
1183 repaintEverything();
1184 } else {
1185 // This isn't from our current hardware composer. If it's a callback
1186 // from the real composer, forward the refresh request to vr
1187 // flinger. Otherwise ignore it.
1188 if (!composer->isUsingVrComposer()) {
1189 mVrFlinger->OnHardwareComposerRefresh();
1190 }
1191 }
1192}
1193
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 getHwComposer().setVsyncEnabled(disp,
1197 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001198}
1199
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001200void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1201 for (size_t i = 0; i < layers.size(); ++i) {
1202 layers[i]->clearHwcLayers();
1203 }
1204}
1205
1206void SurfaceFlinger::resetHwc() {
1207 disableHardwareVsync(true);
1208 clearHwcLayers(mDrawingState.layersSortedByZ);
1209 clearHwcLayers(mCurrentState.layersSortedByZ);
1210 // Clear the drawing state so that the logic inside of
1211 // handleTransactionLocked will fire. It will determine the delta between
1212 // mCurrentState and mDrawingState and re-apply all changes when we make the
1213 // transition.
1214 mDrawingState.displays.clear();
1215 mDisplays.clear();
1216}
1217
1218void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001219 bool enteringVrMode = mEnterVrMode;
1220 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1221 return;
1222 }
1223 if (enteringVrMode && !mVrHwc) {
1224 // Construct new HWComposer without holding any locks.
1225 mVrHwc = new HWComposer(true);
1226 ALOGV("Vr HWC created");
1227 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001228 {
1229 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001230
1231 if (enteringVrMode) {
1232 // Start vrflinger thread, if it hasn't been started already.
1233 if (!mVrFlinger) {
1234 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1235 int err = mVrFlinger->Run(mHwc->getComposer());
1236 if (err != NO_ERROR) {
1237 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1238 mVrFlinger.reset();
1239 mEnterVrMode = false;
1240 return;
1241 }
1242 }
1243
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001244 resetHwc();
1245
1246 mHwc = mVrHwc;
1247 mVrFlinger->EnterVrMode();
1248 } else {
1249 mVrFlinger->ExitVrMode();
1250
1251 resetHwc();
1252
1253 mHwc = mRealHwc;
1254 enableHardwareVsync();
1255 }
1256
1257 mVisibleRegionsDirty = true;
1258 invalidateHwcGeometry();
1259 android_atomic_or(1, &mRepaintEverything);
1260 setTransactionFlags(eDisplayTransactionNeeded);
1261 }
1262 if (mVrHwc) {
1263 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1264 }
1265}
1266
Mathias Agopian4fec8732012-06-29 14:12:52 -07001267void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001268 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001270 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001271 // TODO(eieio): Tied to a conditional until SELinux issues
1272 // are resolved.
1273 if (mVrModeSupported) {
1274 updateVrMode();
1275 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001276
Dan Stoza50182882016-07-08 12:02:20 -07001277 bool frameMissed = !mHadClientComposition &&
1278 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279 (mPreviousPresentFence->getSignalTime() ==
1280 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001281 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001282 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001283 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001284 signalLayerUpdate();
1285 break;
1286 }
1287
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 bool refreshNeeded = handleMessageTransaction();
1289 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001290 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001292 // Signal a refresh if a transaction modified the window state,
1293 // a new buffer was latched, or if HWC has requested a full
1294 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001295 signalRefresh();
1296 }
1297 break;
1298 }
1299 case MessageQueue::REFRESH: {
1300 handleMessageRefresh();
1301 break;
1302 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303 }
1304}
1305
Dan Stoza6b9454d2014-11-07 16:00:59 -08001306bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001307 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001308 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001309 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001310 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001311 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001312 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001313}
1314
Dan Stoza6b9454d2014-11-07 16:00:59 -08001315bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001316 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001317 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001318}
1319
1320void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001321 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001322
Pablo Ceballos40845df2016-01-25 17:41:15 -08001323 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001324
Brian Andersond6927fb2016-07-23 23:37:30 -07001325 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001326 rebuildLayerStacks();
1327 setUpHWComposer();
1328 doDebugFlashRegions();
1329 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001330 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001331
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001332 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001333
1334 mHadClientComposition = false;
1335 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1336 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1337 mHadClientComposition = mHadClientComposition ||
1338 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1339 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001340
Dan Stoza9e56aa02015-11-02 13:00:03 -08001341 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001343
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344void SurfaceFlinger::doDebugFlashRegions()
1345{
1346 // is debugging enabled
1347 if (CC_LIKELY(!mDebugRegion))
1348 return;
1349
1350 const bool repaintEverything = mRepaintEverything;
1351 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1352 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001353 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001354 // transform the dirty region into this screen's coordinate space
1355 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1356 if (!dirtyRegion.isEmpty()) {
1357 // redraw the whole screen
1358 doComposeSurfaces(hw, Region(hw->bounds()));
1359
1360 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001361 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001362 RenderEngine& engine(getRenderEngine());
1363 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1364
Mathias Agopianda27af92012-09-13 18:17:13 -07001365 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001366 }
1367 }
1368 }
1369
1370 postFramebuffer();
1371
1372 if (mDebugRegion > 1) {
1373 usleep(mDebugRegion * 1000);
1374 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001375
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001377 auto& displayDevice = mDisplays[displayId];
1378 if (!displayDevice->isDisplayOn()) {
1379 continue;
1380 }
1381
1382 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1384 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001385 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386}
1387
Brian Andersond6927fb2016-07-23 23:37:30 -07001388void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001390 ATRACE_CALL();
1391 ALOGV("preComposition");
1392
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001394 mDrawingState.traverseInZOrder([&](Layer* layer) {
1395 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001396 needExtraInvalidate = true;
1397 }
Robert Carr2047fae2016-11-28 14:09:09 -08001398 });
1399
Mathias Agopiancd60f992012-08-16 16:28:27 -07001400 if (needExtraInvalidate) {
1401 signalLayerUpdate();
1402 }
1403}
1404
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405void SurfaceFlinger::updateCompositorTiming(
1406 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1407 std::shared_ptr<FenceTime>& presentFenceTime) {
1408 // Update queue of past composite+present times and determine the
1409 // most recently known composite to present latency.
1410 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1411 nsecs_t compositeToPresentLatency = -1;
1412 while (!mCompositePresentTimes.empty()) {
1413 CompositePresentTime& cpt = mCompositePresentTimes.front();
1414 // Cached values should have been updated before calling this method,
1415 // which helps avoid duplicate syscalls.
1416 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1417 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1418 break;
1419 }
1420 compositeToPresentLatency = displayTime - cpt.composite;
1421 mCompositePresentTimes.pop();
1422 }
1423
1424 // Don't let mCompositePresentTimes grow unbounded, just in case.
1425 while (mCompositePresentTimes.size() > 16) {
1426 mCompositePresentTimes.pop();
1427 }
1428
1429 // Integer division and modulo round toward 0 not -inf, so we need to
1430 // treat negative and positive offsets differently.
1431 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1432 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1433 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1434
1435 // 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).
1441 nsecs_t snappedCompositeToPresentLatency = -1;
1442 if (compositeToPresentLatency >= 0) {
1443 nsecs_t bias = vsyncInterval / 2;
1444 int64_t extraVsyncs =
1445 (compositeToPresentLatency - idealLatency + bias) /
1446 vsyncInterval;
1447 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1448 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1449 }
1450
1451 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1452 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1453 mCompositorTiming.interval = vsyncInterval;
1454 if (snappedCompositeToPresentLatency >= 0) {
1455 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1456 }
1457}
1458
1459void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001461 ATRACE_CALL();
1462 ALOGV("postComposition");
1463
Brian Anderson3546a3f2016-07-14 11:51:14 -07001464 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001465 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001466 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001467 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001468 }
1469
Brian Andersond6927fb2016-07-23 23:37:30 -07001470 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001471
1472 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1473 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1474 glCompositionDoneFenceTime =
1475 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1476 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1477 } else {
1478 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1479 }
1480 mGlCompositionDoneTimeline.updateSignalTimes();
1481
1482 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1483 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1484 mDisplayTimeline.push(displayFenceTime);
1485 mDisplayTimeline.updateSignalTimes();
1486
1487 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1488 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1489 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1490 presentFenceTime = &displayFenceTime;
1491 } else {
1492 retireFenceTime = &displayFenceTime;
1493 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001494
1495 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1496 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1497
1498 // We use the refreshStartTime which might be sampled a little later than
1499 // when we started doing work for this frame, but that should be okay
1500 // since updateCompositorTiming has snapping logic.
1501 updateCompositorTiming(
1502 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1503
Robert Carr2047fae2016-11-28 14:09:09 -08001504 mDrawingState.traverseInZOrder([&](Layer* layer) {
1505 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001507 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001508 recordBufferingStats(layer->getName().string(),
1509 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001510 }
Robert Carr2047fae2016-11-28 14:09:09 -08001511 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001512
Brian Anderson3d4039d2016-09-23 16:31:30 -07001513 if (displayFence->isValid()) {
1514 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001515 enableHardwareVsync();
1516 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001517 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001518 }
1519 }
1520
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001521 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001522 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001523 enableHardwareVsync();
1524 }
1525 }
1526
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001527 if (mAnimCompositionPending) {
1528 mAnimCompositionPending = false;
1529
Brian Anderson3d4039d2016-09-23 16:31:30 -07001530 if (displayFenceTime->isValid()) {
1531 mAnimFrameTracker.setActualPresentFence(
1532 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001533 } else {
1534 // The HWC doesn't support present fences, so use the refresh
1535 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 nsecs_t presentTime =
1537 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001538 mAnimFrameTracker.setActualPresentTime(presentTime);
1539 }
1540 mAnimFrameTracker.advanceFrame();
1541 }
Dan Stozab90cf072015-03-05 11:05:59 -08001542
1543 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1544 return;
1545 }
1546
1547 nsecs_t currentTime = systemTime();
1548 if (mHasPoweredOff) {
1549 mHasPoweredOff = false;
1550 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001551 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001552 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001553 if (numPeriods < NUM_BUCKETS - 1) {
1554 mFrameBuckets[numPeriods] += elapsedTime;
1555 } else {
1556 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1557 }
1558 mTotalTime += elapsedTime;
1559 }
1560 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561}
1562
1563void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001564 ATRACE_CALL();
1565 ALOGV("rebuildLayerStacks");
1566
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001568 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1569 ATRACE_CALL();
1570 mVisibleRegionsDirty = false;
1571 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001572
Jeff Sharkey76488112017-02-27 14:15:18 -07001573 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1574 Region opaqueRegion;
1575 Region dirtyRegion;
1576 Vector<sp<Layer>> layersSortedByZ;
1577 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1578 const Transform& tr(displayDevice->getTransform());
1579 const Rect bounds(displayDevice->getBounds());
1580 if (displayDevice->isDisplayOn()) {
1581 computeVisibleRegions(
1582 displayDevice->getLayerStack(), dirtyRegion,
1583 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001584
Jeff Sharkey76488112017-02-27 14:15:18 -07001585 mDrawingState.traverseInZOrder([&](Layer* layer) {
1586 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1587 Region drawRegion(tr.transform(
1588 layer->visibleNonTransparentRegion));
1589 drawRegion.andSelf(bounds);
1590 if (!drawRegion.isEmpty()) {
1591 layersSortedByZ.add(layer);
1592 } else {
1593 // Clear out the HWC layer if this layer was
1594 // previously visible, but no longer is
1595 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1596 nullptr);
1597 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001598 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001599 // WM changes displayDevice->layerStack upon sleep/awake.
1600 // Here we make sure we delete the HWC layers even if
1601 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001602 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1603 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001604 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001605 });
1606 }
1607 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1608 displayDevice->undefinedRegion.set(bounds);
1609 displayDevice->undefinedRegion.subtractSelf(
1610 tr.transform(opaqueRegion));
1611 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001612 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001613 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001615
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001617 ATRACE_CALL();
1618 ALOGV("setUpHWComposer");
1619
Jesse Hall028dc8f2013-08-20 16:35:32 -07001620 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001621 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1622 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1623 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1624
1625 // If nothing has changed (!dirty), don't recompose.
1626 // If something changed, but we don't currently have any visible layers,
1627 // and didn't when we last did a composition, then skip it this time.
1628 // The second rule does two things:
1629 // - When all layers are removed from a display, we'll emit one black
1630 // frame, then nothing more until we get new layers.
1631 // - When a display is created with a private layer stack, we won't
1632 // emit any black frames until a layer is added to the layer stack.
1633 bool mustRecompose = dirty && !(empty && wasEmpty);
1634
1635 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1636 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1637 mustRecompose ? "doing" : "skipping",
1638 dirty ? "+" : "-",
1639 empty ? "+" : "-",
1640 wasEmpty ? "+" : "-");
1641
Dan Stoza71433162014-02-04 16:22:36 -08001642 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001643
1644 if (mustRecompose) {
1645 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1646 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001647 }
1648
Dan Stoza9e56aa02015-11-02 13:00:03 -08001649 // build the h/w work list
1650 if (CC_UNLIKELY(mGeometryInvalid)) {
1651 mGeometryInvalid = false;
1652 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1653 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1654 const auto hwcId = displayDevice->getHwcDisplayId();
1655 if (hwcId >= 0) {
1656 const Vector<sp<Layer>>& currentLayers(
1657 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001658 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001659 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 if (!layer->hasHwcLayer(hwcId)) {
1661 auto hwcLayer = mHwc->createLayer(hwcId);
1662 if (hwcLayer) {
1663 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1664 } else {
1665 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001667 }
1668 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001669
Robert Carrae060832016-11-28 10:51:00 -08001670 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001671 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001673 }
1674 }
1675 }
1676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677 }
Riley Andrews03414a12014-07-01 14:22:59 -07001678
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001679
1680 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1681
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 // Set the per-frame data
1683 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1684 auto& displayDevice = mDisplays[displayId];
1685 const auto hwcId = displayDevice->getHwcDisplayId();
1686 if (hwcId < 0) {
1687 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001688 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001689 if (colorMatrix != mPreviousColorMatrix) {
1690 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1691 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1692 "display %zd: %d", displayId, result);
1693 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1695 layer->setPerFrameData(displayDevice);
1696 }
1697 }
1698
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001699 mPreviousColorMatrix = colorMatrix;
1700
Dan Stoza9e56aa02015-11-02 13:00:03 -08001701 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001702 auto& displayDevice = mDisplays[displayId];
1703 if (!displayDevice->isDisplayOn()) {
1704 continue;
1705 }
1706
1707 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1709 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001710 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001712
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713void SurfaceFlinger::doComposition() {
1714 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 ALOGV("doComposition");
1716
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001717 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001718 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001719 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001720 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721 // transform the dirty region into this screen's coordinate space
1722 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001723
1724 // repaint the framebuffer (if needed)
1725 doDisplayComposition(hw, dirtyRegion);
1726
Mathias Agopiancd60f992012-08-16 16:28:27 -07001727 hw->dirtyRegion.clear();
1728 hw->flip(hw->swapRegion);
1729 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001730 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001731 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001732 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001733}
1734
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001735void SurfaceFlinger::postFramebuffer()
1736{
Mathias Agopian841cde52012-03-01 15:44:37 -08001737 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001739
Mathias Agopiana44b0412011-10-16 18:46:35 -07001740 const nsecs_t now = systemTime();
1741 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001742
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1744 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001745 if (!displayDevice->isDisplayOn()) {
1746 continue;
1747 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001748 const auto hwcId = displayDevice->getHwcDisplayId();
1749 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001750 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001751 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001752 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001753 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001754 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1755 sp<Fence> releaseFence = Fence::NO_FENCE;
1756 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1757 releaseFence = displayDevice->getClientTargetAcquireFence();
1758 } else {
1759 auto hwcLayer = layer->getHwcLayer(hwcId);
1760 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001761 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762 layer->onLayerDisplayed(releaseFence);
1763 }
1764 if (hwcId >= 0) {
1765 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001766 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001767 }
1768
Mathias Agopiana44b0412011-10-16 18:46:35 -07001769 mLastSwapBufferTime = systemTime() - now;
1770 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001771
1772 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1773 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1774 logFrameStats();
1775 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001776}
1777
Mathias Agopian87baae12012-07-31 12:38:26 -07001778void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779{
Mathias Agopian841cde52012-03-01 15:44:37 -08001780 ATRACE_CALL();
1781
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001782 // here we keep a copy of the drawing state (that is the state that's
1783 // going to be overwritten by handleTransactionLocked()) outside of
1784 // mStateLock so that the side-effects of the State assignment
1785 // don't happen with mStateLock held (which can cause deadlocks).
1786 State drawingState(mDrawingState);
1787
Mathias Agopianca4d3602011-05-19 15:38:14 -07001788 Mutex::Autolock _l(mStateLock);
1789 const nsecs_t now = systemTime();
1790 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001791
Mathias Agopianca4d3602011-05-19 15:38:14 -07001792 // Here we're guaranteed that some transaction flags are set
1793 // so we can call handleTransactionLocked() unconditionally.
1794 // We call getTransactionFlags(), which will also clear the flags,
1795 // with mStateLock held to guarantee that mCurrentState won't change
1796 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001797
Mathias Agopiane57f2922012-08-09 16:29:12 -07001798 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001799 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001800
Mathias Agopianca4d3602011-05-19 15:38:14 -07001801 mLastTransactionTime = systemTime() - now;
1802 mDebugInTransaction = 0;
1803 invalidateHwcGeometry();
1804 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001805}
1806
Mathias Agopian87baae12012-07-31 12:38:26 -07001807void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001808{
Dan Stoza7dde5992015-05-22 09:51:44 -07001809 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001810 mCurrentState.traverseInZOrder([](Layer* layer) {
1811 layer->notifyAvailableFrames();
1812 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001813
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 /*
1815 * Traversal of the children
1816 * (perform the transaction for each of them if needed)
1817 */
1818
Mathias Agopian3559b072012-08-15 13:46:03 -07001819 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001820 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001822 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001823
1824 const uint32_t flags = layer->doTransaction(0);
1825 if (flags & Layer::eVisibleRegion)
1826 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001827 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828 }
1829
1830 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001831 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001832 */
1833
Mathias Agopiane57f2922012-08-09 16:29:12 -07001834 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001835 // here we take advantage of Vector's copy-on-write semantics to
1836 // improve performance by skipping the transaction entirely when
1837 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001838 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1839 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001840 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001841 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001842 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001843 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001844
1845 // find the displays that were removed
1846 // (ie: in drawing state but not in current state)
1847 // also handle displays that changed
1848 // (ie: displays that are in both lists)
1849 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001850 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1851 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001852 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001853 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001854 // Call makeCurrent() on the primary display so we can
1855 // be sure that nothing associated with this display
1856 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001857 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001858 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001859 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1860 if (hw != NULL)
1861 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001862 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001863 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001864 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001865 } else {
1866 ALOGW("trying to remove the main display");
1867 }
1868 } else {
1869 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001870 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001871 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001872 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1873 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001874 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001875 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001876 // recreating the DisplayDevice, so we just remove it
1877 // from the drawing state, so that it get re-added
1878 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001879 sp<DisplayDevice> hw(getDisplayDevice(display));
1880 if (hw != NULL)
1881 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001882 mDisplays.removeItem(display);
1883 mDrawingState.displays.removeItemsAt(i);
1884 dc--; i--;
1885 // at this point we must loop to the next item
1886 continue;
1887 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001888
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001889 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001890 if (disp != NULL) {
1891 if (state.layerStack != draw[i].layerStack) {
1892 disp->setLayerStack(state.layerStack);
1893 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001894 if ((state.orientation != draw[i].orientation)
1895 || (state.viewport != draw[i].viewport)
1896 || (state.frame != draw[i].frame))
1897 {
1898 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001899 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001900 }
Michael Lentine47e45402014-07-18 15:34:25 -07001901 if (state.width != draw[i].width || state.height != draw[i].height) {
1902 disp->setDisplaySize(state.width, state.height);
1903 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001904 }
1905 }
1906 }
1907
1908 // find displays that were added
1909 // (ie: in current state but not in drawing state)
1910 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001911 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001912 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001913
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001914 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001915 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001916 sp<IGraphicBufferProducer> bqProducer;
1917 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001918 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1919 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001920
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001922 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001923 // Virtual displays without a surface are dormant:
1924 // they have external state (layer stack, projection,
1925 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001926 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001927
Dan Stoza8cf150a2016-08-02 10:27:31 -07001928 if (mUseHwcVirtualDisplays) {
1929 int width = 0;
1930 int status = state.surface->query(
1931 NATIVE_WINDOW_WIDTH, &width);
1932 ALOGE_IF(status != NO_ERROR,
1933 "Unable to query width (%d)", status);
1934 int height = 0;
1935 status = state.surface->query(
1936 NATIVE_WINDOW_HEIGHT, &height);
1937 ALOGE_IF(status != NO_ERROR,
1938 "Unable to query height (%d)", status);
1939 int intFormat = 0;
1940 status = state.surface->query(
1941 NATIVE_WINDOW_FORMAT, &intFormat);
1942 ALOGE_IF(status != NO_ERROR,
1943 "Unable to query format (%d)", status);
1944 auto format = static_cast<android_pixel_format_t>(
1945 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001946
Dan Stoza8cf150a2016-08-02 10:27:31 -07001947 mHwc->allocateVirtualDisplay(width, height, &format,
1948 &hwcId);
1949 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950
Dan Stoza5cf424b2016-05-20 14:02:39 -07001951 // TODO: Plumb requested format back up to consumer
1952
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 sp<VirtualDisplaySurface> vds =
1954 new VirtualDisplaySurface(*mHwc,
1955 hwcId, state.surface, bqProducer,
1956 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001957
1958 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001959 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001960 }
1961 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001962 ALOGE_IF(state.surface!=NULL,
1963 "adding a supported display, but rendering "
1964 "surface is provided (%p), ignoring it",
1965 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001966
1967 hwcId = state.type;
1968 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1969 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001970 }
1971
1972 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001973 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001974 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 state.type, hwcId, state.isSecure, display,
1976 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001977 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001978 hw->setLayerStack(state.layerStack);
1979 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001980 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001981 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001982 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001984 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001985 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001986 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001987 }
1988 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001990 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001991
Mathias Agopian84300952012-11-21 16:02:13 -08001992 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1993 // The transform hint might have changed for some layers
1994 // (either because a display has changed, or because a layer
1995 // as changed).
1996 //
1997 // Walk through all the layers in currentLayers,
1998 // and update their transform hint.
1999 //
2000 // If a layer is visible only on a single display, then that
2001 // display is used to calculate the hint, otherwise we use the
2002 // default display.
2003 //
2004 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2005 // the hint is set before we acquire a buffer from the surface texture.
2006 //
2007 // NOTE: layer transactions have taken place already, so we use their
2008 // drawing state. However, SurfaceFlinger's own transaction has not
2009 // happened yet, so we must use the current state layer list
2010 // (soon to become the drawing state list).
2011 //
2012 sp<const DisplayDevice> disp;
2013 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002014 bool first = true;
2015 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002016 // NOTE: we rely on the fact that layers are sorted by
2017 // layerStack first (so we don't have to traverse the list
2018 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002019 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002020 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002021 currentlayerStack = layerStack;
2022 // figure out if this layerstack is mirrored
2023 // (more than one display) if so, pick the default display,
2024 // if not, pick the only display it's on.
2025 disp.clear();
2026 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2027 sp<const DisplayDevice> hw(mDisplays[dpy]);
2028 if (hw->getLayerStack() == currentlayerStack) {
2029 if (disp == NULL) {
2030 disp = hw;
2031 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002032 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002033 break;
2034 }
2035 }
2036 }
2037 }
Chet Haase91d25932013-04-11 15:24:55 -07002038 if (disp == NULL) {
2039 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2040 // redraw after transform hint changes. See bug 8508397.
2041
2042 // could be null when this layer is using a layerStack
2043 // that is not visible on any display. Also can occur at
2044 // screen off/on times.
2045 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002046 }
Chet Haase91d25932013-04-11 15:24:55 -07002047 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002048
2049 first = false;
2050 });
Mathias Agopian84300952012-11-21 16:02:13 -08002051 }
2052
2053
Mathias Agopian3559b072012-08-15 13:46:03 -07002054 /*
2055 * Perform our own transaction if needed
2056 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002057
2058 if (mLayersAdded) {
2059 mLayersAdded = false;
2060 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002061 mVisibleRegionsDirty = true;
2062 }
2063
2064 // some layers might have been removed, so
2065 // we need to update the regions they're exposing.
2066 if (mLayersRemoved) {
2067 mLayersRemoved = false;
2068 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002069 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002070 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002071 // this layer is not visible anymore
2072 // TODO: we could traverse the tree from front to back and
2073 // compute the actual visible region
2074 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002075 Region visibleReg;
2076 visibleReg.set(layer->computeScreenBounds());
2077 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002078 }
Robert Carr2047fae2016-11-28 14:09:09 -08002079 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002080 }
2081
2082 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002083
2084 updateCursorAsync();
2085}
2086
2087void SurfaceFlinger::updateCursorAsync()
2088{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2090 auto& displayDevice = mDisplays[displayId];
2091 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002092 continue;
2093 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094
2095 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2096 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002097 }
2098 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002099}
2100
2101void SurfaceFlinger::commitTransaction()
2102{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002103 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002104 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002105 for (const auto& l : mLayersPendingRemoval) {
2106 recordBufferingStats(l->getName().string(),
2107 l->getOccupancyHistory(true));
2108 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002109 }
2110 mLayersPendingRemoval.clear();
2111 }
2112
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 // If this transaction is part of a window animation then the next frame
2114 // we composite should be considered an animation as well.
2115 mAnimCompositionPending = mAnimTransactionPending;
2116
Mathias Agopian4fec8732012-06-29 14:12:52 -07002117 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002118 mDrawingState.traverseInZOrder([](Layer* layer) {
2119 layer->commitChildList();
2120 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002121 mTransactionPending = false;
2122 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002123 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124}
2125
Robert Carr2047fae2016-11-28 14:09:09 -08002126void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002127 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128{
Mathias Agopian841cde52012-03-01 15:44:37 -08002129 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132 Region aboveOpaqueLayers;
2133 Region aboveCoveredLayers;
2134 Region dirty;
2135
Mathias Agopian87baae12012-07-31 12:38:26 -07002136 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137
Robert Carr2047fae2016-11-28 14:09:09 -08002138 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002140 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002141
Jesse Hall01e29052013-02-19 16:13:35 -08002142 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002143 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002144 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002145
Mathias Agopianab028732010-03-16 16:41:46 -07002146 /*
2147 * opaqueRegion: area of a surface that is fully opaque.
2148 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002150
2151 /*
2152 * visibleRegion: area of a surface that is visible on screen
2153 * and not fully transparent. This is essentially the layer's
2154 * footprint minus the opaque regions above it.
2155 * Areas covered by a translucent surface are considered visible.
2156 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002158
2159 /*
2160 * coveredRegion: area of a surface that is covered by all
2161 * visible regions above it (which includes the translucent areas).
2162 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002164
Jesse Halla8026d22012-09-25 13:25:04 -07002165 /*
2166 * transparentRegion: area of a surface that is hinted to be completely
2167 * transparent. This is only used to tell when the layer has no visible
2168 * non-transparent regions and can be removed from the layer list. It
2169 * does not affect the visibleRegion of this layer or any layers
2170 * beneath it. The hint may not be correct if apps don't respect the
2171 * SurfaceView restrictions (which, sadly, some don't).
2172 */
2173 Region transparentRegion;
2174
Mathias Agopianab028732010-03-16 16:41:46 -07002175
2176 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002177 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002178 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002179 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002181 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002182 if (!visibleRegion.isEmpty()) {
2183 // Remove the transparent area from the visible region
2184 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002185 if (tr.preserveRects()) {
2186 // transform the transparent region
2187 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002188 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002189 // transformation too complex, can't do the
2190 // transparent region optimization.
2191 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002192 }
Mathias Agopianab028732010-03-16 16:41:46 -07002193 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194
Mathias Agopianab028732010-03-16 16:41:46 -07002195 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002196 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002198 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2199 // the opaque region is the layer's footprint
2200 opaqueRegion = visibleRegion;
2201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202 }
2203 }
2204
Mathias Agopianab028732010-03-16 16:41:46 -07002205 // Clip the covered region to the visible region
2206 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2207
2208 // Update aboveCoveredLayers for next (lower) layer
2209 aboveCoveredLayers.orSelf(visibleRegion);
2210
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002211 // subtract the opaque region covered by the layers above us
2212 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213
2214 // compute this layer's dirty region
2215 if (layer->contentDirty) {
2216 // we need to invalidate the whole region
2217 dirty = visibleRegion;
2218 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002219 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220 layer->contentDirty = false;
2221 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002222 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002223 * the exposed region consists of two components:
2224 * 1) what's VISIBLE now and was COVERED before
2225 * 2) what's EXPOSED now less what was EXPOSED before
2226 *
2227 * note that (1) is conservative, we start with the whole
2228 * visible region but only keep what used to be covered by
2229 * something -- which mean it may have been exposed.
2230 *
2231 * (2) handles areas that were not covered by anything but got
2232 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002233 */
Mathias Agopianab028732010-03-16 16:41:46 -07002234 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002235 const Region oldVisibleRegion = layer->visibleRegion;
2236 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002237 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2238 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239 }
2240 dirty.subtractSelf(aboveOpaqueLayers);
2241
2242 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002243 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244
Mathias Agopianab028732010-03-16 16:41:46 -07002245 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002247
Jesse Halla8026d22012-09-25 13:25:04 -07002248 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002249 layer->setVisibleRegion(visibleRegion);
2250 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002251 layer->setVisibleNonTransparentRegion(
2252 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002253 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Mathias Agopian87baae12012-07-31 12:38:26 -07002255 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256}
2257
Mathias Agopian87baae12012-07-31 12:38:26 -07002258void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2259 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002260 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002261 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2262 if (hw->getLayerStack() == layerStack) {
2263 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002264 }
2265 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002266}
2267
Dan Stoza6b9454d2014-11-07 16:00:59 -08002268bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 ALOGV("handlePageFlip");
2271
Brian Andersond6927fb2016-07-23 23:37:30 -07002272 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002273
Mathias Agopian4fec8732012-06-29 14:12:52 -07002274 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002275 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002276
2277 // Store the set of layers that need updates. This set must not change as
2278 // buffers are being latched, as this could result in a deadlock.
2279 // Example: Two producers share the same command stream and:
2280 // 1.) Layer 0 is latched
2281 // 2.) Layer 0 gets a new frame
2282 // 2.) Layer 1 gets a new frame
2283 // 3.) Layer 1 is latched.
2284 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2285 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002286 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002287 if (layer->hasQueuedFrame()) {
2288 frameQueued = true;
2289 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002290 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002291 } else {
2292 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002293 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002294 } else {
2295 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002296 }
Robert Carr2047fae2016-11-28 14:09:09 -08002297 });
2298
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002300 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002301 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002302 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002303 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002304
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002305 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002306
2307 // If we will need to wake up at some time in the future to deal with a
2308 // queued frame that shouldn't be displayed during this vsync period, wake
2309 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002310 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002311 signalLayerUpdate();
2312 }
2313
2314 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002315 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316}
2317
Mathias Agopianad456f92011-01-13 17:53:01 -08002318void SurfaceFlinger::invalidateHwcGeometry()
2319{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002320 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002321}
2322
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002323
Fabien Sanglard830b8472016-11-30 16:35:58 -08002324void SurfaceFlinger::doDisplayComposition(
2325 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002326 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327{
Dan Stoza71433162014-02-04 16:22:36 -08002328 // We only need to actually compose the display if:
2329 // 1) It is being handled by hardware composer, which may need this to
2330 // keep its virtual display state machine in sync, or
2331 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002333 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002334 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002335 return;
2336 }
2337
Dan Stoza9e56aa02015-11-02 13:00:03 -08002338 ALOGV("doDisplayComposition");
2339
Mathias Agopian87baae12012-07-31 12:38:26 -07002340 Region dirtyRegion(inDirtyRegion);
2341
Mathias Agopianb8a55602009-06-26 19:06:36 -07002342 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002343 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
Fabien Sanglard830b8472016-11-30 16:35:58 -08002345 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002346 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002347 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2348 // takes a rectangle, we must make sure to update that whole
2349 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002350 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002351 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002352 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002353 // We need to redraw the rectangle that will be updated
2354 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002355 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002356 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002358 } else {
2359 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002360 dirtyRegion.set(displayDevice->bounds());
2361 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362 }
2363 }
2364
Fabien Sanglard830b8472016-11-30 16:35:58 -08002365 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002367 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002368 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002369
2370 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002371 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372}
2373
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374bool SurfaceFlinger::doComposeSurfaces(
2375 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002376{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002377 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002378
Dan Stoza9e56aa02015-11-02 13:00:03 -08002379 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002380
2381 mat4 oldColorMatrix;
2382 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2383 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2384 if (applyColorMatrix) {
2385 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2386 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2387 }
2388
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2390 if (hasClientComposition) {
2391 ALOGV("hasClientComposition");
2392
2393 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002394 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002395 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002396 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2397 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2398 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2399 }
2400 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002401 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002403 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2405 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002406 // when using overlays, we assume a fully transparent framebuffer
2407 // NOTE: we could reduce how much we need to clear, for instance
2408 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002409 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002410 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002412 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002413 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002415
2416 // we remove the scissor part
2417 // we're left with the letterbox region
2418 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002420
2421 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002423
2424 // but limit it to the dirty region
2425 region.andSelf(dirty);
2426
Mathias Agopianb9494d52012-04-18 02:28:45 -07002427 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002428 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002429 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002430 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002431 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002432 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002433
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002435 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002436 // scissor on the main display. It should never be needed
2437 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 const Rect& bounds(displayDevice->getBounds());
2439 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002440 if (scissor != bounds) {
2441 // scissor doesn't match the screen's dimensions, so we
2442 // need to clear everything outside of it and enable
2443 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002444
Mathias Agopianf45c5102012-10-24 16:29:17 -07002445 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 const uint32_t height = displayDevice->getHeight();
2447 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002448 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002449 }
2450 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002451 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002452
Mathias Agopian85d751c2012-08-29 16:59:24 -07002453 /*
2454 * and then, render the layers targeted at the framebuffer
2455 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002456
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 ALOGV("Rendering client layers");
2458 const Transform& displayTransform = displayDevice->getTransform();
2459 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002460 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 bool firstLayer = true;
2462 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2463 const Region clip(dirty.intersect(
2464 displayTransform.transform(layer->visibleRegion)));
2465 ALOGV("Layer: %s", layer->getName().string());
2466 ALOGV(" Composition type: %s",
2467 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002468 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 switch (layer->getCompositionType(hwcId)) {
2470 case HWC2::Composition::Cursor:
2471 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002472 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002474 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2476 layer->isOpaque(state) && (state.alpha == 1.0f)
2477 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002478 // never clear the very first layer since we're
2479 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002480 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002481 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002482 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002483 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 case HWC2::Composition::Client: {
2485 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002486 break;
2487 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002489 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002490 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 } else {
2492 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002493 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002495 }
2496 } else {
2497 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002499 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002501 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002502 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002503 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002504 }
2505 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002506
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002507 if (applyColorMatrix) {
2508 getRenderEngine().setupColorTransform(oldColorMatrix);
2509 }
2510
Mathias Agopianf45c5102012-10-24 16:29:17 -07002511 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002513 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514}
2515
Fabien Sanglard830b8472016-11-30 16:35:58 -08002516void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2517 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002518 RenderEngine& engine(getRenderEngine());
2519 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520}
2521
Dan Stoza7d89d062015-04-30 13:29:25 -07002522status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002523 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002524 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525 const sp<Layer>& lbc,
2526 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002527{
Dan Stoza7d89d062015-04-30 13:29:25 -07002528 // add this layer to the current state list
2529 {
2530 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002531 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002532 return NO_MEMORY;
2533 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 if (parent == nullptr) {
2535 mCurrentState.layersSortedByZ.add(lbc);
2536 } else {
2537 parent->addChild(lbc);
2538 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002539 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 mLayersAdded = true;
2541 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002542 }
2543
Mathias Agopian96f08192010-06-02 23:28:45 -07002544 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002545 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002546
Dan Stoza7d89d062015-04-30 13:29:25 -07002547 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002548}
2549
Robert Carr9524cb32017-02-13 11:32:32 -08002550status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002551 Mutex::Autolock _l(mStateLock);
2552
Robert Carr1f0a16a2016-10-24 16:27:39 -07002553 const auto& p = layer->getParent();
2554 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2555 mCurrentState.layersSortedByZ.remove(layer);
2556
Robert Carr136e2f62017-02-08 17:54:29 -08002557 // As a matter of normal operation, the LayerCleaner will produce a second
2558 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2559 // so we will succeed in promoting it, but it's already been removed
2560 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2561 // otherwise something has gone wrong and we are leaking the layer.
2562 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002563 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2564 layer->getName().string(),
2565 (p != nullptr) ? p->getName().string() : "no-parent");
2566 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002567 } else if (index < 0) {
2568 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002569 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570
2571 mLayersPendingRemoval.add(layer);
2572 mLayersRemoved = true;
2573 mNumLayers--;
2574 setTransactionFlags(eTransactionNeeded);
2575 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576}
2577
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002578uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002579 return android_atomic_release_load(&mTransactionFlags);
2580}
2581
Mathias Agopian3f844832013-08-07 21:24:32 -07002582uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2584}
2585
Mathias Agopian3f844832013-08-07 21:24:32 -07002586uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2588 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002589 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
2591 return old;
2592}
2593
Mathias Agopian8b33f032012-07-24 20:43:54 -07002594void SurfaceFlinger::setTransactionState(
2595 const Vector<ComposerState>& state,
2596 const Vector<DisplayState>& displays,
2597 uint32_t flags)
2598{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002599 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002600 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002601 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002602
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002603 if (flags & eAnimation) {
2604 // For window updates that are part of an animation we must wait for
2605 // previous animation "frames" to be handled.
2606 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002607 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002608 if (CC_UNLIKELY(err != NO_ERROR)) {
2609 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002610 // caller after a few seconds.
2611 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2612 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002613 mAnimTransactionPending = false;
2614 break;
2615 }
2616 }
2617 }
2618
Mathias Agopiane57f2922012-08-09 16:29:12 -07002619 size_t count = displays.size();
2620 for (size_t i=0 ; i<count ; i++) {
2621 const DisplayState& s(displays[i]);
2622 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002623 }
2624
Mathias Agopiane57f2922012-08-09 16:29:12 -07002625 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002626 for (size_t i=0 ; i<count ; i++) {
2627 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002628 // Here we need to check that the interface we're given is indeed
2629 // one of our own. A malicious client could give us a NULL
2630 // IInterface, or one of its own or even one of our own but a
2631 // different type. All these situations would cause us to crash.
2632 //
2633 // NOTE: it would be better to use RTTI as we could directly check
2634 // that we have a Client*. however, RTTI is disabled in Android.
2635 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002636 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002637 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002638 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002639 sp<Client> client( static_cast<Client *>(s.client.get()) );
2640 transactionFlags |= setClientStateLocked(client, s.state);
2641 }
2642 }
2643 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002644 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002645
Robert Carr2a7dbb42016-05-24 11:41:28 -07002646 // If a synchronous transaction is explicitly requested without any changes,
2647 // force a transaction anyway. This can be used as a flush mechanism for
2648 // previous async transactions.
2649 if (transactionFlags == 0 && (flags & eSynchronous)) {
2650 transactionFlags = eTransactionNeeded;
2651 }
2652
Mathias Agopian386aa982011-11-07 21:58:03 -08002653 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002654 if (mInterceptor.isEnabled()) {
2655 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2656 }
Irvel468051e2016-06-13 16:44:44 -07002657
Mathias Agopian386aa982011-11-07 21:58:03 -08002658 // this triggers the transaction
2659 setTransactionFlags(transactionFlags);
2660
2661 // if this is a synchronous transaction, wait for it to take effect
2662 // before returning.
2663 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002664 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002665 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002666 if (flags & eAnimation) {
2667 mAnimTransactionPending = true;
2668 }
2669 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002670 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2671 if (CC_UNLIKELY(err != NO_ERROR)) {
2672 // just in case something goes wrong in SF, return to the
2673 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002674 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2675 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002676 break;
2677 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 }
2680}
2681
Mathias Agopiane57f2922012-08-09 16:29:12 -07002682uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2683{
Jesse Hall9a143922012-10-04 16:29:19 -07002684 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2685 if (dpyIdx < 0)
2686 return 0;
2687
Mathias Agopiane57f2922012-08-09 16:29:12 -07002688 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002689 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002690 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002691 const uint32_t what = s.what;
2692 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002693 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002694 disp.surface = s.surface;
2695 flags |= eDisplayTransactionNeeded;
2696 }
2697 }
2698 if (what & DisplayState::eLayerStackChanged) {
2699 if (disp.layerStack != s.layerStack) {
2700 disp.layerStack = s.layerStack;
2701 flags |= eDisplayTransactionNeeded;
2702 }
2703 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002704 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002705 if (disp.orientation != s.orientation) {
2706 disp.orientation = s.orientation;
2707 flags |= eDisplayTransactionNeeded;
2708 }
2709 if (disp.frame != s.frame) {
2710 disp.frame = s.frame;
2711 flags |= eDisplayTransactionNeeded;
2712 }
2713 if (disp.viewport != s.viewport) {
2714 disp.viewport = s.viewport;
2715 flags |= eDisplayTransactionNeeded;
2716 }
2717 }
Michael Lentine47e45402014-07-18 15:34:25 -07002718 if (what & DisplayState::eDisplaySizeChanged) {
2719 if (disp.width != s.width) {
2720 disp.width = s.width;
2721 flags |= eDisplayTransactionNeeded;
2722 }
2723 if (disp.height != s.height) {
2724 disp.height = s.height;
2725 flags |= eDisplayTransactionNeeded;
2726 }
2727 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002728 }
2729 return flags;
2730}
2731
2732uint32_t SurfaceFlinger::setClientStateLocked(
2733 const sp<Client>& client,
2734 const layer_state_t& s)
2735{
2736 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002737 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 if (layer != 0) {
2739 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002740 bool geometryAppliesWithResize =
2741 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002742 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002743 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002744 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002745 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002746 }
2747 if (what & layer_state_t::eLayerChanged) {
2748 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002749 const auto& p = layer->getParent();
2750 if (p == nullptr) {
2751 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2752 if (layer->setLayer(s.z) && idx >= 0) {
2753 mCurrentState.layersSortedByZ.removeAt(idx);
2754 mCurrentState.layersSortedByZ.add(layer);
2755 // we need traversal (state changed)
2756 // AND transaction (list changed)
2757 flags |= eTransactionNeeded|eTraversalNeeded;
2758 }
2759 } else {
2760 if (p->setChildLayer(layer, s.z)) {
2761 flags |= eTransactionNeeded|eTraversalNeeded;
2762 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 }
2764 }
2765 if (what & layer_state_t::eSizeChanged) {
2766 if (layer->setSize(s.w, s.h)) {
2767 flags |= eTraversalNeeded;
2768 }
2769 }
2770 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002772 flags |= eTraversalNeeded;
2773 }
2774 if (what & layer_state_t::eMatrixChanged) {
2775 if (layer->setMatrix(s.matrix))
2776 flags |= eTraversalNeeded;
2777 }
2778 if (what & layer_state_t::eTransparentRegionChanged) {
2779 if (layer->setTransparentRegionHint(s.transparentRegion))
2780 flags |= eTraversalNeeded;
2781 }
Dan Stoza23116082015-06-18 14:58:39 -07002782 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002783 if (layer->setFlags(s.flags, s.mask))
2784 flags |= eTraversalNeeded;
2785 }
2786 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002787 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002788 flags |= eTraversalNeeded;
2789 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002790 if (what & layer_state_t::eFinalCropChanged) {
2791 if (layer->setFinalCrop(s.finalCrop))
2792 flags |= eTraversalNeeded;
2793 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002795 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796 // We only allow setting layer stacks for top level layers,
2797 // everything else inherits layer stack from its parent.
2798 if (layer->hasParent()) {
2799 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2800 layer->getName().string());
2801 } else if (idx < 0) {
2802 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2803 "that also does not appear in the top level layer list. Something"
2804 " has gone wrong.", layer->getName().string());
2805 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002806 mCurrentState.layersSortedByZ.removeAt(idx);
2807 mCurrentState.layersSortedByZ.add(layer);
2808 // we need traversal (state changed)
2809 // AND transaction (list changed)
2810 flags |= eTransactionNeeded|eTraversalNeeded;
2811 }
2812 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002813 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002814 if (s.barrierHandle != nullptr) {
2815 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2816 } else if (s.barrierGbp != nullptr) {
2817 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2818 if (authenticateSurfaceTextureLocked(gbp)) {
2819 const auto& otherLayer =
2820 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2821 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2822 } else {
2823 ALOGE("Attempt to defer transaction to to an"
2824 " unrecognized GraphicBufferProducer");
2825 }
2826 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002827 // We don't trigger a traversal here because if no other state is
2828 // changed, we don't want this to cause any more work
2829 }
Robert Carr1db73f62016-12-21 12:58:51 -08002830 if (what & layer_state_t::eReparentChildren) {
2831 if (layer->reparentChildren(s.reparentHandle)) {
2832 flags |= eTransactionNeeded|eTraversalNeeded;
2833 }
2834 }
Robert Carr9524cb32017-02-13 11:32:32 -08002835 if (what & layer_state_t::eDetachChildren) {
2836 layer->detachChildren();
2837 }
Robert Carrc3574f72016-03-24 12:19:32 -07002838 if (what & layer_state_t::eOverrideScalingModeChanged) {
2839 layer->setOverrideScalingMode(s.overrideScalingMode);
2840 // We don't trigger a traversal here because if no other state is
2841 // changed, we don't want this to cause any more work
2842 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002843 }
2844 return flags;
2845}
2846
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002847status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002848 const String8& name,
2849 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002850 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002851 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2852 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002854 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002855 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002856 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002857 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002858 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002859
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002860 status_t result = NO_ERROR;
2861
2862 sp<Layer> layer;
2863
Mathias Agopian3165cc22012-08-08 19:42:09 -07002864 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2865 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002866 result = createNormalLayer(client,
2867 name, w, h, flags, format,
2868 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002870 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002871 result = createDimLayer(client,
2872 name, w, h, flags,
2873 handle, gbp, &layer);
2874 break;
2875 default:
2876 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 break;
2878 }
2879
Dan Stoza7d89d062015-04-30 13:29:25 -07002880 if (result != NO_ERROR) {
2881 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002883
Albert Chaulk479c60c2017-01-27 14:21:34 -05002884 layer->setInfo(windowType, ownerUid);
2885
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002887 if (result != NO_ERROR) {
2888 return result;
2889 }
Irvelffc9efc2016-07-27 15:16:37 -07002890 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002891
2892 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894}
2895
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002896status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2897 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2898 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899{
2900 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002901 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902 case PIXEL_FORMAT_TRANSPARENT:
2903 case PIXEL_FORMAT_TRANSLUCENT:
2904 format = PIXEL_FORMAT_RGBA_8888;
2905 break;
2906 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002907 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 break;
2909 }
2910
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002911 *outLayer = new Layer(this, client, name, w, h, flags);
2912 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2913 if (err == NO_ERROR) {
2914 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002915 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002917
2918 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2919 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920}
2921
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002922status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2923 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2924 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002926 *outLayer = new LayerDim(this, client, name, w, h, flags);
2927 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002928 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002929 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002930}
2931
Mathias Agopianac9fa422013-02-11 16:40:36 -08002932status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933{
Robert Carr9524cb32017-02-13 11:32:32 -08002934 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002935 status_t err = NO_ERROR;
2936 sp<Layer> l(client->getLayerUser(handle));
2937 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002938 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002939 err = removeLayer(l);
2940 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2941 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002942 }
2943 return err;
2944}
2945
Mathias Agopian13127d82013-03-05 17:47:11 -08002946status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002947{
Mathias Agopian67106042013-03-14 19:18:13 -07002948 // called by ~LayerCleaner() when all references to the IBinder (handle)
2949 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002950 sp<Layer> l = layer.promote();
2951 if (l == nullptr) {
2952 // The layer has already been removed, carry on
2953 return NO_ERROR;
2954 } if (l->getParent() != nullptr) {
2955 // If we have a parent, then we can continue to live as long as it does.
2956 return NO_ERROR;
2957 }
2958 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959}
2960
Mathias Agopianb60314a2012-04-10 22:09:54 -07002961// ---------------------------------------------------------------------------
2962
Andy McFadden13a082e2012-08-24 10:16:42 -07002963void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002964 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002965 Vector<ComposerState> state;
2966 Vector<DisplayState> displays;
2967 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002968 d.what = DisplayState::eDisplayProjectionChanged |
2969 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002970 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002971 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002972 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002973 d.frame.makeInvalid();
2974 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002975 d.width = 0;
2976 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002977 displays.add(d);
2978 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002979 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002980
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2982 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002983 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002984
2985 {
2986 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2987 mCompositorTiming.interval = period;
2988 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002989}
2990
2991void SurfaceFlinger::initializeDisplays() {
2992 class MessageScreenInitialized : public MessageBase {
2993 SurfaceFlinger* flinger;
2994 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002995 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002996 virtual bool handler() {
2997 flinger->onInitializeDisplays();
2998 return true;
2999 }
3000 };
3001 sp<MessageBase> msg = new MessageScreenInitialized(this);
3002 postMessageAsync(msg); // we may be called from main thread, use async message
3003}
3004
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003005void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3006 int mode) {
3007 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3008 this);
3009 int32_t type = hw->getDisplayType();
3010 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003011
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003012 if (mode == currentMode) {
3013 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003014 return;
3015 }
3016
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003017 hw->setPowerMode(mode);
3018 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3019 ALOGW("Trying to set power mode for virtual display");
3020 return;
3021 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003022
Irvelffc9efc2016-07-27 15:16:37 -07003023 if (mInterceptor.isEnabled()) {
3024 Mutex::Autolock _l(mStateLock);
3025 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3026 if (idx < 0) {
3027 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3028 return;
3029 }
3030 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3031 }
3032
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003033 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003034 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003035 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003036 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3037 // FIXME: eventthread only knows about the main display right now
3038 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003039 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003042 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003043 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003045
3046 struct sched_param param = {0};
3047 param.sched_priority = 1;
3048 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3049 ALOGW("Couldn't set SCHED_FIFO on display on");
3050 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003052 // Turn off the display
3053 struct sched_param param = {0};
3054 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3055 ALOGW("Couldn't set SCHED_OTHER on display off");
3056 }
3057
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003058 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003059 disableHardwareVsync(true); // also cancels any in-progress resync
3060
Mathias Agopiancde87a32012-09-13 14:09:01 -07003061 // FIXME: eventthread only knows about the main display right now
3062 mEventThread->onScreenReleased();
3063 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003064
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003065 getHwComposer().setPowerMode(type, mode);
3066 mVisibleRegionsDirty = true;
3067 // from this point on, SF will stop drawing on this display
3068 } else {
3069 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003070 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003071}
3072
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003073void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3074 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003075 SurfaceFlinger& mFlinger;
3076 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003077 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003078 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003079 MessageSetPowerMode(SurfaceFlinger& flinger,
3080 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3081 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003082 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003083 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003084 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003085 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003086 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003087 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088 ALOGW("Attempt to set power mode = %d for virtual display",
3089 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003090 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003091 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003092 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003093 return true;
3094 }
3095 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003096 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003097 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003098}
3099
3100// ---------------------------------------------------------------------------
3101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3103{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003105
Mathias Agopianbd115332013-04-18 16:41:04 -07003106 IPCThreadState* ipc = IPCThreadState::self();
3107 const int pid = ipc->getCallingPid();
3108 const int uid = ipc->getCallingUid();
3109 if ((uid != AID_SHELL) &&
3110 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003111 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003112 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003114 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003115 // (this would indicate SF is stuck, but we want to be able to
3116 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003117 status_t err = mStateLock.timedLock(s2ns(1));
3118 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003119 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003120 result.appendFormat(
3121 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3122 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003123 }
3124
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125 bool dumpAll = true;
3126 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003127 size_t numArgs = args.size();
3128 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003129 if ((index < numArgs) &&
3130 (args[index] == String16("--list"))) {
3131 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003132 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003133 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003134 }
3135
3136 if ((index < numArgs) &&
3137 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003138 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003139 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003140 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003141 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003142
3143 if ((index < numArgs) &&
3144 (args[index] == String16("--latency-clear"))) {
3145 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003146 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003147 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003148 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003149
3150 if ((index < numArgs) &&
3151 (args[index] == String16("--dispsync"))) {
3152 index++;
3153 mPrimaryDispSync.dump(result);
3154 dumpAll = false;
3155 }
Dan Stozab90cf072015-03-05 11:05:59 -08003156
3157 if ((index < numArgs) &&
3158 (args[index] == String16("--static-screen"))) {
3159 index++;
3160 dumpStaticScreenStats(result);
3161 dumpAll = false;
3162 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003163
3164 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003165 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003166 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003167 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003168 dumpAll = false;
3169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003171
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003172 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003173 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003174 }
3175
Mathias Agopian9795c422009-08-26 16:36:26 -07003176 if (locked) {
3177 mStateLock.unlock();
3178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180 write(fd, result.string(), result.size());
3181 return NO_ERROR;
3182}
3183
Dan Stozac7014012014-02-14 15:03:43 -08003184void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3185 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003186{
Robert Carr2047fae2016-11-28 14:09:09 -08003187 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003188 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003189 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003190}
3191
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003192void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003193 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003194{
3195 String8 name;
3196 if (index < args.size()) {
3197 name = String8(args[index]);
3198 index++;
3199 }
3200
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3202 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003203 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003204
3205 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003206 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003207 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003208 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003209 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003210 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003211 }
Robert Carr2047fae2016-11-28 14:09:09 -08003212 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003213 }
3214}
3215
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003216void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003217 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003218{
3219 String8 name;
3220 if (index < args.size()) {
3221 name = String8(args[index]);
3222 index++;
3223 }
3224
Robert Carr2047fae2016-11-28 14:09:09 -08003225 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003226 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003227 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003228 }
Robert Carr2047fae2016-11-28 14:09:09 -08003229 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003230
Svetoslavd85084b2014-03-20 10:28:31 -07003231 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003232}
3233
Jamie Gennis6547ff42013-07-16 20:12:42 -07003234// This should only be called from the main thread. Otherwise it would need
3235// the lock and should use mCurrentState rather than mDrawingState.
3236void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003237 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003238 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003239 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003240
3241 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3242}
3243
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003244void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003245{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003246 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003247 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3248
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003249 if (isLayerTripleBufferingDisabled())
3250 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003251
3252 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003253 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003254 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003255 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003256 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003257}
3258
Dan Stozab90cf072015-03-05 11:05:59 -08003259void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3260{
3261 result.appendFormat("Static screen stats:\n");
3262 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3263 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3264 float percent = 100.0f *
3265 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3266 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3267 b + 1, bucketTimeSec, percent);
3268 }
3269 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3270 float percent = 100.0f *
3271 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3272 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3273 NUM_BUCKETS - 1, bucketTimeSec, percent);
3274}
3275
Dan Stozae77c7662016-05-13 11:37:28 -07003276void SurfaceFlinger::recordBufferingStats(const char* layerName,
3277 std::vector<OccupancyTracker::Segment>&& history) {
3278 Mutex::Autolock lock(mBufferingStatsMutex);
3279 auto& stats = mBufferingStats[layerName];
3280 for (const auto& segment : history) {
3281 if (!segment.usedThirdBuffer) {
3282 stats.twoBufferTime += segment.totalTime;
3283 }
3284 if (segment.occupancyAverage < 1.0f) {
3285 stats.doubleBufferedTime += segment.totalTime;
3286 } else if (segment.occupancyAverage < 2.0f) {
3287 stats.tripleBufferedTime += segment.totalTime;
3288 }
3289 ++stats.numSegments;
3290 stats.totalTime += segment.totalTime;
3291 }
3292}
3293
Brian Andersond6927fb2016-07-23 23:37:30 -07003294void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3295 result.appendFormat("Layer frame timestamps:\n");
3296
3297 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3298 const size_t count = currentLayers.size();
3299 for (size_t i=0 ; i<count ; i++) {
3300 currentLayers[i]->dumpFrameEvents(result);
3301 }
3302}
3303
Dan Stozae77c7662016-05-13 11:37:28 -07003304void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3305 result.append("Buffering stats:\n");
3306 result.append(" [Layer name] <Active time> <Two buffer> "
3307 "<Double buffered> <Triple buffered>\n");
3308 Mutex::Autolock lock(mBufferingStatsMutex);
3309 typedef std::tuple<std::string, float, float, float> BufferTuple;
3310 std::map<float, BufferTuple, std::greater<float>> sorted;
3311 for (const auto& statsPair : mBufferingStats) {
3312 const char* name = statsPair.first.c_str();
3313 const BufferingStats& stats = statsPair.second;
3314 if (stats.numSegments == 0) {
3315 continue;
3316 }
3317 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3318 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3319 stats.totalTime;
3320 float doubleBufferRatio = static_cast<float>(
3321 stats.doubleBufferedTime) / stats.totalTime;
3322 float tripleBufferRatio = static_cast<float>(
3323 stats.tripleBufferedTime) / stats.totalTime;
3324 sorted.insert({activeTime, {name, twoBufferRatio,
3325 doubleBufferRatio, tripleBufferRatio}});
3326 }
3327 for (const auto& sortedPair : sorted) {
3328 float activeTime = sortedPair.first;
3329 const BufferTuple& values = sortedPair.second;
3330 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3331 std::get<0>(values).c_str(), activeTime,
3332 std::get<1>(values), std::get<2>(values),
3333 std::get<3>(values));
3334 }
3335 result.append("\n");
3336}
3337
3338
Mathias Agopian74d211a2013-04-22 16:55:35 +02003339void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3340 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003341{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003342 bool colorize = false;
3343 if (index < args.size()
3344 && (args[index] == String16("--color"))) {
3345 colorize = true;
3346 index++;
3347 }
3348
3349 Colorizer colorizer(colorize);
3350
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003351 // figure out if we're stuck somewhere
3352 const nsecs_t now = systemTime();
3353 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3354 const nsecs_t inTransaction(mDebugInTransaction);
3355 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3356 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3357
3358 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003359 * Dump library configuration.
3360 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003361
3362 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003363 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003365 appendSfConfigString(result);
3366 appendUiConfigString(result);
3367 appendGuiConfigString(result);
3368 result.append("\n");
3369
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003371 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003372 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003373 result.append(SyncFeatures::getInstance().toString());
3374 result.append("\n");
3375
Dan Stoza9e56aa02015-11-02 13:00:03 -08003376 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3377
Andy McFadden41d67d72014-04-25 16:58:34 -07003378 colorizer.bold(result);
3379 result.append("DispSync configuration: ");
3380 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003381 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003382 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003383 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003384 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003385 result.append("\n");
3386
Dan Stozab90cf072015-03-05 11:05:59 -08003387 // Dump static screen stats
3388 result.append("\n");
3389 dumpStaticScreenStats(result);
3390 result.append("\n");
3391
Dan Stozae77c7662016-05-13 11:37:28 -07003392 dumpBufferingStats(result);
3393
Andy McFadden4803b742012-09-24 19:07:20 -07003394 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003395 * Dump the visible layer list
3396 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003398 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003399 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003400 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003401 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003402 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403
3404 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003405 * Dump Display state
3406 */
3407
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003408 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003409 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003410 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003411 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3412 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003413 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003414 }
3415
3416 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003417 * Dump SurfaceFlinger global state
3418 */
3419
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003420 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003421 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003422 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423
Mathias Agopian888c8222012-08-04 21:10:38 -07003424 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003425 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003426
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003427 colorizer.bold(result);
3428 result.appendFormat("EGL implementation : %s\n",
3429 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3430 colorizer.reset(result);
3431 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003432 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003433
Mathias Agopian875d8e12013-06-07 15:35:48 -07003434 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003435
Mathias Agopian42977342012-08-05 00:40:46 -07003436 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003437 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3438 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003439 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003440 " last eglSwapBuffers() time: %f us\n"
3441 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003442 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443 " refresh-rate : %f fps\n"
3444 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003445 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003446 " gpu_to_cpu_unsupported : %d\n"
3447 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448 mLastSwapBufferTime/1000.0,
3449 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003450 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003451 1e9 / activeConfig->getVsyncPeriod(),
3452 activeConfig->getDpiX(),
3453 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003454 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003455
Mathias Agopian74d211a2013-04-22 16:55:35 +02003456 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458
Mathias Agopian74d211a2013-04-22 16:55:35 +02003459 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003460 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003461
3462 /*
3463 * VSYNC state
3464 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003465 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003466 result.append("\n");
3467
3468 /*
3469 * HWC layer minidump
3470 */
3471 for (size_t d = 0; d < mDisplays.size(); d++) {
3472 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3473 int32_t hwcId = displayDevice->getHwcDisplayId();
3474 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3475 continue;
3476 }
3477
3478 result.appendFormat("Display %d HWC layers:\n", hwcId);
3479 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003481 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003482 });
Dan Stozae22aec72016-08-01 13:20:59 -07003483 result.append("\n");
3484 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003485
3486 /*
3487 * Dump HWComposer state
3488 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003489 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003490 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003491 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003492 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003493 result.appendFormat(" h/w composer %s\n",
3494 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003495 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003496
3497 /*
3498 * Dump gralloc state
3499 */
3500 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3501 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003502}
3503
Mathias Agopian13127d82013-03-05 17:47:11 -08003504const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003505SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003506 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003507 wp<IBinder> dpy;
3508 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3509 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3510 dpy = mDisplays.keyAt(i);
3511 break;
3512 }
3513 }
3514 if (dpy == NULL) {
3515 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3516 // Just use the primary display so we have something to return
3517 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3518 }
3519 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003520}
3521
Keun young Park63f165f2012-08-31 10:53:36 -07003522bool SurfaceFlinger::startDdmConnection()
3523{
3524 void* libddmconnection_dso =
3525 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3526 if (!libddmconnection_dso) {
3527 return false;
3528 }
3529 void (*DdmConnection_start)(const char* name);
3530 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003531 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003532 if (!DdmConnection_start) {
3533 dlclose(libddmconnection_dso);
3534 return false;
3535 }
3536 (*DdmConnection_start)(getServiceName());
3537 return true;
3538}
3539
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003540status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 switch (code) {
3542 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003543 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003545 case CLEAR_ANIMATION_FRAME_STATS:
3546 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003547 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003548 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003549 {
3550 // codes that require permission check
3551 IPCThreadState* ipc = IPCThreadState::self();
3552 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003553 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003554 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003555 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003556 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003557 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003558 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003559 break;
3560 }
Robert Carr1db73f62016-12-21 12:58:51 -08003561 /*
3562 * Calling setTransactionState is safe, because you need to have been
3563 * granted a reference to Client* and Handle* to do anything with it.
3564 *
3565 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3566 */
3567 case SET_TRANSACTION_STATE:
3568 case CREATE_SCOPED_CONNECTION:
3569 {
3570 return OK;
3571 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003572 case CAPTURE_SCREEN:
3573 {
3574 // codes that require permission check
3575 IPCThreadState* ipc = IPCThreadState::self();
3576 const int pid = ipc->getCallingPid();
3577 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003578 if ((uid != AID_GRAPHICS) &&
3579 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003580 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003581 return PERMISSION_DENIED;
3582 }
3583 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 }
3585 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003586 return OK;
3587}
3588
3589status_t SurfaceFlinger::onTransact(
3590 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3591{
3592 status_t credentialCheck = CheckTransactCodeCredentials(code);
3593 if (credentialCheck != OK) {
3594 return credentialCheck;
3595 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003596
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3598 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003599 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003600 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003601 IPCThreadState* ipc = IPCThreadState::self();
3602 const int pid = ipc->getCallingPid();
3603 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003604 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003605 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 return PERMISSION_DENIED;
3607 }
3608 int n;
3609 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003610 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003611 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 return NO_ERROR;
3613 case 1002: // SHOW_UPDATES
3614 n = data.readInt32();
3615 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003616 invalidateHwcGeometry();
3617 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003620 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003621 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003623 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003624 setTransactionFlags(
3625 eTransactionNeeded|
3626 eDisplayTransactionNeeded|
3627 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003628 return NO_ERROR;
3629 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003630 case 1006:{ // send empty update
3631 signalRefresh();
3632 return NO_ERROR;
3633 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003634 case 1008: // toggle use of hw composer
3635 n = data.readInt32();
3636 mDebugDisableHWC = n ? 1 : 0;
3637 invalidateHwcGeometry();
3638 repaintEverything();
3639 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003640 case 1009: // toggle use of transform hint
3641 n = data.readInt32();
3642 mDebugDisableTransformHint = n ? 1 : 0;
3643 invalidateHwcGeometry();
3644 repaintEverything();
3645 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003647 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 reply->writeInt32(0);
3649 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003650 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003651 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652 return NO_ERROR;
3653 case 1013: {
3654 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003655 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3656 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003657 return NO_ERROR;
3658 }
3659 case 1014: {
3660 // daltonize
3661 n = data.readInt32();
3662 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003663 case 1:
3664 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3665 break;
3666 case 2:
3667 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3668 break;
3669 case 3:
3670 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3671 break;
3672 default:
3673 mDaltonizer.setType(ColorBlindnessType::None);
3674 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003675 }
3676 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003677 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003678 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003679 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003680 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003681 invalidateHwcGeometry();
3682 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003683 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003685 case 1015: {
3686 // apply a color matrix
3687 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003688 if (n) {
3689 // color matrix is sent as mat3 matrix followed by vec3
3690 // offset, then packed into a mat4 where the last row is
3691 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003692 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003693 for (size_t j = 0; j < 4; j++) {
3694 mColorMatrix[i][j] = data.readFloat();
3695 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003696 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003697 } else {
3698 mColorMatrix = mat4();
3699 }
3700 invalidateHwcGeometry();
3701 repaintEverything();
3702 return NO_ERROR;
3703 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003704 // This is an experimental interface
3705 // Needs to be shifted to proper binder interface when we productize
3706 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003707 n = data.readInt32();
3708 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003709 return NO_ERROR;
3710 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003711 case 1017: {
3712 n = data.readInt32();
3713 mForceFullDamage = static_cast<bool>(n);
3714 return NO_ERROR;
3715 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003716 case 1018: { // Modify Choreographer's phase offset
3717 n = data.readInt32();
3718 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3719 return NO_ERROR;
3720 }
3721 case 1019: { // Modify SurfaceFlinger's phase offset
3722 n = data.readInt32();
3723 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3724 return NO_ERROR;
3725 }
Irvel468051e2016-06-13 16:44:44 -07003726 case 1020: { // Layer updates interceptor
3727 n = data.readInt32();
3728 if (n) {
3729 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003730 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003731 }
3732 else{
3733 ALOGV("Interceptor disabled");
3734 mInterceptor.disable();
3735 }
3736 return NO_ERROR;
3737 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003738 case 1021: { // Disable HWC virtual displays
3739 n = data.readInt32();
3740 mUseHwcVirtualDisplays = !n;
3741 return NO_ERROR;
3742 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 }
3744 }
3745 return err;
3746}
3747
Mathias Agopian53331da2011-08-22 21:44:41 -07003748void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003749 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003750 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003751}
3752
Mathias Agopian59119e62010-10-11 12:37:43 -07003753// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003754// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003755// ---------------------------------------------------------------------------
3756
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003757/* The code below is here to handle b/8734824
3758 *
3759 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003760 * from the surfaceflinger thread to the calling binder thread, where they
3761 * are executed. This allows the calling thread in the calling process to be
3762 * reused and not depend on having "enough" binder threads to handle the
3763 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003764 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003765class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003766 /* Parts of GraphicProducerWrapper are run on two different threads,
3767 * communicating by sending messages via Looper but also by shared member
3768 * data. Coherence maintenance is subtle and in places implicit (ugh).
3769 *
3770 * Don't rely on Looper's sendMessage/handleMessage providing
3771 * release/acquire semantics for any data not actually in the Message.
3772 * Data going from surfaceflinger to binder threads needs to be
3773 * synchronized explicitly.
3774 *
3775 * Barrier open/wait do provide release/acquire semantics. This provides
3776 * implicit synchronization for data coming back from binder to
3777 * surfaceflinger threads.
3778 */
3779
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003780 sp<IGraphicBufferProducer> impl;
3781 sp<Looper> looper;
3782 status_t result;
3783 bool exitPending;
3784 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003785 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003786 uint32_t code;
3787 Parcel const* data;
3788 Parcel* reply;
3789
3790 enum {
3791 MSG_API_CALL,
3792 MSG_EXIT
3793 };
3794
3795 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003796 * Called on surfaceflinger thread. This is called by our "fake"
3797 * BpGraphicBufferProducer. We package the data and reply Parcel and
3798 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003799 */
3800 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003801 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003802 this->code = code;
3803 this->data = &data;
3804 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003805 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003806 // if we've exited, we run the message synchronously right here.
3807 // note (JH): as far as I can tell from looking at the code, this
3808 // never actually happens. if it does, i'm not sure if it happens
3809 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003810 handleMessage(Message(MSG_API_CALL));
3811 } else {
3812 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003813 // Prevent stores to this->{code, data, reply} from being
3814 // reordered later than the construction of Message.
3815 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003816 looper->sendMessage(this, Message(MSG_API_CALL));
3817 barrier.wait();
3818 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003819 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 }
3821
3822 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003823 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 * call the real BpGraphicBufferProducer.
3825 */
3826 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003827 int what = message.what;
3828 // Prevent reads below from happening before the read from Message
3829 atomic_thread_fence(memory_order_acquire);
3830 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003831 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003832 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003833 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003834 exitRequested = true;
3835 }
3836 }
3837
3838public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003839 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003840 : impl(impl),
3841 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003842 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003843 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003844 exitRequested(false),
3845 code(0),
3846 data(NULL),
3847 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003848 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849
Jesse Hallb154c422014-07-13 12:47:02 -07003850 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003851 status_t waitForResponse() {
3852 do {
3853 looper->pollOnce(-1);
3854 } while (!exitRequested);
3855 return result;
3856 }
3857
Jesse Hallb154c422014-07-13 12:47:02 -07003858 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003859 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003860 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003861 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003862 // Ensure this->result is visible to the binder thread before it
3863 // handles the message.
3864 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003865 looper->sendMessage(this, Message(MSG_EXIT));
3866 }
3867};
3868
3869
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003870status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3871 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003872 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003873 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003874 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003875
3876 if (CC_UNLIKELY(display == 0))
3877 return BAD_VALUE;
3878
3879 if (CC_UNLIKELY(producer == 0))
3880 return BAD_VALUE;
3881
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003882 // if we have secure windows on this display, never allow the screen capture
3883 // unless the producer interface is local (i.e.: we can take a screenshot for
3884 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003885 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003886
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003887 // Convert to surfaceflinger's internal rotation type.
3888 Transform::orientation_flags rotationFlags;
3889 switch (rotation) {
3890 case ISurfaceComposer::eRotateNone:
3891 rotationFlags = Transform::ROT_0;
3892 break;
3893 case ISurfaceComposer::eRotate90:
3894 rotationFlags = Transform::ROT_90;
3895 break;
3896 case ISurfaceComposer::eRotate180:
3897 rotationFlags = Transform::ROT_180;
3898 break;
3899 case ISurfaceComposer::eRotate270:
3900 rotationFlags = Transform::ROT_270;
3901 break;
3902 default:
3903 rotationFlags = Transform::ROT_0;
3904 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3905 break;
3906 }
3907
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003908 class MessageCaptureScreen : public MessageBase {
3909 SurfaceFlinger* flinger;
3910 sp<IBinder> display;
3911 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003912 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003913 uint32_t reqWidth, reqHeight;
3914 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003915 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003916 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003917 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003918 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003919 public:
3920 MessageCaptureScreen(SurfaceFlinger* flinger,
3921 const sp<IBinder>& display,
3922 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003923 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003924 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003925 bool useIdentityTransform,
3926 Transform::orientation_flags rotation,
3927 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003929 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003931 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003932 rotation(rotation), result(PERMISSION_DENIED),
3933 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003934 {
3935 }
3936 status_t getResult() const {
3937 return result;
3938 }
3939 virtual bool handler() {
3940 Mutex::Autolock _l(flinger->mStateLock);
3941 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003942 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003943 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003944 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003945 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003946 return true;
3947 }
3948 };
3949
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003950 // this creates a "fake" BBinder which will serve as a "fake" remote
3951 // binder to receive the marshaled calls and forward them to the
3952 // real remote (a BpGraphicBufferProducer)
3953 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3954
3955 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3956 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003957 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003958 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003959 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003960 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003961
3962 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003963 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003964 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003965 }
3966 return res;
3967}
3968
Mathias Agopian180f10d2013-04-10 22:55:41 -07003969
3970void SurfaceFlinger::renderScreenImplLocked(
3971 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003972 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003973 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003974 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003975{
3976 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003977 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003978
3979 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003980 const int32_t hw_w = hw->getWidth();
3981 const int32_t hw_h = hw->getHeight();
3982 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003983 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003984
Dan Stozac1879002014-05-22 15:59:05 -07003985 // if a default or invalid sourceCrop is passed in, set reasonable values
3986 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3987 !sourceCrop.isValid()) {
3988 sourceCrop.setLeftTop(Point(0, 0));
3989 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3990 }
3991
3992 // ensure that sourceCrop is inside screen
3993 if (sourceCrop.left < 0) {
3994 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3995 }
Dan Stozabe31f442014-06-11 11:20:54 -07003996 if (sourceCrop.right > hw_w) {
3997 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003998 }
3999 if (sourceCrop.top < 0) {
4000 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4001 }
Dan Stozabe31f442014-06-11 11:20:54 -07004002 if (sourceCrop.bottom > hw_h) {
4003 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004004 }
4005
Mathias Agopian180f10d2013-04-10 22:55:41 -07004006 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004007 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004008
4009 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004010 engine.setViewportAndProjection(
4011 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004012 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004013
4014 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004015 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004016
Robert Carr1f0a16a2016-10-24 16:27:39 -07004017 // We loop through the first level of layers without traversing,
4018 // as we need to interpret min/max layer Z in the top level Z space.
4019 for (const auto& layer : mDrawingState.layersSortedByZ) {
4020 if (layer->getLayerStack() != hw->getLayerStack()) {
4021 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004023 const Layer::State& state(layer->getDrawingState());
4024 if (state.z < minLayerZ || state.z > maxLayerZ) {
4025 continue;
4026 }
4027 layer->traverseInZOrder([&](Layer* layer) {
4028 if (!layer->isVisible()) {
4029 return;
4030 }
4031 if (filtering) layer->setFiltering(true);
4032 layer->draw(hw, useIdentityTransform);
4033 if (filtering) layer->setFiltering(false);
4034 });
4035 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004036
Mathias Agopian931bda12013-08-28 18:11:46 -07004037 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004038}
4039
4040
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004041status_t SurfaceFlinger::captureScreenImplLocked(
4042 const sp<const DisplayDevice>& hw,
4043 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004044 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004045 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004046 bool useIdentityTransform, Transform::orientation_flags rotation,
4047 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004048{
4049 ATRACE_CALL();
4050
Mathias Agopian180f10d2013-04-10 22:55:41 -07004051 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004052 uint32_t hw_w = hw->getWidth();
4053 uint32_t hw_h = hw->getHeight();
4054
4055 if (rotation & Transform::ROT_90) {
4056 std::swap(hw_w, hw_h);
4057 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004058
Mathias Agopian180f10d2013-04-10 22:55:41 -07004059 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4060 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4061 reqWidth, reqHeight, hw_w, hw_h);
4062 return BAD_VALUE;
4063 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004064
Mathias Agopian180f10d2013-04-10 22:55:41 -07004065 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4066 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4067
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004068 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004069 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004070 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004071 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4072 (state.z < minLayerZ || state.z > maxLayerZ)) {
4073 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004074 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004075 layer->traverseInZOrder([&](Layer *layer) {
4076 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4077 layer->isSecure());
4078 });
4079 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004080
4081 if (!isLocalScreenshot && secureLayerIsVisible) {
4082 ALOGW("FB is protected: PERMISSION_DENIED");
4083 return PERMISSION_DENIED;
4084 }
4085
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004086 // create a surface (because we're a producer, and we need to
4087 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004088 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004089
4090 // Put the screenshot Surface into async mode so that
4091 // Layer::headFenceHasSignaled will always return true and we'll latch the
4092 // first buffer regardless of whether or not its acquire fence has
4093 // signaled. This is needed to avoid a race condition in the rotation
4094 // animation. See b/30209608
4095 sur->setAsyncMode(true);
4096
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004097 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004098
Michael Lentine5a16a622015-05-21 13:48:24 -07004099 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4100 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004101 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4102 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004103
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004104 int err = 0;
4105 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004106 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004107 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4108 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004109
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004110 if (err == NO_ERROR) {
4111 ANativeWindowBuffer* buffer;
4112 /* TODO: Once we have the sync framework everywhere this can use
4113 * server-side waits on the fence that dequeueBuffer returns.
4114 */
4115 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4116 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004117 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004118 // create an EGLImage from the buffer so we can later
4119 // turn it into a texture
4120 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4121 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4122 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004123 // this binds the given EGLImage as a framebuffer for the
4124 // duration of this scope.
4125 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4126 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004127 // this will in fact render into our dequeued buffer
4128 // via an FBO, which means we didn't have to create
4129 // an EGLSurface and therefore we're not
4130 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004131 renderScreenImplLocked(
4132 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4133 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004134
Riley Andrews86639902014-08-15 12:27:24 -07004135 // Attempt to create a sync khr object that can produce a sync point. If that
4136 // isn't available, create a non-dupable sync object in the fallback path and
4137 // wait on it directly.
4138 EGLSyncKHR sync;
4139 if (!DEBUG_SCREENSHOTS) {
4140 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004141 // native fence fd will not be populated until flush() is done.
4142 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004143 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004144 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004145 }
Riley Andrews86639902014-08-15 12:27:24 -07004146 if (sync != EGL_NO_SYNC_KHR) {
4147 // get the sync fd
4148 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4149 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4150 ALOGW("captureScreen: failed to dup sync khr object");
4151 syncFd = -1;
4152 }
4153 eglDestroySyncKHR(mEGLDisplay, sync);
4154 } else {
4155 // fallback path
4156 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4157 if (sync != EGL_NO_SYNC_KHR) {
4158 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4159 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4160 EGLint eglErr = eglGetError();
4161 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4162 ALOGW("captureScreen: fence wait timed out");
4163 } else {
4164 ALOGW_IF(eglErr != EGL_SUCCESS,
4165 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4166 }
4167 eglDestroySyncKHR(mEGLDisplay, sync);
4168 } else {
4169 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4170 }
4171 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004172 if (DEBUG_SCREENSHOTS) {
4173 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4174 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4175 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4176 hw, minLayerZ, maxLayerZ);
4177 delete [] pixels;
4178 }
4179
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004180 } else {
4181 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4182 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004183 window->cancelBuffer(window, buffer, syncFd);
4184 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004185 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004186 // destroy our image
4187 eglDestroyImageKHR(mEGLDisplay, image);
4188 } else {
4189 result = BAD_VALUE;
4190 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004191 if (buffer) {
4192 // queueBuffer takes ownership of syncFd
4193 result = window->queueBuffer(window, buffer, syncFd);
4194 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004195 }
4196 } else {
4197 result = BAD_VALUE;
4198 }
4199 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4200 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004201
Mathias Agopian74c40c02010-09-29 13:02:36 -07004202 return result;
4203}
4204
Mathias Agopiand5556842013-09-19 17:08:37 -07004205void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004206 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004207 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004208 for (size_t y=0 ; y<h ; y++) {
4209 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4210 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004211 if (p[x] != 0xFF000000) return;
4212 }
4213 }
4214 ALOGE("*** we just took a black screenshot ***\n"
4215 "requested minz=%d, maxz=%d, layerStack=%d",
4216 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004217
Robert Carr2047fae2016-11-28 14:09:09 -08004218 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004219 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004220 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004221 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4222 state.z <= maxLayerZ) {
4223 layer->traverseInZOrder([&](Layer* layer) {
4224 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4225 layer->isVisible() ? '+' : '-',
4226 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004227 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004228 i++;
4229 });
4230 }
4231 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004232 }
4233}
4234
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004235// ---------------------------------------------------------------------------
4236
Robert Carr2047fae2016-11-28 14:09:09 -08004237void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4238 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004239}
4240
Robert Carr2047fae2016-11-28 14:09:09 -08004241void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4242 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004243}
4244
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004246
4247
4248#if defined(__gl_h_)
4249#error "don't include gl/gl.h in this file"
4250#endif
4251
4252#if defined(__gl2_h_)
4253#error "don't include gl2/gl2.h in this file"
4254#endif