blob: 5f1d16f21486a8947b5ffe0a24bfb11899f62da0 [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
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Mathias Agopian99b49842011-06-27 16:05:52 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700120 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700122 mTransactionPending(false),
123 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700124 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700125 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700126 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800127 mHwc(nullptr),
128 mRealHwc(nullptr),
129 mVrHwc(nullptr),
130 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800132 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800134 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800135 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800136 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700138 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700139 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700140 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700141 mDebugInSwapBuffers(0),
142 mLastSwapBufferTime(0),
143 mDebugInTransaction(0),
144 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700145 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700146 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800147 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000148 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700149 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700150 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800151 mHasColorMatrix(false),
152 mHasPoweredOff(false),
153 mFrameBuckets(),
154 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700155 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800156 mNumLayers(0)
157#ifdef USE_HWC2
158 ,mEnterVrMode(false)
159#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160{
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800161
162 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
163 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
164
165 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
166 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
167
Steve Blocka19954a2012-01-04 20:05:49 +0000168 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700170 useContextPriority = getBool< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::useContextPriority>(false);
172
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700173 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
175
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700176 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 // debugging stuff...
180 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700181
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800182 // TODO (urbanus): remove once b/35319396 is fixed.
183 property_get("ro.boot.vr", value, "0");
184 mVrModeSupported = atoi(value);
185
Mathias Agopianb4b17302013-03-20 18:36:41 -0700186 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700187 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 property_get("debug.sf.showupdates", value, "0");
190 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700191
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700192 property_get("debug.sf.ddms", value, "0");
193 mDebugDDMS = atoi(value);
194 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700195 if (!startDdmConnection()) {
196 // start failed, and DDMS debugging not enabled
197 mDebugDDMS = 0;
198 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700200 ALOGI_IF(mDebugRegion, "showupdates enabled");
201 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700202
203 property_get("debug.sf.disable_backpressure", value, "0");
204 mPropagateBackpressure = !atoi(value);
205 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700206
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800207 property_get("debug.sf.enable_hwc_vds", value, "0");
208 mUseHwcVirtualDisplays = atoi(value);
209 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800210
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800211 property_get("ro.sf.disable_triple_buffer", value, "1");
212 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800213 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214}
215
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800216void SurfaceFlinger::onFirstRef()
217{
218 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219}
220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221SurfaceFlinger::~SurfaceFlinger()
222{
Mathias Agopiana4912602012-07-12 14:25:33 -0700223 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
224 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
225 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800226
227 if (mVrStateCallbacks.get()) {
228 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
229 defaultServiceManager()->checkService(String16("vrmanager")));
230 if (vrManagerService.get()) {
231 vrManagerService->unregisterListener(mVrStateCallbacks);
232 }
233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234}
235
Dan Stozac7014012014-02-14 15:03:43 -0800236void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800237{
238 // the window manager died on us. prepare its eulogy.
239
Andy McFadden13a082e2012-08-24 10:16:42 -0700240 // restore initial conditions (default device unblank, etc)
241 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242
243 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700244 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245}
246
Robert Carr1db73f62016-12-21 12:58:51 -0800247static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700248 status_t err = client->initCheck();
249 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800250 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 }
Robert Carr1db73f62016-12-21 12:58:51 -0800252 return nullptr;
253}
254
255sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
256 return initClient(new Client(this));
257}
258
259sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
260 const sp<IGraphicBufferProducer>& gbp) {
261 if (authenticateSurfaceTexture(gbp) == false) {
262 return nullptr;
263 }
264 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
265 if (layer == nullptr) {
266 return nullptr;
267 }
268
269 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270}
271
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700272sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
273 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700274{
275 class DisplayToken : public BBinder {
276 sp<SurfaceFlinger> flinger;
277 virtual ~DisplayToken() {
278 // no more references, this display must be terminated
279 Mutex::Autolock _l(flinger->mStateLock);
280 flinger->mCurrentState.displays.removeItem(this);
281 flinger->setTransactionFlags(eDisplayTransactionNeeded);
282 }
283 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700284 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285 : flinger(flinger) {
286 }
287 };
288
289 sp<BBinder> token = new DisplayToken(this);
290
291 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700292 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700293 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700294 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700295 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700296 return token;
297}
298
Jesse Hall6c913be2013-08-08 12:15:49 -0700299void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
300 Mutex::Autolock _l(mStateLock);
301
302 ssize_t idx = mCurrentState.displays.indexOfKey(display);
303 if (idx < 0) {
304 ALOGW("destroyDisplay: invalid display token");
305 return;
306 }
307
308 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
309 if (!info.isVirtualDisplay()) {
310 ALOGE("destroyDisplay called for non-virtual display");
311 return;
312 }
Irvelffc9efc2016-07-27 15:16:37 -0700313 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700314 mCurrentState.displays.removeItemsAt(idx);
315 setTransactionFlags(eDisplayTransactionNeeded);
316}
317
Jesse Hall692c7232012-11-08 15:41:56 -0800318void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800319 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800320 ALOGW_IF(mBuiltinDisplays[type],
321 "Overwriting display token for display type %d", type);
322 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800323 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700324 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700326 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800327}
328
Mathias Agopiane57f2922012-08-09 16:29:12 -0700329sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700330 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
332 return NULL;
333 }
Jesse Hall692c7232012-11-08 15:41:56 -0800334 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335}
336
Romain Guyf8b4ca52017-03-16 18:39:20 +0000337sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
338{
339 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
340 return gba;
341}
342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343void SurfaceFlinger::bootFinished()
344{
Wei Wangb254fa32017-01-31 17:43:23 -0800345 if (mStartBootAnimThread->join() != NO_ERROR) {
346 ALOGE("Join StartBootAnimThread failed!");
347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 const nsecs_t now = systemTime();
349 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000350 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700351 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700352
353 // wait patiently for the window manager death
354 const String16 name("window");
355 sp<IBinder> window(defaultServiceManager()->getService(name));
356 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700357 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358 }
359
360 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700361 // formerly we would just kill the process, but we now ask it to exit so it
362 // can choose where to stop the animation.
363 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700364
365 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
366 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
367 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800368
369 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
370 defaultServiceManager()->checkService(String16("vrmanager")));
371 if (vrManagerService.get()) {
372 mVrStateCallbacks = new VrStateCallbacks(*this);
373 vrManagerService->registerListener(mVrStateCallbacks);
374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian3f844832013-08-07 21:24:32 -0700377void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700379 RenderEngine& engine;
380 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
383 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 }
385 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 return true;
388 }
389 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700391}
392
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700393class DispSyncSource : public VSyncSource, private DispSync::Callback {
394public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700395 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000396 const char* name) :
397 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700398 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700399 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000400 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
401 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700402 mDispSync(dispSync),
403 mCallbackMutex(),
404 mCallback(),
405 mVsyncMutex(),
406 mPhaseOffset(phaseOffset),
407 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700408
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 virtual ~DispSyncSource() {}
410
411 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700413 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000414 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 static_cast<DispSync::Callback*>(this));
416 if (err != NO_ERROR) {
417 ALOGE("error registering vsync callback: %s (%d)",
418 strerror(-err), err);
419 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700420 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 } else {
422 status_t err = mDispSync->removeEventListener(
423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error unregistering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 }
432
433 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 mCallback = callback;
436 }
437
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 virtual void setPhaseOffset(nsecs_t phaseOffset) {
439 Mutex::Autolock lock(mVsyncMutex);
440
441 // Normalize phaseOffset to [0, period)
442 auto period = mDispSync->getPeriod();
443 phaseOffset %= period;
444 if (phaseOffset < 0) {
445 // If we're here, then phaseOffset is in (-period, 0). After this
446 // operation, it will be in (0, period)
447 phaseOffset += period;
448 }
449 mPhaseOffset = phaseOffset;
450
451 // If we're not enabled, we don't need to mess with the listeners
452 if (!mEnabled) {
453 return;
454 }
455
456 // Remove the listener with the old offset
457 status_t err = mDispSync->removeEventListener(
458 static_cast<DispSync::Callback*>(this));
459 if (err != NO_ERROR) {
460 ALOGE("error unregistering vsync callback: %s (%d)",
461 strerror(-err), err);
462 }
463
464 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error registering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471 }
472
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473private:
474 virtual void onDispSyncEvent(nsecs_t when) {
475 sp<VSyncSource::Callback> callback;
476 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700477 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 callback = mCallback;
479
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700480 if (mTraceVsync) {
481 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700482 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 }
485
486 if (callback != NULL) {
487 callback->onVSyncEvent(when);
488 }
489 }
490
Tim Murray4a4e4a22016-04-19 16:29:23 +0000491 const char* const mName;
492
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493 int mValue;
494
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700495 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 const String8 mVsyncOnLabel;
497 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500
501 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mVsyncMutex; // Protects the following
505 nsecs_t mPhaseOffset;
506 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507};
508
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700509class InjectVSyncSource : public VSyncSource {
510public:
511 InjectVSyncSource() {}
512
513 virtual ~InjectVSyncSource() {}
514
515 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
516 std::lock_guard<std::mutex> lock(mCallbackMutex);
517 mCallback = callback;
518 }
519
520 virtual void onInjectSyncEvent(nsecs_t when) {
521 std::lock_guard<std::mutex> lock(mCallbackMutex);
522 mCallback->onVSyncEvent(when);
523 }
524
525 virtual void setVSyncEnabled(bool) {}
526 virtual void setPhaseOffset(nsecs_t) {}
527
528private:
529 std::mutex mCallbackMutex; // Protects the following
530 sp<VSyncSource::Callback> mCallback;
531};
532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700534 ALOGI( "SurfaceFlinger's main thread ready to run. "
535 "Initializing graphics H/W...");
536
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900537 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
538
Dan Stoza9e56aa02015-11-02 13:00:03 -0800539 { // Autolock scope
540 Mutex::Autolock _l(mStateLock);
541
542 // initialize EGL for the default display
543 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
544 eglInitialize(mEGLDisplay, NULL, NULL);
545
546 // start the EventThread
547 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
548 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700549 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700552 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 mEventQueue.setEventThread(mSFEventThread);
554
Tim Murrayacff43d2016-07-29 13:57:24 -0700555 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700556 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700557 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700558 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
559 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
560 }
561
Dan Stoza9e56aa02015-11-02 13:00:03 -0800562 // Get a RenderEngine for the given display / config (can't fail)
563 mRenderEngine = RenderEngine::create(mEGLDisplay,
564 HAL_PIXEL_FORMAT_RGBA_8888);
565 }
566
567 // Drop the state lock while we initialize the hardware composer. We drop
568 // the lock because on creation, it will call back into SurfaceFlinger to
569 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800570 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800571 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800572 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
574
Jesse Hall692c7232012-11-08 15:41:56 -0800575 Mutex::Autolock _l(mStateLock);
576
Mathias Agopian875d8e12013-06-07 15:35:48 -0700577 // retrieve the EGL context that was selected/created
578 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700579
Mathias Agopianda27af92012-09-13 18:17:13 -0700580 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
581 "couldn't create EGLContext");
582
Dan Stoza9e56aa02015-11-02 13:00:03 -0800583 // make the GLContext current so that we can create textures when creating
584 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700585 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
586
Jamie Gennisd1700752013-10-14 12:22:52 -0700587 mEventControlThread = new EventControlThread(this);
588 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
589
Mathias Agopian92a979a2012-08-02 18:32:23 -0700590 // initialize our drawing state
591 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700592
Andy McFadden13a082e2012-08-24 10:16:42 -0700593 // set initial conditions (e.g. unblank default device)
594 initializeDisplays();
595
Dan Stoza4e637772016-07-28 13:31:51 -0700596 mRenderEngine->primeCache();
597
Wei Wangb254fa32017-01-31 17:43:23 -0800598 mStartBootAnimThread = new StartBootAnimThread();
599 if (mStartBootAnimThread->Start() != NO_ERROR) {
600 ALOGE("Run StartBootAnimThread failed!");
601 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800602
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700604}
605
Mathias Agopiana67e4182012-06-19 17:26:12 -0700606void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800607 // Start boot animation service by setting a property mailbox
608 // if property setting thread is already running, Start() will be just a NOP
609 mStartBootAnimThread->Start();
610 // Wait until property was set
611 if (mStartBootAnimThread->join() != NO_ERROR) {
612 ALOGE("Join StartBootAnimThread failed!");
613 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700614}
615
Mathias Agopian875d8e12013-06-07 15:35:48 -0700616size_t SurfaceFlinger::getMaxTextureSize() const {
617 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700618}
619
Mathias Agopian875d8e12013-06-07 15:35:48 -0700620size_t SurfaceFlinger::getMaxViewportDims() const {
621 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700622}
623
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800624// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800625
Jamie Gennis582270d2011-08-17 18:19:00 -0700626bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800627 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800628 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800629 return authenticateSurfaceTextureLocked(bufferProducer);
630}
631
632bool SurfaceFlinger::authenticateSurfaceTextureLocked(
633 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800634 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700635 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800636}
637
Brian Anderson069b3652016-07-22 10:32:47 -0700638status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700639 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700640 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700641 FrameEvent::REQUESTED_PRESENT,
642 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700643 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700644 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700645 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700646 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700647 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700648 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700649 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700650 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700651 };
652 return NO_ERROR;
653}
654
Dan Stoza7f7da322014-05-02 15:26:25 -0700655status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
656 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700657 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700658 return BAD_VALUE;
659 }
660
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500661 if (!display.get())
662 return NAME_NOT_FOUND;
663
Jesse Hall692c7232012-11-08 15:41:56 -0800664 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700665 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800666 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700667 type = i;
668 break;
669 }
670 }
671
672 if (type < 0) {
673 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700674 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700675
Mathias Agopian8b736f12012-08-13 17:54:26 -0700676 // TODO: Not sure if display density should handled by SF any longer
677 class Density {
678 static int getDensityFromProperty(char const* propName) {
679 char property[PROPERTY_VALUE_MAX];
680 int density = 0;
681 if (property_get(propName, property, NULL) > 0) {
682 density = atoi(property);
683 }
684 return density;
685 }
686 public:
687 static int getEmuDensity() {
688 return getDensityFromProperty("qemu.sf.lcd_density"); }
689 static int getBuildDensity() {
690 return getDensityFromProperty("ro.sf.lcd_density"); }
691 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700692
Dan Stoza7f7da322014-05-02 15:26:25 -0700693 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700694
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700696 DisplayInfo info = DisplayInfo();
697
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 float xdpi = hwConfig->getDpiX();
699 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700700
701 if (type == DisplayDevice::DISPLAY_PRIMARY) {
702 // The density of the device is provided by a build property
703 float density = Density::getBuildDensity() / 160.0f;
704 if (density == 0) {
705 // the build doesn't provide a density -- this is wrong!
706 // use xdpi instead
707 ALOGE("ro.sf.lcd_density must be defined as a build property");
708 density = xdpi / 160.0f;
709 }
710 if (Density::getEmuDensity()) {
711 // if "qemu.sf.lcd_density" is specified, it overrides everything
712 xdpi = ydpi = density = Density::getEmuDensity();
713 density /= 160.0f;
714 }
715 info.density = density;
716
717 // TODO: this needs to go away (currently needed only by webkit)
718 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
719 info.orientation = hw->getOrientation();
720 } else {
721 // TODO: where should this value come from?
722 static const int TV_DENSITY = 213;
723 info.density = TV_DENSITY / 160.0f;
724 info.orientation = 0;
725 }
726
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 info.w = hwConfig->getWidth();
728 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700729 info.xdpi = xdpi;
730 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900732 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733
Andy McFadden91b2ca82014-06-13 14:04:23 -0700734 // This is how far in advance a buffer must be queued for
735 // presentation at a given time. If you want a buffer to appear
736 // on the screen at time N, you must submit the buffer before
737 // (N - presentationDeadline).
738 //
739 // Normally it's one full refresh period (to give SF a chance to
740 // latch the buffer), but this can be reduced by configuring a
741 // DispSync offset. Any additional delays introduced by the hardware
742 // composer or panel must be accounted for here.
743 //
744 // We add an additional 1ms to allow for processing time and
745 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800747 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700748
749 // All non-virtual displays are currently considered secure.
750 info.secure = true;
751
Michael Wright28f24d02016-07-12 13:30:53 -0700752 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 }
754
Dan Stoza7f7da322014-05-02 15:26:25 -0700755 return NO_ERROR;
756}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700757
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800758status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700759 DisplayStatInfo* stats) {
760 if (stats == NULL) {
761 return BAD_VALUE;
762 }
763
764 // FIXME for now we always return stats for the primary display
765 memset(stats, 0, sizeof(*stats));
766 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
767 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
768 return NO_ERROR;
769}
770
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700771int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800772 if (display == NULL) {
773 ALOGE("%s : display is NULL", __func__);
774 return BAD_VALUE;
775 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700776 sp<DisplayDevice> device(getDisplayDevice(display));
777 if (device != NULL) {
778 return device->getActiveConfig();
779 }
780 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700781}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700782
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700783void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
784 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
785 this);
786 int32_t type = hw->getDisplayType();
787 int currentMode = hw->getActiveConfig();
788
789 if (mode == currentMode) {
790 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
791 return;
792 }
793
794 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
795 ALOGW("Trying to set config for virtual display");
796 return;
797 }
798
799 hw->setActiveConfig(mode);
800 getHwComposer().setActiveConfig(type, mode);
801}
802
803status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
804 class MessageSetActiveConfig: public MessageBase {
805 SurfaceFlinger& mFlinger;
806 sp<IBinder> mDisplay;
807 int mMode;
808 public:
809 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
810 int mode) :
811 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
812 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700813 Vector<DisplayInfo> configs;
814 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700815 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700816 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700817 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700818 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700819 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700820 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
821 if (hw == NULL) {
822 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700823 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700824 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
825 ALOGW("Attempt to set active config = %d for virtual display",
826 mMode);
827 } else {
828 mFlinger.setActiveConfigInternal(hw, mMode);
829 }
830 return true;
831 }
832 };
833 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
834 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700835 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700836}
Michael Wright28f24d02016-07-12 13:30:53 -0700837status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
838 Vector<android_color_mode_t>* outColorModes) {
839 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
840 return BAD_VALUE;
841 }
842
843 if (!display.get()) {
844 return NAME_NOT_FOUND;
845 }
846
847 int32_t type = NAME_NOT_FOUND;
848 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
849 if (display == mBuiltinDisplays[i]) {
850 type = i;
851 break;
852 }
853 }
854
855 if (type < 0) {
856 return type;
857 }
858
859 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
860 outColorModes->clear();
861 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
862
863 return NO_ERROR;
864}
865
866android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
867 sp<DisplayDevice> device(getDisplayDevice(display));
868 if (device != nullptr) {
869 return device->getActiveColorMode();
870 }
871 return static_cast<android_color_mode_t>(BAD_VALUE);
872}
873
874void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
875 android_color_mode_t mode) {
876 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
877 this);
878 int32_t type = hw->getDisplayType();
879 android_color_mode_t currentMode = hw->getActiveColorMode();
880
881 if (mode == currentMode) {
882 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
883 return;
884 }
885
886 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
887 ALOGW("Trying to set config for virtual display");
888 return;
889 }
890
891 hw->setActiveColorMode(mode);
892 getHwComposer().setActiveColorMode(type, mode);
893}
894
895
896status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
897 android_color_mode_t colorMode) {
898 class MessageSetActiveColorMode: public MessageBase {
899 SurfaceFlinger& mFlinger;
900 sp<IBinder> mDisplay;
901 android_color_mode_t mMode;
902 public:
903 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
904 android_color_mode_t mode) :
905 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
906 virtual bool handler() {
907 Vector<android_color_mode_t> modes;
908 mFlinger.getDisplayColorModes(mDisplay, &modes);
909 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
910 if (mMode < 0 || !exists) {
911 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
912 mDisplay.get());
913 return true;
914 }
915 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
916 if (hw == nullptr) {
917 ALOGE("Attempt to set active color mode = %d for null display %p",
918 mMode, mDisplay.get());
919 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
920 ALOGW("Attempt to set active color mode= %d for virtual display",
921 mMode);
922 } else {
923 mFlinger.setActiveColorModeInternal(hw, mMode);
924 }
925 return true;
926 }
927 };
928 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
929 postMessageSync(msg);
930 return NO_ERROR;
931}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700932
Svetoslavd85084b2014-03-20 10:28:31 -0700933status_t SurfaceFlinger::clearAnimationFrameStats() {
934 Mutex::Autolock _l(mStateLock);
935 mAnimFrameTracker.clearStats();
936 return NO_ERROR;
937}
938
939status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
940 Mutex::Autolock _l(mStateLock);
941 mAnimFrameTracker.getStats(outStats);
942 return NO_ERROR;
943}
944
Dan Stozac4f471e2016-03-24 09:31:08 -0700945status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
946 HdrCapabilities* outCapabilities) const {
947 Mutex::Autolock _l(mStateLock);
948
949 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
950 if (displayDevice == nullptr) {
951 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
952 return BAD_VALUE;
953 }
954
955 std::unique_ptr<HdrCapabilities> capabilities =
956 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
957 if (capabilities) {
958 std::swap(*outCapabilities, *capabilities);
959 } else {
960 return BAD_VALUE;
961 }
962
963 return NO_ERROR;
964}
965
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700966status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
967 if (enable == mInjectVSyncs) {
968 return NO_ERROR;
969 }
970
971 if (enable) {
972 mInjectVSyncs = enable;
973 ALOGV("VSync Injections enabled");
974 if (mVSyncInjector.get() == nullptr) {
975 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700976 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700977 }
978 mEventQueue.setEventThread(mInjectorEventThread);
979 } else {
980 mInjectVSyncs = enable;
981 ALOGV("VSync Injections disabled");
982 mEventQueue.setEventThread(mSFEventThread);
983 mVSyncInjector.clear();
984 }
985 return NO_ERROR;
986}
987
988status_t SurfaceFlinger::injectVSync(nsecs_t when) {
989 if (!mInjectVSyncs) {
990 ALOGE("VSync Injections not enabled");
991 return BAD_VALUE;
992 }
993 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
994 ALOGV("Injecting VSync inside SurfaceFlinger");
995 mVSyncInjector->onInjectSyncEvent(when);
996 }
997 return NO_ERROR;
998}
999
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001000// ----------------------------------------------------------------------------
1001
1002sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001003 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001004}
1005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001006// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001007
1008void SurfaceFlinger::waitForEvent() {
1009 mEventQueue.waitMessage();
1010}
1011
1012void SurfaceFlinger::signalTransaction() {
1013 mEventQueue.invalidate();
1014}
1015
1016void SurfaceFlinger::signalLayerUpdate() {
1017 mEventQueue.invalidate();
1018}
1019
1020void SurfaceFlinger::signalRefresh() {
1021 mEventQueue.refresh();
1022}
1023
1024status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001025 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001026 return mEventQueue.postMessage(msg, reltime);
1027}
1028
1029status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001030 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001031 status_t res = mEventQueue.postMessage(msg, reltime);
1032 if (res == NO_ERROR) {
1033 msg->wait();
1034 }
1035 return res;
1036}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001038void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001039 do {
1040 waitForEvent();
1041 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042}
1043
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001044void SurfaceFlinger::enableHardwareVsync() {
1045 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001046 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001047 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001048 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1049 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001051 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001052}
1053
Jesse Hall948fe0c2013-10-14 12:56:09 -07001054void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055 Mutex::Autolock _l(mHWVsyncLock);
1056
Jesse Hall948fe0c2013-10-14 12:56:09 -07001057 if (makeAvailable) {
1058 mHWVsyncAvailable = true;
1059 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001060 // Hardware vsync is not currently available, so abort the resync
1061 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001062 return;
1063 }
1064
Dan Stoza9e56aa02015-11-02 13:00:03 -08001065 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1066 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001067
1068 mPrimaryDispSync.reset();
1069 mPrimaryDispSync.setPeriod(period);
1070
1071 if (!mPrimaryHWVsyncEnabled) {
1072 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001073 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1074 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075 mPrimaryHWVsyncEnabled = true;
1076 }
1077}
1078
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 Mutex::Autolock _l(mHWVsyncLock);
1081 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001082 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1083 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001084 mPrimaryDispSync.endResync();
1085 mPrimaryHWVsyncEnabled = false;
1086 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087 if (makeUnavailable) {
1088 mHWVsyncAvailable = false;
1089 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090}
1091
Tim Murray4a4e4a22016-04-19 16:29:23 +00001092void SurfaceFlinger::resyncWithRateLimit() {
1093 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1094 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001095 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001096 }
1097}
1098
Steven Thomas3cfac282017-02-06 12:29:30 -08001099void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1100 nsecs_t timestamp) {
1101 Mutex::Autolock lock(mStateLock);
1102 // Ignore any vsyncs from the non-active hardware composer.
1103 if (composer != mHwc) {
1104 return;
1105 }
1106
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108
Jamie Gennisd1700752013-10-14 12:22:52 -07001109 { // Scope for the lock
1110 Mutex::Autolock _l(mHWVsyncLock);
1111 if (type == 0 && mPrimaryHWVsyncEnabled) {
1112 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001114 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001115
1116 if (needsHwVsync) {
1117 enableHardwareVsync();
1118 } else {
1119 disableHardwareVsync(false);
1120 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001121}
1122
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001123void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1124 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1125 *compositorTiming = mCompositorTiming;
1126}
1127
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1129 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1130 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1131 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001132
Dan Stoza9e56aa02015-11-02 13:00:03 -08001133 // All non-virtual displays are currently considered secure.
1134 bool isSecure = true;
1135
1136 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001137
1138 // When we're using the vr composer, the assumption is that we've
1139 // already created the IBinder object for the primary display.
1140 if (!mHwc->isUsingVrComposer()) {
1141 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1142 }
1143
Dan Stoza9e56aa02015-11-02 13:00:03 -08001144 wp<IBinder> token = mBuiltinDisplays[type];
1145
1146 sp<IGraphicBufferProducer> producer;
1147 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001148 BufferQueue::createBufferQueue(&producer, &consumer,
1149 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150
1151 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1152 DisplayDevice::DISPLAY_PRIMARY, consumer);
1153 sp<DisplayDevice> hw = new DisplayDevice(this,
1154 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1155 producer, mRenderEngine->getEGLConfig());
1156 mDisplays.add(token, hw);
1157 } else {
1158 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001159 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001160 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001161 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001162 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001163 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1164 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001165 }
1166 setTransactionFlags(eDisplayTransactionNeeded);
1167
Andy McFadden9e9689c2012-10-10 18:17:51 -07001168 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001169 }
Mathias Agopian86303202012-07-24 22:46:10 -07001170}
1171
Steven Thomas3cfac282017-02-06 12:29:30 -08001172void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1173 Mutex::Autolock lock(mStateLock);
1174 if (composer == mHwc) {
1175 repaintEverything();
1176 } else {
1177 // This isn't from our current hardware composer. If it's a callback
1178 // from the real composer, forward the refresh request to vr
1179 // flinger. Otherwise ignore it.
1180 if (!composer->isUsingVrComposer()) {
1181 mVrFlinger->OnHardwareComposerRefresh();
1182 }
1183 }
1184}
1185
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 getHwComposer().setVsyncEnabled(disp,
1189 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001190}
1191
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001192void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1193 for (size_t i = 0; i < layers.size(); ++i) {
1194 layers[i]->clearHwcLayers();
1195 }
1196}
1197
1198void SurfaceFlinger::resetHwc() {
1199 disableHardwareVsync(true);
1200 clearHwcLayers(mDrawingState.layersSortedByZ);
1201 clearHwcLayers(mCurrentState.layersSortedByZ);
1202 // Clear the drawing state so that the logic inside of
1203 // handleTransactionLocked will fire. It will determine the delta between
1204 // mCurrentState and mDrawingState and re-apply all changes when we make the
1205 // transition.
1206 mDrawingState.displays.clear();
1207 mDisplays.clear();
1208}
1209
1210void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001211 bool enteringVrMode = mEnterVrMode;
1212 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1213 return;
1214 }
1215 if (enteringVrMode && !mVrHwc) {
1216 // Construct new HWComposer without holding any locks.
1217 mVrHwc = new HWComposer(true);
1218 ALOGV("Vr HWC created");
1219 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001220 {
1221 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001222
1223 if (enteringVrMode) {
1224 // Start vrflinger thread, if it hasn't been started already.
1225 if (!mVrFlinger) {
1226 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1227 int err = mVrFlinger->Run(mHwc->getComposer());
1228 if (err != NO_ERROR) {
1229 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1230 mVrFlinger.reset();
1231 mEnterVrMode = false;
1232 return;
1233 }
1234 }
1235
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001236 resetHwc();
1237
1238 mHwc = mVrHwc;
1239 mVrFlinger->EnterVrMode();
1240 } else {
1241 mVrFlinger->ExitVrMode();
1242
1243 resetHwc();
1244
1245 mHwc = mRealHwc;
1246 enableHardwareVsync();
1247 }
1248
1249 mVisibleRegionsDirty = true;
1250 invalidateHwcGeometry();
1251 android_atomic_or(1, &mRepaintEverything);
1252 setTransactionFlags(eDisplayTransactionNeeded);
1253 }
1254 if (mVrHwc) {
1255 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1256 }
1257}
1258
Mathias Agopian4fec8732012-06-29 14:12:52 -07001259void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001260 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001262 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001263 // TODO(eieio): Tied to a conditional until SELinux issues
1264 // are resolved.
1265 if (mVrModeSupported) {
1266 updateVrMode();
1267 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001268
Dan Stoza50182882016-07-08 12:02:20 -07001269 bool frameMissed = !mHadClientComposition &&
1270 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001271 (mPreviousPresentFence->getSignalTime() ==
1272 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001273 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001274 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001275 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001276 signalLayerUpdate();
1277 break;
1278 }
1279
Dan Stoza6b9454d2014-11-07 16:00:59 -08001280 bool refreshNeeded = handleMessageTransaction();
1281 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001282 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001283 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001284 // Signal a refresh if a transaction modified the window state,
1285 // a new buffer was latched, or if HWC has requested a full
1286 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001287 signalRefresh();
1288 }
1289 break;
1290 }
1291 case MessageQueue::REFRESH: {
1292 handleMessageRefresh();
1293 break;
1294 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001295 }
1296}
1297
Dan Stoza6b9454d2014-11-07 16:00:59 -08001298bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001299 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001300 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001301 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001302 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001303 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001304 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001305}
1306
Dan Stoza6b9454d2014-11-07 16:00:59 -08001307bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001308 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001309 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001310}
1311
1312void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001313 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001314
Pablo Ceballos40845df2016-01-25 17:41:15 -08001315 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001316
Brian Andersond6927fb2016-07-23 23:37:30 -07001317 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001318 rebuildLayerStacks();
1319 setUpHWComposer();
1320 doDebugFlashRegions();
1321 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001322 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001323
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001324 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001325
1326 mHadClientComposition = false;
1327 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1328 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1329 mHadClientComposition = mHadClientComposition ||
1330 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1331 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001332
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001334}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001335
Mathias Agopiancd60f992012-08-16 16:28:27 -07001336void SurfaceFlinger::doDebugFlashRegions()
1337{
1338 // is debugging enabled
1339 if (CC_LIKELY(!mDebugRegion))
1340 return;
1341
1342 const bool repaintEverything = mRepaintEverything;
1343 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1344 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001345 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001346 // transform the dirty region into this screen's coordinate space
1347 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1348 if (!dirtyRegion.isEmpty()) {
1349 // redraw the whole screen
1350 doComposeSurfaces(hw, Region(hw->bounds()));
1351
1352 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001353 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001354 RenderEngine& engine(getRenderEngine());
1355 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1356
Mathias Agopianda27af92012-09-13 18:17:13 -07001357 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001358 }
1359 }
1360 }
1361
1362 postFramebuffer();
1363
1364 if (mDebugRegion > 1) {
1365 usleep(mDebugRegion * 1000);
1366 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001369 auto& displayDevice = mDisplays[displayId];
1370 if (!displayDevice->isDisplayOn()) {
1371 continue;
1372 }
1373
1374 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1376 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001377 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001378}
1379
Brian Andersond6927fb2016-07-23 23:37:30 -07001380void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001381{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382 ATRACE_CALL();
1383 ALOGV("preComposition");
1384
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001386 mDrawingState.traverseInZOrder([&](Layer* layer) {
1387 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001388 needExtraInvalidate = true;
1389 }
Robert Carr2047fae2016-11-28 14:09:09 -08001390 });
1391
Mathias Agopiancd60f992012-08-16 16:28:27 -07001392 if (needExtraInvalidate) {
1393 signalLayerUpdate();
1394 }
1395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::updateCompositorTiming(
1398 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1399 std::shared_ptr<FenceTime>& presentFenceTime) {
1400 // Update queue of past composite+present times and determine the
1401 // most recently known composite to present latency.
1402 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1403 nsecs_t compositeToPresentLatency = -1;
1404 while (!mCompositePresentTimes.empty()) {
1405 CompositePresentTime& cpt = mCompositePresentTimes.front();
1406 // Cached values should have been updated before calling this method,
1407 // which helps avoid duplicate syscalls.
1408 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1409 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1410 break;
1411 }
1412 compositeToPresentLatency = displayTime - cpt.composite;
1413 mCompositePresentTimes.pop();
1414 }
1415
1416 // Don't let mCompositePresentTimes grow unbounded, just in case.
1417 while (mCompositePresentTimes.size() > 16) {
1418 mCompositePresentTimes.pop();
1419 }
1420
1421 // Integer division and modulo round toward 0 not -inf, so we need to
1422 // treat negative and positive offsets differently.
1423 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1424 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1425 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1426
1427 // Snap the latency to a value that removes scheduling jitter from the
1428 // composition and present times, which often have >1ms of jitter.
1429 // Reducing jitter is important if an app attempts to extrapolate
1430 // something (such as user input) to an accurate diasplay time.
1431 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1432 // with (presentLatency % interval).
1433 nsecs_t snappedCompositeToPresentLatency = -1;
1434 if (compositeToPresentLatency >= 0) {
1435 nsecs_t bias = vsyncInterval / 2;
1436 int64_t extraVsyncs =
1437 (compositeToPresentLatency - idealLatency + bias) /
1438 vsyncInterval;
1439 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1440 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1441 }
1442
1443 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1444 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1445 mCompositorTiming.interval = vsyncInterval;
1446 if (snappedCompositeToPresentLatency >= 0) {
1447 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1448 }
1449}
1450
1451void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001452{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 ATRACE_CALL();
1454 ALOGV("postComposition");
1455
Brian Anderson3546a3f2016-07-14 11:51:14 -07001456 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001457 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001458 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001459 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001460 }
1461
Brian Andersond6927fb2016-07-23 23:37:30 -07001462 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001463
1464 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1465 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1466 glCompositionDoneFenceTime =
1467 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1468 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1469 } else {
1470 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1471 }
1472 mGlCompositionDoneTimeline.updateSignalTimes();
1473
1474 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1475 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1476 mDisplayTimeline.push(displayFenceTime);
1477 mDisplayTimeline.updateSignalTimes();
1478
1479 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1480 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1481 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1482 presentFenceTime = &displayFenceTime;
1483 } else {
1484 retireFenceTime = &displayFenceTime;
1485 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486
1487 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1488 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1489
1490 // We use the refreshStartTime which might be sampled a little later than
1491 // when we started doing work for this frame, but that should be okay
1492 // since updateCompositorTiming has snapping logic.
1493 updateCompositorTiming(
1494 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1495
Robert Carr2047fae2016-11-28 14:09:09 -08001496 mDrawingState.traverseInZOrder([&](Layer* layer) {
1497 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001498 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001499 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001500 recordBufferingStats(layer->getName().string(),
1501 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001502 }
Robert Carr2047fae2016-11-28 14:09:09 -08001503 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001504
Brian Anderson3d4039d2016-09-23 16:31:30 -07001505 if (displayFence->isValid()) {
1506 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001507 enableHardwareVsync();
1508 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001509 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001510 }
1511 }
1512
Andy McFadden5167ec62014-05-22 13:08:43 -07001513 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001514 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001515 enableHardwareVsync();
1516 }
1517 }
1518
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001519 if (mAnimCompositionPending) {
1520 mAnimCompositionPending = false;
1521
Brian Anderson3d4039d2016-09-23 16:31:30 -07001522 if (displayFenceTime->isValid()) {
1523 mAnimFrameTracker.setActualPresentFence(
1524 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001525 } else {
1526 // The HWC doesn't support present fences, so use the refresh
1527 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001528 nsecs_t presentTime =
1529 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001530 mAnimFrameTracker.setActualPresentTime(presentTime);
1531 }
1532 mAnimFrameTracker.advanceFrame();
1533 }
Dan Stozab90cf072015-03-05 11:05:59 -08001534
1535 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1536 return;
1537 }
1538
1539 nsecs_t currentTime = systemTime();
1540 if (mHasPoweredOff) {
1541 mHasPoweredOff = false;
1542 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001543 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001545 if (numPeriods < NUM_BUCKETS - 1) {
1546 mFrameBuckets[numPeriods] += elapsedTime;
1547 } else {
1548 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1549 }
1550 mTotalTime += elapsedTime;
1551 }
1552 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553}
1554
1555void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001556 ATRACE_CALL();
1557 ALOGV("rebuildLayerStacks");
1558
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001560 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1561 ATRACE_CALL();
1562 mVisibleRegionsDirty = false;
1563 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001564
Jeff Sharkey76488112017-02-27 14:15:18 -07001565 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1566 Region opaqueRegion;
1567 Region dirtyRegion;
1568 Vector<sp<Layer>> layersSortedByZ;
1569 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1570 const Transform& tr(displayDevice->getTransform());
1571 const Rect bounds(displayDevice->getBounds());
1572 if (displayDevice->isDisplayOn()) {
1573 computeVisibleRegions(
1574 displayDevice->getLayerStack(), dirtyRegion,
1575 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001576
Jeff Sharkey76488112017-02-27 14:15:18 -07001577 mDrawingState.traverseInZOrder([&](Layer* layer) {
1578 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1579 Region drawRegion(tr.transform(
1580 layer->visibleNonTransparentRegion));
1581 drawRegion.andSelf(bounds);
1582 if (!drawRegion.isEmpty()) {
1583 layersSortedByZ.add(layer);
1584 } else {
1585 // Clear out the HWC layer if this layer was
1586 // previously visible, but no longer is
1587 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1588 nullptr);
1589 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001590 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001591 // WM changes displayDevice->layerStack upon sleep/awake.
1592 // Here we make sure we delete the HWC layers even if
1593 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001594 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1595 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001596 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001597 });
1598 }
1599 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1600 displayDevice->undefinedRegion.set(bounds);
1601 displayDevice->undefinedRegion.subtractSelf(
1602 tr.transform(opaqueRegion));
1603 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001604 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001605 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001607
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001609 ATRACE_CALL();
1610 ALOGV("setUpHWComposer");
1611
Jesse Hall028dc8f2013-08-20 16:35:32 -07001612 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001613 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1614 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1615 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1616
1617 // If nothing has changed (!dirty), don't recompose.
1618 // If something changed, but we don't currently have any visible layers,
1619 // and didn't when we last did a composition, then skip it this time.
1620 // The second rule does two things:
1621 // - When all layers are removed from a display, we'll emit one black
1622 // frame, then nothing more until we get new layers.
1623 // - When a display is created with a private layer stack, we won't
1624 // emit any black frames until a layer is added to the layer stack.
1625 bool mustRecompose = dirty && !(empty && wasEmpty);
1626
1627 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1628 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1629 mustRecompose ? "doing" : "skipping",
1630 dirty ? "+" : "-",
1631 empty ? "+" : "-",
1632 wasEmpty ? "+" : "-");
1633
Dan Stoza71433162014-02-04 16:22:36 -08001634 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001635
1636 if (mustRecompose) {
1637 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1638 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001639 }
1640
Dan Stoza9e56aa02015-11-02 13:00:03 -08001641 // build the h/w work list
1642 if (CC_UNLIKELY(mGeometryInvalid)) {
1643 mGeometryInvalid = false;
1644 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1645 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1646 const auto hwcId = displayDevice->getHwcDisplayId();
1647 if (hwcId >= 0) {
1648 const Vector<sp<Layer>>& currentLayers(
1649 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001650 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001651 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001652 if (!layer->hasHwcLayer(hwcId)) {
1653 auto hwcLayer = mHwc->createLayer(hwcId);
1654 if (hwcLayer) {
1655 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1656 } else {
1657 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001659 }
1660 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001661
Robert Carrae060832016-11-28 10:51:00 -08001662 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001663 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001665 }
1666 }
1667 }
1668 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 }
Riley Andrews03414a12014-07-01 14:22:59 -07001670
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001671
1672 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1673
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 // Set the per-frame data
1675 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1676 auto& displayDevice = mDisplays[displayId];
1677 const auto hwcId = displayDevice->getHwcDisplayId();
1678 if (hwcId < 0) {
1679 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001680 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001681 if (colorMatrix != mPreviousColorMatrix) {
1682 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1683 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1684 "display %zd: %d", displayId, result);
1685 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1687 layer->setPerFrameData(displayDevice);
1688 }
1689 }
1690
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001691 mPreviousColorMatrix = colorMatrix;
1692
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001694 auto& displayDevice = mDisplays[displayId];
1695 if (!displayDevice->isDisplayOn()) {
1696 continue;
1697 }
1698
1699 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1701 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001702 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001704
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705void SurfaceFlinger::doComposition() {
1706 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ALOGV("doComposition");
1708
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001709 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001710 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001711 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001712 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 // transform the dirty region into this screen's coordinate space
1714 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001715
1716 // repaint the framebuffer (if needed)
1717 doDisplayComposition(hw, dirtyRegion);
1718
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719 hw->dirtyRegion.clear();
1720 hw->flip(hw->swapRegion);
1721 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001722 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001724 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725}
1726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001727void SurfaceFlinger::postFramebuffer()
1728{
Mathias Agopian841cde52012-03-01 15:44:37 -08001729 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001731
Mathias Agopiana44b0412011-10-16 18:46:35 -07001732 const nsecs_t now = systemTime();
1733 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001734
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1736 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001737 if (!displayDevice->isDisplayOn()) {
1738 continue;
1739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 const auto hwcId = displayDevice->getHwcDisplayId();
1741 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001742 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001743 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001744 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001745 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001746 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1747 sp<Fence> releaseFence = Fence::NO_FENCE;
1748 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1749 releaseFence = displayDevice->getClientTargetAcquireFence();
1750 } else {
1751 auto hwcLayer = layer->getHwcLayer(hwcId);
1752 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001753 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001754 layer->onLayerDisplayed(releaseFence);
1755 }
1756 if (hwcId >= 0) {
1757 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001758 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001759 }
1760
Mathias Agopiana44b0412011-10-16 18:46:35 -07001761 mLastSwapBufferTime = systemTime() - now;
1762 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001763
1764 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1765 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1766 logFrameStats();
1767 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001768}
1769
Mathias Agopian87baae12012-07-31 12:38:26 -07001770void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001771{
Mathias Agopian841cde52012-03-01 15:44:37 -08001772 ATRACE_CALL();
1773
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001774 // here we keep a copy of the drawing state (that is the state that's
1775 // going to be overwritten by handleTransactionLocked()) outside of
1776 // mStateLock so that the side-effects of the State assignment
1777 // don't happen with mStateLock held (which can cause deadlocks).
1778 State drawingState(mDrawingState);
1779
Mathias Agopianca4d3602011-05-19 15:38:14 -07001780 Mutex::Autolock _l(mStateLock);
1781 const nsecs_t now = systemTime();
1782 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001783
Mathias Agopianca4d3602011-05-19 15:38:14 -07001784 // Here we're guaranteed that some transaction flags are set
1785 // so we can call handleTransactionLocked() unconditionally.
1786 // We call getTransactionFlags(), which will also clear the flags,
1787 // with mStateLock held to guarantee that mCurrentState won't change
1788 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001789
Mathias Agopiane57f2922012-08-09 16:29:12 -07001790 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001791 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001792
Mathias Agopianca4d3602011-05-19 15:38:14 -07001793 mLastTransactionTime = systemTime() - now;
1794 mDebugInTransaction = 0;
1795 invalidateHwcGeometry();
1796 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001797}
1798
Mathias Agopian87baae12012-07-31 12:38:26 -07001799void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001800{
Dan Stoza7dde5992015-05-22 09:51:44 -07001801 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001802 mCurrentState.traverseInZOrder([](Layer* layer) {
1803 layer->notifyAvailableFrames();
1804 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001805
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806 /*
1807 * Traversal of the children
1808 * (perform the transaction for each of them if needed)
1809 */
1810
Mathias Agopian3559b072012-08-15 13:46:03 -07001811 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001812 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001814 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815
1816 const uint32_t flags = layer->doTransaction(0);
1817 if (flags & Layer::eVisibleRegion)
1818 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001819 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 }
1821
1822 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001823 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824 */
1825
Mathias Agopiane57f2922012-08-09 16:29:12 -07001826 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001827 // here we take advantage of Vector's copy-on-write semantics to
1828 // improve performance by skipping the transaction entirely when
1829 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001830 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1831 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001833 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001835 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001836
1837 // find the displays that were removed
1838 // (ie: in drawing state but not in current state)
1839 // also handle displays that changed
1840 // (ie: displays that are in both lists)
1841 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001842 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1843 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001844 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001845 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001846 // Call makeCurrent() on the primary display so we can
1847 // be sure that nothing associated with this display
1848 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001849 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001850 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001851 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1852 if (hw != NULL)
1853 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001854 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001855 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001856 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001857 } else {
1858 ALOGW("trying to remove the main display");
1859 }
1860 } else {
1861 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001862 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001863 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001864 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1865 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001866 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001867 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001868 // recreating the DisplayDevice, so we just remove it
1869 // from the drawing state, so that it get re-added
1870 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001871 sp<DisplayDevice> hw(getDisplayDevice(display));
1872 if (hw != NULL)
1873 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001874 mDisplays.removeItem(display);
1875 mDrawingState.displays.removeItemsAt(i);
1876 dc--; i--;
1877 // at this point we must loop to the next item
1878 continue;
1879 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001880
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001881 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001882 if (disp != NULL) {
1883 if (state.layerStack != draw[i].layerStack) {
1884 disp->setLayerStack(state.layerStack);
1885 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001886 if ((state.orientation != draw[i].orientation)
1887 || (state.viewport != draw[i].viewport)
1888 || (state.frame != draw[i].frame))
1889 {
1890 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001891 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001892 }
Michael Lentine47e45402014-07-18 15:34:25 -07001893 if (state.width != draw[i].width || state.height != draw[i].height) {
1894 disp->setDisplaySize(state.width, state.height);
1895 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001896 }
1897 }
1898 }
1899
1900 // find displays that were added
1901 // (ie: in current state but not in drawing state)
1902 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001903 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001904 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001905
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001906 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001907 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001908 sp<IGraphicBufferProducer> bqProducer;
1909 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001910 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1911 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001912
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001914 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001915 // Virtual displays without a surface are dormant:
1916 // they have external state (layer stack, projection,
1917 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001918 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001919
Dan Stoza8cf150a2016-08-02 10:27:31 -07001920 if (mUseHwcVirtualDisplays) {
1921 int width = 0;
1922 int status = state.surface->query(
1923 NATIVE_WINDOW_WIDTH, &width);
1924 ALOGE_IF(status != NO_ERROR,
1925 "Unable to query width (%d)", status);
1926 int height = 0;
1927 status = state.surface->query(
1928 NATIVE_WINDOW_HEIGHT, &height);
1929 ALOGE_IF(status != NO_ERROR,
1930 "Unable to query height (%d)", status);
1931 int intFormat = 0;
1932 status = state.surface->query(
1933 NATIVE_WINDOW_FORMAT, &intFormat);
1934 ALOGE_IF(status != NO_ERROR,
1935 "Unable to query format (%d)", status);
1936 auto format = static_cast<android_pixel_format_t>(
1937 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001938
Dan Stoza8cf150a2016-08-02 10:27:31 -07001939 mHwc->allocateVirtualDisplay(width, height, &format,
1940 &hwcId);
1941 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942
Dan Stoza5cf424b2016-05-20 14:02:39 -07001943 // TODO: Plumb requested format back up to consumer
1944
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 sp<VirtualDisplaySurface> vds =
1946 new VirtualDisplaySurface(*mHwc,
1947 hwcId, state.surface, bqProducer,
1948 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001949
1950 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001951 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001952 }
1953 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001954 ALOGE_IF(state.surface!=NULL,
1955 "adding a supported display, but rendering "
1956 "surface is provided (%p), ignoring it",
1957 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001958
1959 hwcId = state.type;
1960 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1961 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001962 }
1963
1964 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001965 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001966 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 state.type, hwcId, state.isSecure, display,
1968 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001969 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001970 hw->setLayerStack(state.layerStack);
1971 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001972 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001973 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001974 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001976 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001977 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001978 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001979 }
1980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001982 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983
Mathias Agopian84300952012-11-21 16:02:13 -08001984 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1985 // The transform hint might have changed for some layers
1986 // (either because a display has changed, or because a layer
1987 // as changed).
1988 //
1989 // Walk through all the layers in currentLayers,
1990 // and update their transform hint.
1991 //
1992 // If a layer is visible only on a single display, then that
1993 // display is used to calculate the hint, otherwise we use the
1994 // default display.
1995 //
1996 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1997 // the hint is set before we acquire a buffer from the surface texture.
1998 //
1999 // NOTE: layer transactions have taken place already, so we use their
2000 // drawing state. However, SurfaceFlinger's own transaction has not
2001 // happened yet, so we must use the current state layer list
2002 // (soon to become the drawing state list).
2003 //
2004 sp<const DisplayDevice> disp;
2005 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002006 bool first = true;
2007 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002008 // NOTE: we rely on the fact that layers are sorted by
2009 // layerStack first (so we don't have to traverse the list
2010 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002011 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002012 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002013 currentlayerStack = layerStack;
2014 // figure out if this layerstack is mirrored
2015 // (more than one display) if so, pick the default display,
2016 // if not, pick the only display it's on.
2017 disp.clear();
2018 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2019 sp<const DisplayDevice> hw(mDisplays[dpy]);
2020 if (hw->getLayerStack() == currentlayerStack) {
2021 if (disp == NULL) {
2022 disp = hw;
2023 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002024 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002025 break;
2026 }
2027 }
2028 }
2029 }
Chet Haase91d25932013-04-11 15:24:55 -07002030 if (disp == NULL) {
2031 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2032 // redraw after transform hint changes. See bug 8508397.
2033
2034 // could be null when this layer is using a layerStack
2035 // that is not visible on any display. Also can occur at
2036 // screen off/on times.
2037 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002038 }
Chet Haase91d25932013-04-11 15:24:55 -07002039 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002040
2041 first = false;
2042 });
Mathias Agopian84300952012-11-21 16:02:13 -08002043 }
2044
2045
Mathias Agopian3559b072012-08-15 13:46:03 -07002046 /*
2047 * Perform our own transaction if needed
2048 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002049
2050 if (mLayersAdded) {
2051 mLayersAdded = false;
2052 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002053 mVisibleRegionsDirty = true;
2054 }
2055
2056 // some layers might have been removed, so
2057 // we need to update the regions they're exposing.
2058 if (mLayersRemoved) {
2059 mLayersRemoved = false;
2060 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002061 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002062 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002063 // this layer is not visible anymore
2064 // TODO: we could traverse the tree from front to back and
2065 // compute the actual visible region
2066 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002067 Region visibleReg;
2068 visibleReg.set(layer->computeScreenBounds());
2069 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002070 }
Robert Carr2047fae2016-11-28 14:09:09 -08002071 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 }
2073
2074 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002075
2076 updateCursorAsync();
2077}
2078
2079void SurfaceFlinger::updateCursorAsync()
2080{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2082 auto& displayDevice = mDisplays[displayId];
2083 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002084 continue;
2085 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086
2087 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2088 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002089 }
2090 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091}
2092
2093void SurfaceFlinger::commitTransaction()
2094{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002095 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002097 for (const auto& l : mLayersPendingRemoval) {
2098 recordBufferingStats(l->getName().string(),
2099 l->getOccupancyHistory(true));
2100 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002101 }
2102 mLayersPendingRemoval.clear();
2103 }
2104
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002105 // If this transaction is part of a window animation then the next frame
2106 // we composite should be considered an animation as well.
2107 mAnimCompositionPending = mAnimTransactionPending;
2108
Mathias Agopian4fec8732012-06-29 14:12:52 -07002109 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002110 mDrawingState.traverseInZOrder([](Layer* layer) {
2111 layer->commitChildList();
2112 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002113 mTransactionPending = false;
2114 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002115 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116}
2117
Robert Carr2047fae2016-11-28 14:09:09 -08002118void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002119 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120{
Mathias Agopian841cde52012-03-01 15:44:37 -08002121 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124 Region aboveOpaqueLayers;
2125 Region aboveCoveredLayers;
2126 Region dirty;
2127
Mathias Agopian87baae12012-07-31 12:38:26 -07002128 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129
Robert Carr2047fae2016-11-28 14:09:09 -08002130 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002132 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133
Jesse Hall01e29052013-02-19 16:13:35 -08002134 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002135 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002136 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002137
Mathias Agopianab028732010-03-16 16:41:46 -07002138 /*
2139 * opaqueRegion: area of a surface that is fully opaque.
2140 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002141 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002142
2143 /*
2144 * visibleRegion: area of a surface that is visible on screen
2145 * and not fully transparent. This is essentially the layer's
2146 * footprint minus the opaque regions above it.
2147 * Areas covered by a translucent surface are considered visible.
2148 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002150
2151 /*
2152 * coveredRegion: area of a surface that is covered by all
2153 * visible regions above it (which includes the translucent areas).
2154 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002156
Jesse Halla8026d22012-09-25 13:25:04 -07002157 /*
2158 * transparentRegion: area of a surface that is hinted to be completely
2159 * transparent. This is only used to tell when the layer has no visible
2160 * non-transparent regions and can be removed from the layer list. It
2161 * does not affect the visibleRegion of this layer or any layers
2162 * beneath it. The hint may not be correct if apps don't respect the
2163 * SurfaceView restrictions (which, sadly, some don't).
2164 */
2165 Region transparentRegion;
2166
Mathias Agopianab028732010-03-16 16:41:46 -07002167
2168 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002169 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002170 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002171 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002173 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002174 if (!visibleRegion.isEmpty()) {
2175 // Remove the transparent area from the visible region
2176 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002177 if (tr.preserveRects()) {
2178 // transform the transparent region
2179 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002180 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002181 // transformation too complex, can't do the
2182 // transparent region optimization.
2183 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002184 }
Mathias Agopianab028732010-03-16 16:41:46 -07002185 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186
Mathias Agopianab028732010-03-16 16:41:46 -07002187 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002188 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002190 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2191 // the opaque region is the layer's footprint
2192 opaqueRegion = visibleRegion;
2193 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194 }
2195 }
2196
Mathias Agopianab028732010-03-16 16:41:46 -07002197 // Clip the covered region to the visible region
2198 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2199
2200 // Update aboveCoveredLayers for next (lower) layer
2201 aboveCoveredLayers.orSelf(visibleRegion);
2202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203 // subtract the opaque region covered by the layers above us
2204 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205
2206 // compute this layer's dirty region
2207 if (layer->contentDirty) {
2208 // we need to invalidate the whole region
2209 dirty = visibleRegion;
2210 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002211 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212 layer->contentDirty = false;
2213 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002214 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002215 * the exposed region consists of two components:
2216 * 1) what's VISIBLE now and was COVERED before
2217 * 2) what's EXPOSED now less what was EXPOSED before
2218 *
2219 * note that (1) is conservative, we start with the whole
2220 * visible region but only keep what used to be covered by
2221 * something -- which mean it may have been exposed.
2222 *
2223 * (2) handles areas that were not covered by anything but got
2224 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002225 */
Mathias Agopianab028732010-03-16 16:41:46 -07002226 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002227 const Region oldVisibleRegion = layer->visibleRegion;
2228 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002229 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2230 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231 }
2232 dirty.subtractSelf(aboveOpaqueLayers);
2233
2234 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002235 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236
Mathias Agopianab028732010-03-16 16:41:46 -07002237 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002239
Jesse Halla8026d22012-09-25 13:25:04 -07002240 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241 layer->setVisibleRegion(visibleRegion);
2242 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002243 layer->setVisibleNonTransparentRegion(
2244 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002245 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246
Mathias Agopian87baae12012-07-31 12:38:26 -07002247 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248}
2249
Mathias Agopian87baae12012-07-31 12:38:26 -07002250void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2251 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002252 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002253 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2254 if (hw->getLayerStack() == layerStack) {
2255 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002256 }
2257 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002258}
2259
Dan Stoza6b9454d2014-11-07 16:00:59 -08002260bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262 ALOGV("handlePageFlip");
2263
Brian Andersond6927fb2016-07-23 23:37:30 -07002264 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002265
Mathias Agopian4fec8732012-06-29 14:12:52 -07002266 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002268
2269 // Store the set of layers that need updates. This set must not change as
2270 // buffers are being latched, as this could result in a deadlock.
2271 // Example: Two producers share the same command stream and:
2272 // 1.) Layer 0 is latched
2273 // 2.) Layer 0 gets a new frame
2274 // 2.) Layer 1 gets a new frame
2275 // 3.) Layer 1 is latched.
2276 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2277 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002278 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002279 if (layer->hasQueuedFrame()) {
2280 frameQueued = true;
2281 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002282 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002283 } else {
2284 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002286 } else {
2287 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002288 }
Robert Carr2047fae2016-11-28 14:09:09 -08002289 });
2290
Dan Stoza9e56aa02015-11-02 13:00:03 -08002291 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002292 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002293 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002296
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002297 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002298
2299 // If we will need to wake up at some time in the future to deal with a
2300 // queued frame that shouldn't be displayed during this vsync period, wake
2301 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002302 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002303 signalLayerUpdate();
2304 }
2305
2306 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308}
2309
Mathias Agopianad456f92011-01-13 17:53:01 -08002310void SurfaceFlinger::invalidateHwcGeometry()
2311{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002313}
2314
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002315
Fabien Sanglard830b8472016-11-30 16:35:58 -08002316void SurfaceFlinger::doDisplayComposition(
2317 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002318 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319{
Dan Stoza71433162014-02-04 16:22:36 -08002320 // We only need to actually compose the display if:
2321 // 1) It is being handled by hardware composer, which may need this to
2322 // keep its virtual display state machine in sync, or
2323 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002324 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002325 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002326 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002327 return;
2328 }
2329
Dan Stoza9e56aa02015-11-02 13:00:03 -08002330 ALOGV("doDisplayComposition");
2331
Mathias Agopian87baae12012-07-31 12:38:26 -07002332 Region dirtyRegion(inDirtyRegion);
2333
Mathias Agopianb8a55602009-06-26 19:06:36 -07002334 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002335 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002338 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002339 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2340 // takes a rectangle, we must make sure to update that whole
2341 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002343 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002344 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002345 // We need to redraw the rectangle that will be updated
2346 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002347 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002348 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002350 } else {
2351 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002352 dirtyRegion.set(displayDevice->bounds());
2353 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354 }
2355 }
2356
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002359 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002360 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002361
2362 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002363 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364}
2365
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366bool SurfaceFlinger::doComposeSurfaces(
2367 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002368{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002370
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002372
2373 mat4 oldColorMatrix;
2374 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2375 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2376 if (applyColorMatrix) {
2377 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2378 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2379 }
2380
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2382 if (hasClientComposition) {
2383 ALOGV("hasClientComposition");
2384
2385 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002386 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002388 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2389 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2390 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2391 }
2392 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002393 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002394
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002395 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2397 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002398 // when using overlays, we assume a fully transparent framebuffer
2399 // NOTE: we could reduce how much we need to clear, for instance
2400 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002401 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002402 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002404 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002405 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002407
2408 // we remove the scissor part
2409 // we're left with the letterbox region
2410 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002412
2413 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002415
2416 // but limit it to the dirty region
2417 region.andSelf(dirty);
2418
Mathias Agopianb9494d52012-04-18 02:28:45 -07002419 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002420 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002421 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002423 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002424 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002425
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002427 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002428 // scissor on the main display. It should never be needed
2429 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002430 const Rect& bounds(displayDevice->getBounds());
2431 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002432 if (scissor != bounds) {
2433 // scissor doesn't match the screen's dimensions, so we
2434 // need to clear everything outside of it and enable
2435 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002436
Mathias Agopianf45c5102012-10-24 16:29:17 -07002437 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 const uint32_t height = displayDevice->getHeight();
2439 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002440 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002441 }
2442 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002443 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002444
Mathias Agopian85d751c2012-08-29 16:59:24 -07002445 /*
2446 * and then, render the layers targeted at the framebuffer
2447 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002448
Dan Stoza9e56aa02015-11-02 13:00:03 -08002449 ALOGV("Rendering client layers");
2450 const Transform& displayTransform = displayDevice->getTransform();
2451 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002452 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 bool firstLayer = true;
2454 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2455 const Region clip(dirty.intersect(
2456 displayTransform.transform(layer->visibleRegion)));
2457 ALOGV("Layer: %s", layer->getName().string());
2458 ALOGV(" Composition type: %s",
2459 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002460 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 switch (layer->getCompositionType(hwcId)) {
2462 case HWC2::Composition::Cursor:
2463 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002464 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002466 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2468 layer->isOpaque(state) && (state.alpha == 1.0f)
2469 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 // never clear the very first layer since we're
2471 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002472 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002473 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002474 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002475 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 case HWC2::Composition::Client: {
2477 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002478 break;
2479 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002481 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 } else {
2484 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002485 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002487 }
2488 } else {
2489 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002491 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002493 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002495 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002496 }
2497 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002498
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002499 if (applyColorMatrix) {
2500 getRenderEngine().setupColorTransform(oldColorMatrix);
2501 }
2502
Mathias Agopianf45c5102012-10-24 16:29:17 -07002503 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002505 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506}
2507
Fabien Sanglard830b8472016-11-30 16:35:58 -08002508void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2509 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002510 RenderEngine& engine(getRenderEngine());
2511 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512}
2513
Dan Stoza7d89d062015-04-30 13:29:25 -07002514status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002515 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002516 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002517 const sp<Layer>& lbc,
2518 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002519{
Dan Stoza7d89d062015-04-30 13:29:25 -07002520 // add this layer to the current state list
2521 {
2522 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002523 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002524 return NO_MEMORY;
2525 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526 if (parent == nullptr) {
2527 mCurrentState.layersSortedByZ.add(lbc);
2528 } else {
2529 parent->addChild(lbc);
2530 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002531 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 mLayersAdded = true;
2533 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002534 }
2535
Mathias Agopian96f08192010-06-02 23:28:45 -07002536 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002537 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002538
Dan Stoza7d89d062015-04-30 13:29:25 -07002539 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002540}
2541
Robert Carr9524cb32017-02-13 11:32:32 -08002542status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002543 Mutex::Autolock _l(mStateLock);
2544
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545 const auto& p = layer->getParent();
2546 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2547 mCurrentState.layersSortedByZ.remove(layer);
2548
Robert Carr136e2f62017-02-08 17:54:29 -08002549 // As a matter of normal operation, the LayerCleaner will produce a second
2550 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2551 // so we will succeed in promoting it, but it's already been removed
2552 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2553 // otherwise something has gone wrong and we are leaking the layer.
2554 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2556 layer->getName().string(),
2557 (p != nullptr) ? p->getName().string() : "no-parent");
2558 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002559 } else if (index < 0) {
2560 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002561 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562
2563 mLayersPendingRemoval.add(layer);
2564 mLayersRemoved = true;
2565 mNumLayers--;
2566 setTransactionFlags(eTransactionNeeded);
2567 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568}
2569
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002570uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002571 return android_atomic_release_load(&mTransactionFlags);
2572}
2573
Mathias Agopian3f844832013-08-07 21:24:32 -07002574uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2576}
2577
Mathias Agopian3f844832013-08-07 21:24:32 -07002578uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2580 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002581 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 }
2583 return old;
2584}
2585
Mathias Agopian8b33f032012-07-24 20:43:54 -07002586void SurfaceFlinger::setTransactionState(
2587 const Vector<ComposerState>& state,
2588 const Vector<DisplayState>& displays,
2589 uint32_t flags)
2590{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002591 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002592 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002593 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002594
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002595 if (flags & eAnimation) {
2596 // For window updates that are part of an animation we must wait for
2597 // previous animation "frames" to be handled.
2598 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002599 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002600 if (CC_UNLIKELY(err != NO_ERROR)) {
2601 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002602 // caller after a few seconds.
2603 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2604 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002605 mAnimTransactionPending = false;
2606 break;
2607 }
2608 }
2609 }
2610
Mathias Agopiane57f2922012-08-09 16:29:12 -07002611 size_t count = displays.size();
2612 for (size_t i=0 ; i<count ; i++) {
2613 const DisplayState& s(displays[i]);
2614 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002615 }
2616
Mathias Agopiane57f2922012-08-09 16:29:12 -07002617 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002618 for (size_t i=0 ; i<count ; i++) {
2619 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002620 // Here we need to check that the interface we're given is indeed
2621 // one of our own. A malicious client could give us a NULL
2622 // IInterface, or one of its own or even one of our own but a
2623 // different type. All these situations would cause us to crash.
2624 //
2625 // NOTE: it would be better to use RTTI as we could directly check
2626 // that we have a Client*. however, RTTI is disabled in Android.
2627 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002628 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002629 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002630 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002631 sp<Client> client( static_cast<Client *>(s.client.get()) );
2632 transactionFlags |= setClientStateLocked(client, s.state);
2633 }
2634 }
2635 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002636 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002637
Robert Carr2a7dbb42016-05-24 11:41:28 -07002638 // If a synchronous transaction is explicitly requested without any changes,
2639 // force a transaction anyway. This can be used as a flush mechanism for
2640 // previous async transactions.
2641 if (transactionFlags == 0 && (flags & eSynchronous)) {
2642 transactionFlags = eTransactionNeeded;
2643 }
2644
Mathias Agopian386aa982011-11-07 21:58:03 -08002645 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002646 if (mInterceptor.isEnabled()) {
2647 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2648 }
Irvel468051e2016-06-13 16:44:44 -07002649
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 // this triggers the transaction
2651 setTransactionFlags(transactionFlags);
2652
2653 // if this is a synchronous transaction, wait for it to take effect
2654 // before returning.
2655 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002656 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002657 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002658 if (flags & eAnimation) {
2659 mAnimTransactionPending = true;
2660 }
2661 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002662 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2663 if (CC_UNLIKELY(err != NO_ERROR)) {
2664 // just in case something goes wrong in SF, return to the
2665 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002666 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2667 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002668 break;
2669 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002670 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 }
2672}
2673
Mathias Agopiane57f2922012-08-09 16:29:12 -07002674uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2675{
Jesse Hall9a143922012-10-04 16:29:19 -07002676 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2677 if (dpyIdx < 0)
2678 return 0;
2679
Mathias Agopiane57f2922012-08-09 16:29:12 -07002680 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002681 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002682 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 const uint32_t what = s.what;
2684 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002685 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002686 disp.surface = s.surface;
2687 flags |= eDisplayTransactionNeeded;
2688 }
2689 }
2690 if (what & DisplayState::eLayerStackChanged) {
2691 if (disp.layerStack != s.layerStack) {
2692 disp.layerStack = s.layerStack;
2693 flags |= eDisplayTransactionNeeded;
2694 }
2695 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002696 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002697 if (disp.orientation != s.orientation) {
2698 disp.orientation = s.orientation;
2699 flags |= eDisplayTransactionNeeded;
2700 }
2701 if (disp.frame != s.frame) {
2702 disp.frame = s.frame;
2703 flags |= eDisplayTransactionNeeded;
2704 }
2705 if (disp.viewport != s.viewport) {
2706 disp.viewport = s.viewport;
2707 flags |= eDisplayTransactionNeeded;
2708 }
2709 }
Michael Lentine47e45402014-07-18 15:34:25 -07002710 if (what & DisplayState::eDisplaySizeChanged) {
2711 if (disp.width != s.width) {
2712 disp.width = s.width;
2713 flags |= eDisplayTransactionNeeded;
2714 }
2715 if (disp.height != s.height) {
2716 disp.height = s.height;
2717 flags |= eDisplayTransactionNeeded;
2718 }
2719 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002720 }
2721 return flags;
2722}
2723
2724uint32_t SurfaceFlinger::setClientStateLocked(
2725 const sp<Client>& client,
2726 const layer_state_t& s)
2727{
2728 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002729 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002730 if (layer != 0) {
2731 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002732 bool geometryAppliesWithResize =
2733 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002734 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002735 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002736 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002737 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 }
2739 if (what & layer_state_t::eLayerChanged) {
2740 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 const auto& p = layer->getParent();
2742 if (p == nullptr) {
2743 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2744 if (layer->setLayer(s.z) && idx >= 0) {
2745 mCurrentState.layersSortedByZ.removeAt(idx);
2746 mCurrentState.layersSortedByZ.add(layer);
2747 // we need traversal (state changed)
2748 // AND transaction (list changed)
2749 flags |= eTransactionNeeded|eTraversalNeeded;
2750 }
2751 } else {
2752 if (p->setChildLayer(layer, s.z)) {
2753 flags |= eTransactionNeeded|eTraversalNeeded;
2754 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002755 }
2756 }
2757 if (what & layer_state_t::eSizeChanged) {
2758 if (layer->setSize(s.w, s.h)) {
2759 flags |= eTraversalNeeded;
2760 }
2761 }
2762 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002764 flags |= eTraversalNeeded;
2765 }
2766 if (what & layer_state_t::eMatrixChanged) {
2767 if (layer->setMatrix(s.matrix))
2768 flags |= eTraversalNeeded;
2769 }
2770 if (what & layer_state_t::eTransparentRegionChanged) {
2771 if (layer->setTransparentRegionHint(s.transparentRegion))
2772 flags |= eTraversalNeeded;
2773 }
Dan Stoza23116082015-06-18 14:58:39 -07002774 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 if (layer->setFlags(s.flags, s.mask))
2776 flags |= eTraversalNeeded;
2777 }
2778 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002779 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 flags |= eTraversalNeeded;
2781 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002782 if (what & layer_state_t::eFinalCropChanged) {
2783 if (layer->setFinalCrop(s.finalCrop))
2784 flags |= eTraversalNeeded;
2785 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002786 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002787 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 // We only allow setting layer stacks for top level layers,
2789 // everything else inherits layer stack from its parent.
2790 if (layer->hasParent()) {
2791 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2792 layer->getName().string());
2793 } else if (idx < 0) {
2794 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2795 "that also does not appear in the top level layer list. Something"
2796 " has gone wrong.", layer->getName().string());
2797 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002798 mCurrentState.layersSortedByZ.removeAt(idx);
2799 mCurrentState.layersSortedByZ.add(layer);
2800 // we need traversal (state changed)
2801 // AND transaction (list changed)
2802 flags |= eTransactionNeeded|eTraversalNeeded;
2803 }
2804 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002805 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002806 if (s.barrierHandle != nullptr) {
2807 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2808 } else if (s.barrierGbp != nullptr) {
2809 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2810 if (authenticateSurfaceTextureLocked(gbp)) {
2811 const auto& otherLayer =
2812 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2813 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2814 } else {
2815 ALOGE("Attempt to defer transaction to to an"
2816 " unrecognized GraphicBufferProducer");
2817 }
2818 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002819 // We don't trigger a traversal here because if no other state is
2820 // changed, we don't want this to cause any more work
2821 }
Robert Carr1db73f62016-12-21 12:58:51 -08002822 if (what & layer_state_t::eReparentChildren) {
2823 if (layer->reparentChildren(s.reparentHandle)) {
2824 flags |= eTransactionNeeded|eTraversalNeeded;
2825 }
2826 }
Robert Carr9524cb32017-02-13 11:32:32 -08002827 if (what & layer_state_t::eDetachChildren) {
2828 layer->detachChildren();
2829 }
Robert Carrc3574f72016-03-24 12:19:32 -07002830 if (what & layer_state_t::eOverrideScalingModeChanged) {
2831 layer->setOverrideScalingMode(s.overrideScalingMode);
2832 // We don't trigger a traversal here because if no other state is
2833 // changed, we don't want this to cause any more work
2834 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002835 }
2836 return flags;
2837}
2838
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002839status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002840 const String8& name,
2841 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002842 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002843 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2844 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002846 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002847 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002848 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002849 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002850 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002851
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002852 status_t result = NO_ERROR;
2853
2854 sp<Layer> layer;
2855
Mathias Agopian3165cc22012-08-08 19:42:09 -07002856 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2857 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002858 result = createNormalLayer(client,
2859 name, w, h, flags, format,
2860 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002862 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002863 result = createDimLayer(client,
2864 name, w, h, flags,
2865 handle, gbp, &layer);
2866 break;
2867 default:
2868 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 break;
2870 }
2871
Dan Stoza7d89d062015-04-30 13:29:25 -07002872 if (result != NO_ERROR) {
2873 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002875
Albert Chaulk479c60c2017-01-27 14:21:34 -05002876 layer->setInfo(windowType, ownerUid);
2877
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002879 if (result != NO_ERROR) {
2880 return result;
2881 }
Irvelffc9efc2016-07-27 15:16:37 -07002882 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002883
2884 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002885 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886}
2887
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002888status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2889 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2890 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891{
2892 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002893 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 case PIXEL_FORMAT_TRANSPARENT:
2895 case PIXEL_FORMAT_TRANSLUCENT:
2896 format = PIXEL_FORMAT_RGBA_8888;
2897 break;
2898 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002899 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900 break;
2901 }
2902
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002903 *outLayer = new Layer(this, client, name, w, h, flags);
2904 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2905 if (err == NO_ERROR) {
2906 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002907 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002909
2910 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2911 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912}
2913
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002914status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2915 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2916 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002918 *outLayer = new LayerDim(this, client, name, w, h, flags);
2919 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002920 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002921 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002922}
2923
Mathias Agopianac9fa422013-02-11 16:40:36 -08002924status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925{
Robert Carr9524cb32017-02-13 11:32:32 -08002926 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002927 status_t err = NO_ERROR;
2928 sp<Layer> l(client->getLayerUser(handle));
2929 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002930 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002931 err = removeLayer(l);
2932 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2933 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002934 }
2935 return err;
2936}
2937
Mathias Agopian13127d82013-03-05 17:47:11 -08002938status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002939{
Mathias Agopian67106042013-03-14 19:18:13 -07002940 // called by ~LayerCleaner() when all references to the IBinder (handle)
2941 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002942 sp<Layer> l = layer.promote();
2943 if (l == nullptr) {
2944 // The layer has already been removed, carry on
2945 return NO_ERROR;
2946 } if (l->getParent() != nullptr) {
2947 // If we have a parent, then we can continue to live as long as it does.
2948 return NO_ERROR;
2949 }
2950 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951}
2952
Mathias Agopianb60314a2012-04-10 22:09:54 -07002953// ---------------------------------------------------------------------------
2954
Andy McFadden13a082e2012-08-24 10:16:42 -07002955void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002956 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002957 Vector<ComposerState> state;
2958 Vector<DisplayState> displays;
2959 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002960 d.what = DisplayState::eDisplayProjectionChanged |
2961 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002962 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002963 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002964 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002965 d.frame.makeInvalid();
2966 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002967 d.width = 0;
2968 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002969 displays.add(d);
2970 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002971 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002972
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2974 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002975 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002976
2977 {
2978 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2979 mCompositorTiming.interval = period;
2980 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002981}
2982
2983void SurfaceFlinger::initializeDisplays() {
2984 class MessageScreenInitialized : public MessageBase {
2985 SurfaceFlinger* flinger;
2986 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002987 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002988 virtual bool handler() {
2989 flinger->onInitializeDisplays();
2990 return true;
2991 }
2992 };
2993 sp<MessageBase> msg = new MessageScreenInitialized(this);
2994 postMessageAsync(msg); // we may be called from main thread, use async message
2995}
2996
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2998 int mode) {
2999 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3000 this);
3001 int32_t type = hw->getDisplayType();
3002 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003003
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003004 if (mode == currentMode) {
3005 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003006 return;
3007 }
3008
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003009 hw->setPowerMode(mode);
3010 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3011 ALOGW("Trying to set power mode for virtual display");
3012 return;
3013 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003014
Irvelffc9efc2016-07-27 15:16:37 -07003015 if (mInterceptor.isEnabled()) {
3016 Mutex::Autolock _l(mStateLock);
3017 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3018 if (idx < 0) {
3019 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3020 return;
3021 }
3022 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3023 }
3024
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003025 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003026 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003027 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003028 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3029 // FIXME: eventthread only knows about the main display right now
3030 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003031 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003034 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003035 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003036 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003037
3038 struct sched_param param = {0};
3039 param.sched_priority = 1;
3040 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3041 ALOGW("Couldn't set SCHED_FIFO on display on");
3042 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003044 // Turn off the display
3045 struct sched_param param = {0};
3046 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3047 ALOGW("Couldn't set SCHED_OTHER on display off");
3048 }
3049
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003050 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003051 disableHardwareVsync(true); // also cancels any in-progress resync
3052
Mathias Agopiancde87a32012-09-13 14:09:01 -07003053 // FIXME: eventthread only knows about the main display right now
3054 mEventThread->onScreenReleased();
3055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003057 getHwComposer().setPowerMode(type, mode);
3058 mVisibleRegionsDirty = true;
3059 // from this point on, SF will stop drawing on this display
3060 } else {
3061 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003062 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003063}
3064
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003065void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3066 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003067 SurfaceFlinger& mFlinger;
3068 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003069 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003070 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003071 MessageSetPowerMode(SurfaceFlinger& flinger,
3072 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3073 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003074 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003075 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003076 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003077 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003078 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003079 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003080 ALOGW("Attempt to set power mode = %d for virtual display",
3081 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003082 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003083 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003084 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003085 return true;
3086 }
3087 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003089 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003090}
3091
3092// ---------------------------------------------------------------------------
3093
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3095{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003097
Mathias Agopianbd115332013-04-18 16:41:04 -07003098 IPCThreadState* ipc = IPCThreadState::self();
3099 const int pid = ipc->getCallingPid();
3100 const int uid = ipc->getCallingUid();
3101 if ((uid != AID_SHELL) &&
3102 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003104 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003106 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003107 // (this would indicate SF is stuck, but we want to be able to
3108 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003109 status_t err = mStateLock.timedLock(s2ns(1));
3110 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003111 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003112 result.appendFormat(
3113 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3114 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003115 }
3116
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003117 bool dumpAll = true;
3118 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003119 size_t numArgs = args.size();
3120 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003121 if ((index < numArgs) &&
3122 (args[index] == String16("--list"))) {
3123 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003124 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003125 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003126 }
3127
3128 if ((index < numArgs) &&
3129 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003130 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003131 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003132 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003133 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003134
3135 if ((index < numArgs) &&
3136 (args[index] == String16("--latency-clear"))) {
3137 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003138 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003139 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003140 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003141
3142 if ((index < numArgs) &&
3143 (args[index] == String16("--dispsync"))) {
3144 index++;
3145 mPrimaryDispSync.dump(result);
3146 dumpAll = false;
3147 }
Dan Stozab90cf072015-03-05 11:05:59 -08003148
3149 if ((index < numArgs) &&
3150 (args[index] == String16("--static-screen"))) {
3151 index++;
3152 dumpStaticScreenStats(result);
3153 dumpAll = false;
3154 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003155
3156 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003157 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003158 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003159 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003160 dumpAll = false;
3161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003163
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003164 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003165 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003166 }
3167
Mathias Agopian9795c422009-08-26 16:36:26 -07003168 if (locked) {
3169 mStateLock.unlock();
3170 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 }
3172 write(fd, result.string(), result.size());
3173 return NO_ERROR;
3174}
3175
Dan Stozac7014012014-02-14 15:03:43 -08003176void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3177 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003178{
Robert Carr2047fae2016-11-28 14:09:09 -08003179 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003180 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003181 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003182}
3183
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003184void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003185 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003186{
3187 String8 name;
3188 if (index < args.size()) {
3189 name = String8(args[index]);
3190 index++;
3191 }
3192
Dan Stoza9e56aa02015-11-02 13:00:03 -08003193 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3194 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003195 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003196
3197 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003198 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003199 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003201 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003202 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003203 }
Robert Carr2047fae2016-11-28 14:09:09 -08003204 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003205 }
3206}
3207
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003208void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003209 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003210{
3211 String8 name;
3212 if (index < args.size()) {
3213 name = String8(args[index]);
3214 index++;
3215 }
3216
Robert Carr2047fae2016-11-28 14:09:09 -08003217 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003218 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003219 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003220 }
Robert Carr2047fae2016-11-28 14:09:09 -08003221 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003222
Svetoslavd85084b2014-03-20 10:28:31 -07003223 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003224}
3225
Jamie Gennis6547ff42013-07-16 20:12:42 -07003226// This should only be called from the main thread. Otherwise it would need
3227// the lock and should use mCurrentState rather than mDrawingState.
3228void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003229 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003230 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003231 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003232
3233 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3234}
3235
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003236void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003237{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003238 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003239 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3240
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003241 if (isLayerTripleBufferingDisabled())
3242 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003243
3244 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003245 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003246 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003247}
3248
Dan Stozab90cf072015-03-05 11:05:59 -08003249void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3250{
3251 result.appendFormat("Static screen stats:\n");
3252 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3253 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3254 float percent = 100.0f *
3255 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3256 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3257 b + 1, bucketTimeSec, percent);
3258 }
3259 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3260 float percent = 100.0f *
3261 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3262 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3263 NUM_BUCKETS - 1, bucketTimeSec, percent);
3264}
3265
Dan Stozae77c7662016-05-13 11:37:28 -07003266void SurfaceFlinger::recordBufferingStats(const char* layerName,
3267 std::vector<OccupancyTracker::Segment>&& history) {
3268 Mutex::Autolock lock(mBufferingStatsMutex);
3269 auto& stats = mBufferingStats[layerName];
3270 for (const auto& segment : history) {
3271 if (!segment.usedThirdBuffer) {
3272 stats.twoBufferTime += segment.totalTime;
3273 }
3274 if (segment.occupancyAverage < 1.0f) {
3275 stats.doubleBufferedTime += segment.totalTime;
3276 } else if (segment.occupancyAverage < 2.0f) {
3277 stats.tripleBufferedTime += segment.totalTime;
3278 }
3279 ++stats.numSegments;
3280 stats.totalTime += segment.totalTime;
3281 }
3282}
3283
Brian Andersond6927fb2016-07-23 23:37:30 -07003284void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3285 result.appendFormat("Layer frame timestamps:\n");
3286
3287 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3288 const size_t count = currentLayers.size();
3289 for (size_t i=0 ; i<count ; i++) {
3290 currentLayers[i]->dumpFrameEvents(result);
3291 }
3292}
3293
Dan Stozae77c7662016-05-13 11:37:28 -07003294void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3295 result.append("Buffering stats:\n");
3296 result.append(" [Layer name] <Active time> <Two buffer> "
3297 "<Double buffered> <Triple buffered>\n");
3298 Mutex::Autolock lock(mBufferingStatsMutex);
3299 typedef std::tuple<std::string, float, float, float> BufferTuple;
3300 std::map<float, BufferTuple, std::greater<float>> sorted;
3301 for (const auto& statsPair : mBufferingStats) {
3302 const char* name = statsPair.first.c_str();
3303 const BufferingStats& stats = statsPair.second;
3304 if (stats.numSegments == 0) {
3305 continue;
3306 }
3307 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3308 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3309 stats.totalTime;
3310 float doubleBufferRatio = static_cast<float>(
3311 stats.doubleBufferedTime) / stats.totalTime;
3312 float tripleBufferRatio = static_cast<float>(
3313 stats.tripleBufferedTime) / stats.totalTime;
3314 sorted.insert({activeTime, {name, twoBufferRatio,
3315 doubleBufferRatio, tripleBufferRatio}});
3316 }
3317 for (const auto& sortedPair : sorted) {
3318 float activeTime = sortedPair.first;
3319 const BufferTuple& values = sortedPair.second;
3320 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3321 std::get<0>(values).c_str(), activeTime,
3322 std::get<1>(values), std::get<2>(values),
3323 std::get<3>(values));
3324 }
3325 result.append("\n");
3326}
3327
3328
Mathias Agopian74d211a2013-04-22 16:55:35 +02003329void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3330 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003331{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003332 bool colorize = false;
3333 if (index < args.size()
3334 && (args[index] == String16("--color"))) {
3335 colorize = true;
3336 index++;
3337 }
3338
3339 Colorizer colorizer(colorize);
3340
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003341 // figure out if we're stuck somewhere
3342 const nsecs_t now = systemTime();
3343 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3344 const nsecs_t inTransaction(mDebugInTransaction);
3345 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3346 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3347
3348 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003349 * Dump library configuration.
3350 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003351
3352 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003353 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003354 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003355 appendSfConfigString(result);
3356 appendUiConfigString(result);
3357 appendGuiConfigString(result);
3358 result.append("\n");
3359
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003361 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003363 result.append(SyncFeatures::getInstance().toString());
3364 result.append("\n");
3365
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3367
Andy McFadden41d67d72014-04-25 16:58:34 -07003368 colorizer.bold(result);
3369 result.append("DispSync configuration: ");
3370 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003371 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003372 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003373 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003374 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003375 result.append("\n");
3376
Dan Stozab90cf072015-03-05 11:05:59 -08003377 // Dump static screen stats
3378 result.append("\n");
3379 dumpStaticScreenStats(result);
3380 result.append("\n");
3381
Dan Stozae77c7662016-05-13 11:37:28 -07003382 dumpBufferingStats(result);
3383
Andy McFadden4803b742012-09-24 19:07:20 -07003384 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003385 * Dump the visible layer list
3386 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003387 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003388 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003389 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003390 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003391 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003392 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003393
3394 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003395 * Dump Display state
3396 */
3397
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003398 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003399 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003400 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003401 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3402 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003403 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003404 }
3405
3406 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003407 * Dump SurfaceFlinger global state
3408 */
3409
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003410 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003411 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003412 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413
Mathias Agopian888c8222012-08-04 21:10:38 -07003414 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003415 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003416
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003417 colorizer.bold(result);
3418 result.appendFormat("EGL implementation : %s\n",
3419 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3420 colorizer.reset(result);
3421 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003422 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003423
Mathias Agopian875d8e12013-06-07 15:35:48 -07003424 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425
Mathias Agopian42977342012-08-05 00:40:46 -07003426 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3428 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003429 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430 " last eglSwapBuffers() time: %f us\n"
3431 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003432 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003433 " refresh-rate : %f fps\n"
3434 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003435 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003436 " gpu_to_cpu_unsupported : %d\n"
3437 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438 mLastSwapBufferTime/1000.0,
3439 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003440 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003441 1e9 / activeConfig->getVsyncPeriod(),
3442 activeConfig->getDpiX(),
3443 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003444 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003445
Mathias Agopian74d211a2013-04-22 16:55:35 +02003446 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003447 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448
Mathias Agopian74d211a2013-04-22 16:55:35 +02003449 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003450 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003451
3452 /*
3453 * VSYNC state
3454 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003455 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003456 result.append("\n");
3457
3458 /*
3459 * HWC layer minidump
3460 */
3461 for (size_t d = 0; d < mDisplays.size(); d++) {
3462 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3463 int32_t hwcId = displayDevice->getHwcDisplayId();
3464 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3465 continue;
3466 }
3467
3468 result.appendFormat("Display %d HWC layers:\n", hwcId);
3469 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003470 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003471 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003472 });
Dan Stozae22aec72016-08-01 13:20:59 -07003473 result.append("\n");
3474 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003475
3476 /*
3477 * Dump HWComposer state
3478 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003479 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003480 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003481 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003482 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003483 result.appendFormat(" h/w composer %s\n",
3484 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003485 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003486
3487 /*
3488 * Dump gralloc state
3489 */
3490 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3491 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003492}
3493
Mathias Agopian13127d82013-03-05 17:47:11 -08003494const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003495SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003496 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003497 wp<IBinder> dpy;
3498 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3499 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3500 dpy = mDisplays.keyAt(i);
3501 break;
3502 }
3503 }
3504 if (dpy == NULL) {
3505 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3506 // Just use the primary display so we have something to return
3507 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3508 }
3509 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003510}
3511
Keun young Park63f165f2012-08-31 10:53:36 -07003512bool SurfaceFlinger::startDdmConnection()
3513{
3514 void* libddmconnection_dso =
3515 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3516 if (!libddmconnection_dso) {
3517 return false;
3518 }
3519 void (*DdmConnection_start)(const char* name);
3520 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003521 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003522 if (!DdmConnection_start) {
3523 dlclose(libddmconnection_dso);
3524 return false;
3525 }
3526 (*DdmConnection_start)(getServiceName());
3527 return true;
3528}
3529
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003530status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 switch (code) {
3532 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003533 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003535 case CLEAR_ANIMATION_FRAME_STATS:
3536 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003538 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003539 {
3540 // codes that require permission check
3541 IPCThreadState* ipc = IPCThreadState::self();
3542 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003543 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003544 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003545 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003546 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003547 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003549 break;
3550 }
Robert Carr1db73f62016-12-21 12:58:51 -08003551 /*
3552 * Calling setTransactionState is safe, because you need to have been
3553 * granted a reference to Client* and Handle* to do anything with it.
3554 *
3555 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3556 */
3557 case SET_TRANSACTION_STATE:
3558 case CREATE_SCOPED_CONNECTION:
3559 {
3560 return OK;
3561 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003562 case CAPTURE_SCREEN:
3563 {
3564 // codes that require permission check
3565 IPCThreadState* ipc = IPCThreadState::self();
3566 const int pid = ipc->getCallingPid();
3567 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003568 if ((uid != AID_GRAPHICS) &&
3569 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003570 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003571 return PERMISSION_DENIED;
3572 }
3573 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 }
3575 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003576 return OK;
3577}
3578
3579status_t SurfaceFlinger::onTransact(
3580 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3581{
3582 status_t credentialCheck = CheckTransactCodeCredentials(code);
3583 if (credentialCheck != OK) {
3584 return credentialCheck;
3585 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003586
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003587 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3588 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003589 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003590 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003591 IPCThreadState* ipc = IPCThreadState::self();
3592 const int pid = ipc->getCallingPid();
3593 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003594 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003595 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 return PERMISSION_DENIED;
3597 }
3598 int n;
3599 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003600 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003601 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 return NO_ERROR;
3603 case 1002: // SHOW_UPDATES
3604 n = data.readInt32();
3605 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003606 invalidateHwcGeometry();
3607 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003610 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003611 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003613 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003614 setTransactionFlags(
3615 eTransactionNeeded|
3616 eDisplayTransactionNeeded|
3617 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003618 return NO_ERROR;
3619 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003620 case 1006:{ // send empty update
3621 signalRefresh();
3622 return NO_ERROR;
3623 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003624 case 1008: // toggle use of hw composer
3625 n = data.readInt32();
3626 mDebugDisableHWC = n ? 1 : 0;
3627 invalidateHwcGeometry();
3628 repaintEverything();
3629 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003630 case 1009: // toggle use of transform hint
3631 n = data.readInt32();
3632 mDebugDisableTransformHint = n ? 1 : 0;
3633 invalidateHwcGeometry();
3634 repaintEverything();
3635 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003637 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 reply->writeInt32(0);
3639 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003640 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003641 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 return NO_ERROR;
3643 case 1013: {
3644 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003645 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3646 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003647 return NO_ERROR;
3648 }
3649 case 1014: {
3650 // daltonize
3651 n = data.readInt32();
3652 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003653 case 1:
3654 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3655 break;
3656 case 2:
3657 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3658 break;
3659 case 3:
3660 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3661 break;
3662 default:
3663 mDaltonizer.setType(ColorBlindnessType::None);
3664 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003665 }
3666 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003667 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003668 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003669 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003670 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003671 invalidateHwcGeometry();
3672 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003673 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003675 case 1015: {
3676 // apply a color matrix
3677 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003678 if (n) {
3679 // color matrix is sent as mat3 matrix followed by vec3
3680 // offset, then packed into a mat4 where the last row is
3681 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003682 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003683 for (size_t j = 0; j < 4; j++) {
3684 mColorMatrix[i][j] = data.readFloat();
3685 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003686 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003687 } else {
3688 mColorMatrix = mat4();
3689 }
3690 invalidateHwcGeometry();
3691 repaintEverything();
3692 return NO_ERROR;
3693 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003694 // This is an experimental interface
3695 // Needs to be shifted to proper binder interface when we productize
3696 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003697 n = data.readInt32();
3698 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003699 return NO_ERROR;
3700 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003701 case 1017: {
3702 n = data.readInt32();
3703 mForceFullDamage = static_cast<bool>(n);
3704 return NO_ERROR;
3705 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003706 case 1018: { // Modify Choreographer's phase offset
3707 n = data.readInt32();
3708 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3709 return NO_ERROR;
3710 }
3711 case 1019: { // Modify SurfaceFlinger's phase offset
3712 n = data.readInt32();
3713 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3714 return NO_ERROR;
3715 }
Irvel468051e2016-06-13 16:44:44 -07003716 case 1020: { // Layer updates interceptor
3717 n = data.readInt32();
3718 if (n) {
3719 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003720 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003721 }
3722 else{
3723 ALOGV("Interceptor disabled");
3724 mInterceptor.disable();
3725 }
3726 return NO_ERROR;
3727 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003728 case 1021: { // Disable HWC virtual displays
3729 n = data.readInt32();
3730 mUseHwcVirtualDisplays = !n;
3731 return NO_ERROR;
3732 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 }
3734 }
3735 return err;
3736}
3737
Mathias Agopian53331da2011-08-22 21:44:41 -07003738void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003739 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003740 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003741}
3742
Mathias Agopian59119e62010-10-11 12:37:43 -07003743// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003744// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003745// ---------------------------------------------------------------------------
3746
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003747/* The code below is here to handle b/8734824
3748 *
3749 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003750 * from the surfaceflinger thread to the calling binder thread, where they
3751 * are executed. This allows the calling thread in the calling process to be
3752 * reused and not depend on having "enough" binder threads to handle the
3753 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003754 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003755class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003756 /* Parts of GraphicProducerWrapper are run on two different threads,
3757 * communicating by sending messages via Looper but also by shared member
3758 * data. Coherence maintenance is subtle and in places implicit (ugh).
3759 *
3760 * Don't rely on Looper's sendMessage/handleMessage providing
3761 * release/acquire semantics for any data not actually in the Message.
3762 * Data going from surfaceflinger to binder threads needs to be
3763 * synchronized explicitly.
3764 *
3765 * Barrier open/wait do provide release/acquire semantics. This provides
3766 * implicit synchronization for data coming back from binder to
3767 * surfaceflinger threads.
3768 */
3769
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003770 sp<IGraphicBufferProducer> impl;
3771 sp<Looper> looper;
3772 status_t result;
3773 bool exitPending;
3774 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003775 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003776 uint32_t code;
3777 Parcel const* data;
3778 Parcel* reply;
3779
3780 enum {
3781 MSG_API_CALL,
3782 MSG_EXIT
3783 };
3784
3785 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003786 * Called on surfaceflinger thread. This is called by our "fake"
3787 * BpGraphicBufferProducer. We package the data and reply Parcel and
3788 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003789 */
3790 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003791 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003792 this->code = code;
3793 this->data = &data;
3794 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003796 // if we've exited, we run the message synchronously right here.
3797 // note (JH): as far as I can tell from looking at the code, this
3798 // never actually happens. if it does, i'm not sure if it happens
3799 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003800 handleMessage(Message(MSG_API_CALL));
3801 } else {
3802 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003803 // Prevent stores to this->{code, data, reply} from being
3804 // reordered later than the construction of Message.
3805 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003806 looper->sendMessage(this, Message(MSG_API_CALL));
3807 barrier.wait();
3808 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003809 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003810 }
3811
3812 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003813 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 * call the real BpGraphicBufferProducer.
3815 */
3816 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003817 int what = message.what;
3818 // Prevent reads below from happening before the read from Message
3819 atomic_thread_fence(memory_order_acquire);
3820 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003821 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003823 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 exitRequested = true;
3825 }
3826 }
3827
3828public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003829 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003830 : impl(impl),
3831 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003832 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003833 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003834 exitRequested(false),
3835 code(0),
3836 data(NULL),
3837 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003838 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003839
Jesse Hallb154c422014-07-13 12:47:02 -07003840 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003841 status_t waitForResponse() {
3842 do {
3843 looper->pollOnce(-1);
3844 } while (!exitRequested);
3845 return result;
3846 }
3847
Jesse Hallb154c422014-07-13 12:47:02 -07003848 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003850 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003851 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003852 // Ensure this->result is visible to the binder thread before it
3853 // handles the message.
3854 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003855 looper->sendMessage(this, Message(MSG_EXIT));
3856 }
3857};
3858
3859
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003860status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3861 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003862 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003863 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003864 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003865
3866 if (CC_UNLIKELY(display == 0))
3867 return BAD_VALUE;
3868
3869 if (CC_UNLIKELY(producer == 0))
3870 return BAD_VALUE;
3871
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003872 // if we have secure windows on this display, never allow the screen capture
3873 // unless the producer interface is local (i.e.: we can take a screenshot for
3874 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003875 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003876
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003877 // Convert to surfaceflinger's internal rotation type.
3878 Transform::orientation_flags rotationFlags;
3879 switch (rotation) {
3880 case ISurfaceComposer::eRotateNone:
3881 rotationFlags = Transform::ROT_0;
3882 break;
3883 case ISurfaceComposer::eRotate90:
3884 rotationFlags = Transform::ROT_90;
3885 break;
3886 case ISurfaceComposer::eRotate180:
3887 rotationFlags = Transform::ROT_180;
3888 break;
3889 case ISurfaceComposer::eRotate270:
3890 rotationFlags = Transform::ROT_270;
3891 break;
3892 default:
3893 rotationFlags = Transform::ROT_0;
3894 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3895 break;
3896 }
3897
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003898 class MessageCaptureScreen : public MessageBase {
3899 SurfaceFlinger* flinger;
3900 sp<IBinder> display;
3901 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003902 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903 uint32_t reqWidth, reqHeight;
3904 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003905 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003906 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003908 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 public:
3910 MessageCaptureScreen(SurfaceFlinger* flinger,
3911 const sp<IBinder>& display,
3912 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003913 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003914 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003915 bool useIdentityTransform,
3916 Transform::orientation_flags rotation,
3917 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003918 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003919 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003920 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003921 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003922 rotation(rotation), result(PERMISSION_DENIED),
3923 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003924 {
3925 }
3926 status_t getResult() const {
3927 return result;
3928 }
3929 virtual bool handler() {
3930 Mutex::Autolock _l(flinger->mStateLock);
3931 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003932 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003933 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003934 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003935 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003936 return true;
3937 }
3938 };
3939
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003940 // this creates a "fake" BBinder which will serve as a "fake" remote
3941 // binder to receive the marshaled calls and forward them to the
3942 // real remote (a BpGraphicBufferProducer)
3943 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3944
3945 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3946 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003947 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003948 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003949 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003950 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003951
3952 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003953 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003955 }
3956 return res;
3957}
3958
Mathias Agopian180f10d2013-04-10 22:55:41 -07003959
3960void SurfaceFlinger::renderScreenImplLocked(
3961 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003962 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003963 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003964 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003965{
3966 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003967 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003968
3969 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003970 const int32_t hw_w = hw->getWidth();
3971 const int32_t hw_h = hw->getHeight();
3972 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003973 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003974
Dan Stozac1879002014-05-22 15:59:05 -07003975 // if a default or invalid sourceCrop is passed in, set reasonable values
3976 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3977 !sourceCrop.isValid()) {
3978 sourceCrop.setLeftTop(Point(0, 0));
3979 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3980 }
3981
3982 // ensure that sourceCrop is inside screen
3983 if (sourceCrop.left < 0) {
3984 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3985 }
Dan Stozabe31f442014-06-11 11:20:54 -07003986 if (sourceCrop.right > hw_w) {
3987 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003988 }
3989 if (sourceCrop.top < 0) {
3990 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3991 }
Dan Stozabe31f442014-06-11 11:20:54 -07003992 if (sourceCrop.bottom > hw_h) {
3993 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003994 }
3995
Mathias Agopian180f10d2013-04-10 22:55:41 -07003996 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003997 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003998
3999 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004000 engine.setViewportAndProjection(
4001 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004002 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004003
4004 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004005 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004006
Robert Carr1f0a16a2016-10-24 16:27:39 -07004007 // We loop through the first level of layers without traversing,
4008 // as we need to interpret min/max layer Z in the top level Z space.
4009 for (const auto& layer : mDrawingState.layersSortedByZ) {
4010 if (layer->getLayerStack() != hw->getLayerStack()) {
4011 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004012 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004013 const Layer::State& state(layer->getDrawingState());
4014 if (state.z < minLayerZ || state.z > maxLayerZ) {
4015 continue;
4016 }
4017 layer->traverseInZOrder([&](Layer* layer) {
4018 if (!layer->isVisible()) {
4019 return;
4020 }
4021 if (filtering) layer->setFiltering(true);
4022 layer->draw(hw, useIdentityTransform);
4023 if (filtering) layer->setFiltering(false);
4024 });
4025 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004026
Mathias Agopian931bda12013-08-28 18:11:46 -07004027 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004028}
4029
4030
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004031status_t SurfaceFlinger::captureScreenImplLocked(
4032 const sp<const DisplayDevice>& hw,
4033 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004034 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004035 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004036 bool useIdentityTransform, Transform::orientation_flags rotation,
4037 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004038{
4039 ATRACE_CALL();
4040
Mathias Agopian180f10d2013-04-10 22:55:41 -07004041 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004042 uint32_t hw_w = hw->getWidth();
4043 uint32_t hw_h = hw->getHeight();
4044
4045 if (rotation & Transform::ROT_90) {
4046 std::swap(hw_w, hw_h);
4047 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004048
Mathias Agopian180f10d2013-04-10 22:55:41 -07004049 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4050 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4051 reqWidth, reqHeight, hw_w, hw_h);
4052 return BAD_VALUE;
4053 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004054
Mathias Agopian180f10d2013-04-10 22:55:41 -07004055 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4056 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4057
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004058 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004060 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004061 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4062 (state.z < minLayerZ || state.z > maxLayerZ)) {
4063 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004064 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004065 layer->traverseInZOrder([&](Layer *layer) {
4066 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4067 layer->isSecure());
4068 });
4069 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004070
4071 if (!isLocalScreenshot && secureLayerIsVisible) {
4072 ALOGW("FB is protected: PERMISSION_DENIED");
4073 return PERMISSION_DENIED;
4074 }
4075
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004076 // create a surface (because we're a producer, and we need to
4077 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004078 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004079
4080 // Put the screenshot Surface into async mode so that
4081 // Layer::headFenceHasSignaled will always return true and we'll latch the
4082 // first buffer regardless of whether or not its acquire fence has
4083 // signaled. This is needed to avoid a race condition in the rotation
4084 // animation. See b/30209608
4085 sur->setAsyncMode(true);
4086
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004087 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004088
Michael Lentine5a16a622015-05-21 13:48:24 -07004089 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4090 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004091 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4092 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004093
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004094 int err = 0;
4095 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004096 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004097 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4098 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004099
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004100 if (err == NO_ERROR) {
4101 ANativeWindowBuffer* buffer;
4102 /* TODO: Once we have the sync framework everywhere this can use
4103 * server-side waits on the fence that dequeueBuffer returns.
4104 */
4105 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4106 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004107 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004108 // create an EGLImage from the buffer so we can later
4109 // turn it into a texture
4110 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4111 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4112 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004113 // this binds the given EGLImage as a framebuffer for the
4114 // duration of this scope.
4115 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4116 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004117 // this will in fact render into our dequeued buffer
4118 // via an FBO, which means we didn't have to create
4119 // an EGLSurface and therefore we're not
4120 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004121 renderScreenImplLocked(
4122 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4123 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004124
Riley Andrews86639902014-08-15 12:27:24 -07004125 // Attempt to create a sync khr object that can produce a sync point. If that
4126 // isn't available, create a non-dupable sync object in the fallback path and
4127 // wait on it directly.
4128 EGLSyncKHR sync;
4129 if (!DEBUG_SCREENSHOTS) {
4130 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004131 // native fence fd will not be populated until flush() is done.
4132 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004133 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004134 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004135 }
Riley Andrews86639902014-08-15 12:27:24 -07004136 if (sync != EGL_NO_SYNC_KHR) {
4137 // get the sync fd
4138 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4139 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4140 ALOGW("captureScreen: failed to dup sync khr object");
4141 syncFd = -1;
4142 }
4143 eglDestroySyncKHR(mEGLDisplay, sync);
4144 } else {
4145 // fallback path
4146 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4147 if (sync != EGL_NO_SYNC_KHR) {
4148 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4149 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4150 EGLint eglErr = eglGetError();
4151 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4152 ALOGW("captureScreen: fence wait timed out");
4153 } else {
4154 ALOGW_IF(eglErr != EGL_SUCCESS,
4155 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4156 }
4157 eglDestroySyncKHR(mEGLDisplay, sync);
4158 } else {
4159 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4160 }
4161 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004162 if (DEBUG_SCREENSHOTS) {
4163 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4164 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4165 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4166 hw, minLayerZ, maxLayerZ);
4167 delete [] pixels;
4168 }
4169
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004170 } else {
4171 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4172 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004173 window->cancelBuffer(window, buffer, syncFd);
4174 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004175 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004176 // destroy our image
4177 eglDestroyImageKHR(mEGLDisplay, image);
4178 } else {
4179 result = BAD_VALUE;
4180 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004181 if (buffer) {
4182 // queueBuffer takes ownership of syncFd
4183 result = window->queueBuffer(window, buffer, syncFd);
4184 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004185 }
4186 } else {
4187 result = BAD_VALUE;
4188 }
4189 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4190 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004191
Mathias Agopian74c40c02010-09-29 13:02:36 -07004192 return result;
4193}
4194
Mathias Agopiand5556842013-09-19 17:08:37 -07004195void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004196 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004197 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004198 for (size_t y=0 ; y<h ; y++) {
4199 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4200 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004201 if (p[x] != 0xFF000000) return;
4202 }
4203 }
4204 ALOGE("*** we just took a black screenshot ***\n"
4205 "requested minz=%d, maxz=%d, layerStack=%d",
4206 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004207
Robert Carr2047fae2016-11-28 14:09:09 -08004208 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004209 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004210 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004211 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4212 state.z <= maxLayerZ) {
4213 layer->traverseInZOrder([&](Layer* layer) {
4214 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4215 layer->isVisible() ? '+' : '-',
4216 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004217 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004218 i++;
4219 });
4220 }
4221 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004222 }
4223}
4224
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004225// ---------------------------------------------------------------------------
4226
Robert Carr2047fae2016-11-28 14:09:09 -08004227void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4228 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004229}
4230
Robert Carr2047fae2016-11-28 14:09:09 -08004231void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4232 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004233}
4234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004235}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004236
4237
4238#if defined(__gl_h_)
4239#error "don't include gl/gl.h in this file"
4240#endif
4241
4242#if defined(__gl2_h_)
4243#error "don't include gl2/gl2.h in this file"
4244#endif