blob: 06dd9037ffb4d9efbabe25827c613e1b29fa990c [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"
Jin Qian7480c062017-03-21 00:04:15 +000076#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Mathias Agopian99b49842011-06-27 16:05:52 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700123 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700125 mTransactionPending(false),
126 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700127 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700128 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700129 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800130 mHwc(nullptr),
131 mRealHwc(nullptr),
132 mVrHwc(nullptr),
133 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800135 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800138 mAnimCompositionPending(false),
Jin Qian7480c062017-03-21 00:04:15 +0000139 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700141 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700142 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700143 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700144 mDebugInSwapBuffers(0),
145 mLastSwapBufferTime(0),
146 mDebugInTransaction(0),
147 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700148 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700149 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800150 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000151 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700152 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700153 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800154 mHasColorMatrix(false),
155 mHasPoweredOff(false),
156 mFrameBuckets(),
157 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700158 mLastSwapTime(0),
Jin Qian7480c062017-03-21 00:04:15 +0000159 mNumLayers(0)
160#ifdef USE_HWC2
161 ,mEnterVrMode(false)
162#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187 // debugging stuff...
188 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700189
Jin Qian7480c062017-03-21 00:04:15 +0000190 // TODO (urbanus): remove once b/35319396 is fixed.
191 property_get("ro.boot.vr", value, "0");
192 mVrModeSupported = atoi(value);
193
Mathias Agopianb4b17302013-03-20 18:36:41 -0700194 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700195 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 property_get("debug.sf.showupdates", value, "0");
198 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200 property_get("debug.sf.ddms", value, "0");
201 mDebugDDMS = atoi(value);
202 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700203 if (!startDdmConnection()) {
204 // start failed, and DDMS debugging not enabled
205 mDebugDDMS = 0;
206 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700208 ALOGI_IF(mDebugRegion, "showupdates enabled");
209 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700210
211 property_get("debug.sf.disable_backpressure", value, "0");
212 mPropagateBackpressure = !atoi(value);
213 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700214
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800215 property_get("debug.sf.enable_hwc_vds", value, "0");
216 mUseHwcVirtualDisplays = atoi(value);
217 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800218
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800219 property_get("ro.sf.disable_triple_buffer", value, "1");
220 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800221 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222}
223
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224void SurfaceFlinger::onFirstRef()
225{
226 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800227}
228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229SurfaceFlinger::~SurfaceFlinger()
230{
Mathias Agopiana4912602012-07-12 14:25:33 -0700231 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
232 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
233 eglTerminate(display);
Jin Qian7480c062017-03-21 00:04:15 +0000234
235 if (mVrStateCallbacks.get()) {
236 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
237 defaultServiceManager()->checkService(String16("vrmanager")));
238 if (vrManagerService.get()) {
239 vrManagerService->unregisterListener(mVrStateCallbacks);
240 }
241 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242}
243
Dan Stozac7014012014-02-14 15:03:43 -0800244void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245{
246 // the window manager died on us. prepare its eulogy.
247
Andy McFadden13a082e2012-08-24 10:16:42 -0700248 // restore initial conditions (default device unblank, etc)
249 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250
251 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700252 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253}
254
Robert Carr1db73f62016-12-21 12:58:51 -0800255static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700256 status_t err = client->initCheck();
257 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 }
Robert Carr1db73f62016-12-21 12:58:51 -0800260 return nullptr;
261}
262
263sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
264 return initClient(new Client(this));
265}
266
267sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
268 const sp<IGraphicBufferProducer>& gbp) {
269 if (authenticateSurfaceTexture(gbp) == false) {
270 return nullptr;
271 }
272 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
273 if (layer == nullptr) {
274 return nullptr;
275 }
276
277 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700280sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
281 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700282{
283 class DisplayToken : public BBinder {
284 sp<SurfaceFlinger> flinger;
285 virtual ~DisplayToken() {
286 // no more references, this display must be terminated
287 Mutex::Autolock _l(flinger->mStateLock);
288 flinger->mCurrentState.displays.removeItem(this);
289 flinger->setTransactionFlags(eDisplayTransactionNeeded);
290 }
291 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700292 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293 : flinger(flinger) {
294 }
295 };
296
297 sp<BBinder> token = new DisplayToken(this);
298
299 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700300 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700301 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700303 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700304 return token;
305}
306
Jesse Hall6c913be2013-08-08 12:15:49 -0700307void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
308 Mutex::Autolock _l(mStateLock);
309
310 ssize_t idx = mCurrentState.displays.indexOfKey(display);
311 if (idx < 0) {
312 ALOGW("destroyDisplay: invalid display token");
313 return;
314 }
315
316 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
317 if (!info.isVirtualDisplay()) {
318 ALOGE("destroyDisplay called for non-virtual display");
319 return;
320 }
Irvelffc9efc2016-07-27 15:16:37 -0700321 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700322 mCurrentState.displays.removeItemsAt(idx);
323 setTransactionFlags(eDisplayTransactionNeeded);
324}
325
Jesse Hall692c7232012-11-08 15:41:56 -0800326void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800327 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800328 ALOGW_IF(mBuiltinDisplays[type],
329 "Overwriting display token for display type %d", type);
330 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800331 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700332 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800333 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700334 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800335}
336
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700338 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
340 return NULL;
341 }
Jesse Hall692c7232012-11-08 15:41:56 -0800342 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343}
344
Romain Guyf8b4ca52017-03-16 18:39:20 +0000345sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
346{
347 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
348 return gba;
349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351void SurfaceFlinger::bootFinished()
352{
Wei Wangb254fa32017-01-31 17:43:23 -0800353 if (mStartBootAnimThread->join() != NO_ERROR) {
354 ALOGE("Join StartBootAnimThread failed!");
355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 const nsecs_t now = systemTime();
357 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000358 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700359 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700360
361 // wait patiently for the window manager death
362 const String16 name("window");
363 sp<IBinder> window(defaultServiceManager()->getService(name));
364 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700365 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700366 }
367
368 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700369 // formerly we would just kill the process, but we now ask it to exit so it
370 // can choose where to stop the animation.
371 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700372
373 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
374 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
375 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Jin Qian7480c062017-03-21 00:04:15 +0000376
377 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
378 defaultServiceManager()->checkService(String16("vrmanager")));
379 if (vrManagerService.get()) {
380 mVrStateCallbacks = new VrStateCallbacks(*this);
381 vrManagerService->registerListener(mVrStateCallbacks);
382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian3f844832013-08-07 21:24:32 -0700385void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 RenderEngine& engine;
388 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
391 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 }
393 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700394 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 return true;
396 }
397 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700399}
400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401class DispSyncSource : public VSyncSource, private DispSync::Callback {
402public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700403 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 const char* name) :
405 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700406 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700407 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
409 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700410 mDispSync(dispSync),
411 mCallbackMutex(),
412 mCallback(),
413 mVsyncMutex(),
414 mPhaseOffset(phaseOffset),
415 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700416
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 virtual ~DispSyncSource() {}
418
419 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000422 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error registering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 } else {
430 status_t err = mDispSync->removeEventListener(
431 static_cast<DispSync::Callback*>(this));
432 if (err != NO_ERROR) {
433 ALOGE("error unregistering vsync callback: %s (%d)",
434 strerror(-err), err);
435 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 }
440
441 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 mCallback = callback;
444 }
445
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 virtual void setPhaseOffset(nsecs_t phaseOffset) {
447 Mutex::Autolock lock(mVsyncMutex);
448
449 // Normalize phaseOffset to [0, period)
450 auto period = mDispSync->getPeriod();
451 phaseOffset %= period;
452 if (phaseOffset < 0) {
453 // If we're here, then phaseOffset is in (-period, 0). After this
454 // operation, it will be in (0, period)
455 phaseOffset += period;
456 }
457 mPhaseOffset = phaseOffset;
458
459 // If we're not enabled, we don't need to mess with the listeners
460 if (!mEnabled) {
461 return;
462 }
463
464 // Remove the listener with the old offset
465 status_t err = mDispSync->removeEventListener(
466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error unregistering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471
472 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
479 }
480
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481private:
482 virtual void onDispSyncEvent(nsecs_t when) {
483 sp<VSyncSource::Callback> callback;
484 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 callback = mCallback;
487
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 if (mTraceVsync) {
489 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700490 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492 }
493
494 if (callback != NULL) {
495 callback->onVSyncEvent(when);
496 }
497 }
498
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 const char* const mName;
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 int mValue;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700504 const String8 mVsyncOnLabel;
505 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508
509 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511
512 Mutex mVsyncMutex; // Protects the following
513 nsecs_t mPhaseOffset;
514 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515};
516
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700517class InjectVSyncSource : public VSyncSource {
518public:
519 InjectVSyncSource() {}
520
521 virtual ~InjectVSyncSource() {}
522
523 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback = callback;
526 }
527
528 virtual void onInjectSyncEvent(nsecs_t when) {
529 std::lock_guard<std::mutex> lock(mCallbackMutex);
530 mCallback->onVSyncEvent(when);
531 }
532
533 virtual void setVSyncEnabled(bool) {}
534 virtual void setPhaseOffset(nsecs_t) {}
535
536private:
537 std::mutex mCallbackMutex; // Protects the following
538 sp<VSyncSource::Callback> mCallback;
539};
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700542 ALOGI( "SurfaceFlinger's main thread ready to run. "
543 "Initializing graphics H/W...");
544
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900545 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 { // Autolock scope
548 Mutex::Autolock _l(mStateLock);
549
550 // initialize EGL for the default display
551 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
552 eglInitialize(mEGLDisplay, NULL, NULL);
553
554 // start the EventThread
555 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
556 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700557 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
559 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700560 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 mEventQueue.setEventThread(mSFEventThread);
562
Tim Murrayacff43d2016-07-29 13:57:24 -0700563 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700564 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700565 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700566 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
567 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
568 }
569
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 // Get a RenderEngine for the given display / config (can't fail)
571 mRenderEngine = RenderEngine::create(mEGLDisplay,
572 HAL_PIXEL_FORMAT_RGBA_8888);
573 }
574
575 // Drop the state lock while we initialize the hardware composer. We drop
576 // the lock because on creation, it will call back into SurfaceFlinger to
577 // initialize the primary display.
Jin Qian7480c062017-03-21 00:04:15 +0000578 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800579 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800580 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
582
Jesse Hall692c7232012-11-08 15:41:56 -0800583 Mutex::Autolock _l(mStateLock);
584
Mathias Agopian875d8e12013-06-07 15:35:48 -0700585 // retrieve the EGL context that was selected/created
586 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700587
Mathias Agopianda27af92012-09-13 18:17:13 -0700588 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
589 "couldn't create EGLContext");
590
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591 // make the GLContext current so that we can create textures when creating
592 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700593 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
594
Jamie Gennisd1700752013-10-14 12:22:52 -0700595 mEventControlThread = new EventControlThread(this);
596 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
597
Mathias Agopian92a979a2012-08-02 18:32:23 -0700598 // initialize our drawing state
599 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700600
Andy McFadden13a082e2012-08-24 10:16:42 -0700601 // set initial conditions (e.g. unblank default device)
602 initializeDisplays();
603
Dan Stoza4e637772016-07-28 13:31:51 -0700604 mRenderEngine->primeCache();
605
Wei Wangb254fa32017-01-31 17:43:23 -0800606 mStartBootAnimThread = new StartBootAnimThread();
607 if (mStartBootAnimThread->Start() != NO_ERROR) {
608 ALOGE("Run StartBootAnimThread failed!");
609 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800610
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700612}
613
Mathias Agopiana67e4182012-06-19 17:26:12 -0700614void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800615 // Start boot animation service by setting a property mailbox
616 // if property setting thread is already running, Start() will be just a NOP
617 mStartBootAnimThread->Start();
618 // Wait until property was set
619 if (mStartBootAnimThread->join() != NO_ERROR) {
620 ALOGE("Join StartBootAnimThread failed!");
621 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700622}
623
Mathias Agopian875d8e12013-06-07 15:35:48 -0700624size_t SurfaceFlinger::getMaxTextureSize() const {
625 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700626}
627
Mathias Agopian875d8e12013-06-07 15:35:48 -0700628size_t SurfaceFlinger::getMaxViewportDims() const {
629 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700630}
631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800632// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800633
Jamie Gennis582270d2011-08-17 18:19:00 -0700634bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800635 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800636 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800637 return authenticateSurfaceTextureLocked(bufferProducer);
638}
639
640bool SurfaceFlinger::authenticateSurfaceTextureLocked(
641 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800642 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700643 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800644}
645
Brian Anderson069b3652016-07-22 10:32:47 -0700646status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700647 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700648 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700649 FrameEvent::REQUESTED_PRESENT,
650 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700651 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700652 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700653 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700654 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700655 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700656 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700657 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700658 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700659 };
660 return NO_ERROR;
661}
662
Dan Stoza7f7da322014-05-02 15:26:25 -0700663status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
664 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700665 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700666 return BAD_VALUE;
667 }
668
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500669 if (!display.get())
670 return NAME_NOT_FOUND;
671
Jesse Hall692c7232012-11-08 15:41:56 -0800672 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700673 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800674 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700675 type = i;
676 break;
677 }
678 }
679
680 if (type < 0) {
681 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700682 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700683
Mathias Agopian8b736f12012-08-13 17:54:26 -0700684 // TODO: Not sure if display density should handled by SF any longer
685 class Density {
686 static int getDensityFromProperty(char const* propName) {
687 char property[PROPERTY_VALUE_MAX];
688 int density = 0;
689 if (property_get(propName, property, NULL) > 0) {
690 density = atoi(property);
691 }
692 return density;
693 }
694 public:
695 static int getEmuDensity() {
696 return getDensityFromProperty("qemu.sf.lcd_density"); }
697 static int getBuildDensity() {
698 return getDensityFromProperty("ro.sf.lcd_density"); }
699 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700700
Dan Stoza7f7da322014-05-02 15:26:25 -0700701 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700702
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700704 DisplayInfo info = DisplayInfo();
705
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706 float xdpi = hwConfig->getDpiX();
707 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700708
709 if (type == DisplayDevice::DISPLAY_PRIMARY) {
710 // The density of the device is provided by a build property
711 float density = Density::getBuildDensity() / 160.0f;
712 if (density == 0) {
713 // the build doesn't provide a density -- this is wrong!
714 // use xdpi instead
715 ALOGE("ro.sf.lcd_density must be defined as a build property");
716 density = xdpi / 160.0f;
717 }
718 if (Density::getEmuDensity()) {
719 // if "qemu.sf.lcd_density" is specified, it overrides everything
720 xdpi = ydpi = density = Density::getEmuDensity();
721 density /= 160.0f;
722 }
723 info.density = density;
724
725 // TODO: this needs to go away (currently needed only by webkit)
726 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
727 info.orientation = hw->getOrientation();
728 } else {
729 // TODO: where should this value come from?
730 static const int TV_DENSITY = 213;
731 info.density = TV_DENSITY / 160.0f;
732 info.orientation = 0;
733 }
734
Dan Stoza9e56aa02015-11-02 13:00:03 -0800735 info.w = hwConfig->getWidth();
736 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 info.xdpi = xdpi;
738 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900740 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741
Andy McFadden91b2ca82014-06-13 14:04:23 -0700742 // This is how far in advance a buffer must be queued for
743 // presentation at a given time. If you want a buffer to appear
744 // on the screen at time N, you must submit the buffer before
745 // (N - presentationDeadline).
746 //
747 // Normally it's one full refresh period (to give SF a chance to
748 // latch the buffer), but this can be reduced by configuring a
749 // DispSync offset. Any additional delays introduced by the hardware
750 // composer or panel must be accounted for here.
751 //
752 // We add an additional 1ms to allow for processing time and
753 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800755 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700756
757 // All non-virtual displays are currently considered secure.
758 info.secure = true;
759
Michael Wright28f24d02016-07-12 13:30:53 -0700760 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 }
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763 return NO_ERROR;
764}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700765
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800766status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700767 DisplayStatInfo* stats) {
768 if (stats == NULL) {
769 return BAD_VALUE;
770 }
771
772 // FIXME for now we always return stats for the primary display
773 memset(stats, 0, sizeof(*stats));
774 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
775 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
776 return NO_ERROR;
777}
778
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700779int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800780 if (display == NULL) {
781 ALOGE("%s : display is NULL", __func__);
782 return BAD_VALUE;
783 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700784 sp<DisplayDevice> device(getDisplayDevice(display));
785 if (device != NULL) {
786 return device->getActiveConfig();
787 }
788 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700789}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700790
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700791void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
792 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
793 this);
794 int32_t type = hw->getDisplayType();
795 int currentMode = hw->getActiveConfig();
796
797 if (mode == currentMode) {
798 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
799 return;
800 }
801
802 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
803 ALOGW("Trying to set config for virtual display");
804 return;
805 }
806
807 hw->setActiveConfig(mode);
808 getHwComposer().setActiveConfig(type, mode);
809}
810
811status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
812 class MessageSetActiveConfig: public MessageBase {
813 SurfaceFlinger& mFlinger;
814 sp<IBinder> mDisplay;
815 int mMode;
816 public:
817 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
818 int mode) :
819 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
820 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700821 Vector<DisplayInfo> configs;
822 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700823 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700824 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700825 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700826 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700827 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700828 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
829 if (hw == NULL) {
830 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700831 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700832 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
833 ALOGW("Attempt to set active config = %d for virtual display",
834 mMode);
835 } else {
836 mFlinger.setActiveConfigInternal(hw, mMode);
837 }
838 return true;
839 }
840 };
841 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
842 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700843 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700844}
Michael Wright28f24d02016-07-12 13:30:53 -0700845status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
846 Vector<android_color_mode_t>* outColorModes) {
847 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
848 return BAD_VALUE;
849 }
850
851 if (!display.get()) {
852 return NAME_NOT_FOUND;
853 }
854
855 int32_t type = NAME_NOT_FOUND;
856 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
857 if (display == mBuiltinDisplays[i]) {
858 type = i;
859 break;
860 }
861 }
862
863 if (type < 0) {
864 return type;
865 }
866
867 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
868 outColorModes->clear();
869 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
870
871 return NO_ERROR;
872}
873
874android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
875 sp<DisplayDevice> device(getDisplayDevice(display));
876 if (device != nullptr) {
877 return device->getActiveColorMode();
878 }
879 return static_cast<android_color_mode_t>(BAD_VALUE);
880}
881
882void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
883 android_color_mode_t mode) {
884 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
885 this);
886 int32_t type = hw->getDisplayType();
887 android_color_mode_t currentMode = hw->getActiveColorMode();
888
889 if (mode == currentMode) {
890 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
891 return;
892 }
893
894 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
895 ALOGW("Trying to set config for virtual display");
896 return;
897 }
898
899 hw->setActiveColorMode(mode);
900 getHwComposer().setActiveColorMode(type, mode);
901}
902
903
904status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
905 android_color_mode_t colorMode) {
906 class MessageSetActiveColorMode: public MessageBase {
907 SurfaceFlinger& mFlinger;
908 sp<IBinder> mDisplay;
909 android_color_mode_t mMode;
910 public:
911 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
912 android_color_mode_t mode) :
913 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
914 virtual bool handler() {
915 Vector<android_color_mode_t> modes;
916 mFlinger.getDisplayColorModes(mDisplay, &modes);
917 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
918 if (mMode < 0 || !exists) {
919 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
920 mDisplay.get());
921 return true;
922 }
923 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
924 if (hw == nullptr) {
925 ALOGE("Attempt to set active color mode = %d for null display %p",
926 mMode, mDisplay.get());
927 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
928 ALOGW("Attempt to set active color mode= %d for virtual display",
929 mMode);
930 } else {
931 mFlinger.setActiveColorModeInternal(hw, mMode);
932 }
933 return true;
934 }
935 };
936 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
937 postMessageSync(msg);
938 return NO_ERROR;
939}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700940
Svetoslavd85084b2014-03-20 10:28:31 -0700941status_t SurfaceFlinger::clearAnimationFrameStats() {
942 Mutex::Autolock _l(mStateLock);
943 mAnimFrameTracker.clearStats();
944 return NO_ERROR;
945}
946
947status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
948 Mutex::Autolock _l(mStateLock);
949 mAnimFrameTracker.getStats(outStats);
950 return NO_ERROR;
951}
952
Dan Stozac4f471e2016-03-24 09:31:08 -0700953status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
954 HdrCapabilities* outCapabilities) const {
955 Mutex::Autolock _l(mStateLock);
956
957 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
958 if (displayDevice == nullptr) {
959 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
960 return BAD_VALUE;
961 }
962
963 std::unique_ptr<HdrCapabilities> capabilities =
964 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
965 if (capabilities) {
966 std::swap(*outCapabilities, *capabilities);
967 } else {
968 return BAD_VALUE;
969 }
970
971 return NO_ERROR;
972}
973
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700974status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
975 if (enable == mInjectVSyncs) {
976 return NO_ERROR;
977 }
978
979 if (enable) {
980 mInjectVSyncs = enable;
981 ALOGV("VSync Injections enabled");
982 if (mVSyncInjector.get() == nullptr) {
983 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700984 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700985 }
986 mEventQueue.setEventThread(mInjectorEventThread);
987 } else {
988 mInjectVSyncs = enable;
989 ALOGV("VSync Injections disabled");
990 mEventQueue.setEventThread(mSFEventThread);
991 mVSyncInjector.clear();
992 }
993 return NO_ERROR;
994}
995
996status_t SurfaceFlinger::injectVSync(nsecs_t when) {
997 if (!mInjectVSyncs) {
998 ALOGE("VSync Injections not enabled");
999 return BAD_VALUE;
1000 }
1001 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1002 ALOGV("Injecting VSync inside SurfaceFlinger");
1003 mVSyncInjector->onInjectSyncEvent(when);
1004 }
1005 return NO_ERROR;
1006}
1007
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001008// ----------------------------------------------------------------------------
1009
1010sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001011 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001012}
1013
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001014// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001015
1016void SurfaceFlinger::waitForEvent() {
1017 mEventQueue.waitMessage();
1018}
1019
1020void SurfaceFlinger::signalTransaction() {
1021 mEventQueue.invalidate();
1022}
1023
1024void SurfaceFlinger::signalLayerUpdate() {
1025 mEventQueue.invalidate();
1026}
1027
1028void SurfaceFlinger::signalRefresh() {
1029 mEventQueue.refresh();
1030}
1031
1032status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001033 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001034 return mEventQueue.postMessage(msg, reltime);
1035}
1036
1037status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001038 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001039 status_t res = mEventQueue.postMessage(msg, reltime);
1040 if (res == NO_ERROR) {
1041 msg->wait();
1042 }
1043 return res;
1044}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001046void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001047 do {
1048 waitForEvent();
1049 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001050}
1051
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001052void SurfaceFlinger::enableHardwareVsync() {
1053 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001054 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001056 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1057 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001058 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001059 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001060}
1061
Jesse Hall948fe0c2013-10-14 12:56:09 -07001062void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001063 Mutex::Autolock _l(mHWVsyncLock);
1064
Jesse Hall948fe0c2013-10-14 12:56:09 -07001065 if (makeAvailable) {
1066 mHWVsyncAvailable = true;
1067 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001068 // Hardware vsync is not currently available, so abort the resync
1069 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001070 return;
1071 }
1072
Dan Stoza9e56aa02015-11-02 13:00:03 -08001073 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1074 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075
1076 mPrimaryDispSync.reset();
1077 mPrimaryDispSync.setPeriod(period);
1078
1079 if (!mPrimaryHWVsyncEnabled) {
1080 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001081 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1082 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 mPrimaryHWVsyncEnabled = true;
1084 }
1085}
1086
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 Mutex::Autolock _l(mHWVsyncLock);
1089 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001090 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1091 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092 mPrimaryDispSync.endResync();
1093 mPrimaryHWVsyncEnabled = false;
1094 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001095 if (makeUnavailable) {
1096 mHWVsyncAvailable = false;
1097 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098}
1099
Tim Murray4a4e4a22016-04-19 16:29:23 +00001100void SurfaceFlinger::resyncWithRateLimit() {
1101 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1102 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001103 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001104 }
1105}
1106
Steven Thomas3cfac282017-02-06 12:29:30 -08001107void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1108 nsecs_t timestamp) {
1109 Mutex::Autolock lock(mStateLock);
1110 // Ignore any vsyncs from the non-active hardware composer.
1111 if (composer != mHwc) {
1112 return;
1113 }
1114
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116
Jamie Gennisd1700752013-10-14 12:22:52 -07001117 { // Scope for the lock
1118 Mutex::Autolock _l(mHWVsyncLock);
1119 if (type == 0 && mPrimaryHWVsyncEnabled) {
1120 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001122 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001123
1124 if (needsHwVsync) {
1125 enableHardwareVsync();
1126 } else {
1127 disableHardwareVsync(false);
1128 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001129}
1130
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001131void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001132 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001133 *compositorTiming = mCompositorTiming;
1134}
1135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1137 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1138 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1139 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001140
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 // All non-virtual displays are currently considered secure.
1142 bool isSecure = true;
1143
1144 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001145
1146 // When we're using the vr composer, the assumption is that we've
1147 // already created the IBinder object for the primary display.
1148 if (!mHwc->isUsingVrComposer()) {
1149 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1150 }
1151
Dan Stoza9e56aa02015-11-02 13:00:03 -08001152 wp<IBinder> token = mBuiltinDisplays[type];
1153
1154 sp<IGraphicBufferProducer> producer;
1155 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001156 BufferQueue::createBufferQueue(&producer, &consumer,
1157 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001158
1159 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1160 DisplayDevice::DISPLAY_PRIMARY, consumer);
1161 sp<DisplayDevice> hw = new DisplayDevice(this,
1162 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1163 producer, mRenderEngine->getEGLConfig());
1164 mDisplays.add(token, hw);
1165 } else {
1166 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001167 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001168 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001169 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001170 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001171 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1172 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001173 }
1174 setTransactionFlags(eDisplayTransactionNeeded);
1175
Andy McFadden9e9689c2012-10-10 18:17:51 -07001176 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001177 }
Mathias Agopian86303202012-07-24 22:46:10 -07001178}
1179
Steven Thomas3cfac282017-02-06 12:29:30 -08001180void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1181 Mutex::Autolock lock(mStateLock);
1182 if (composer == mHwc) {
1183 repaintEverything();
1184 } else {
1185 // This isn't from our current hardware composer. If it's a callback
1186 // from the real composer, forward the refresh request to vr
1187 // flinger. Otherwise ignore it.
1188 if (!composer->isUsingVrComposer()) {
1189 mVrFlinger->OnHardwareComposerRefresh();
1190 }
1191 }
1192}
1193
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 getHwComposer().setVsyncEnabled(disp,
1197 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001198}
1199
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001200void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1201 for (size_t i = 0; i < layers.size(); ++i) {
1202 layers[i]->clearHwcLayers();
1203 }
1204}
1205
1206void SurfaceFlinger::resetHwc() {
1207 disableHardwareVsync(true);
1208 clearHwcLayers(mDrawingState.layersSortedByZ);
1209 clearHwcLayers(mCurrentState.layersSortedByZ);
1210 // Clear the drawing state so that the logic inside of
1211 // handleTransactionLocked will fire. It will determine the delta between
1212 // mCurrentState and mDrawingState and re-apply all changes when we make the
1213 // transition.
1214 mDrawingState.displays.clear();
1215 mDisplays.clear();
1216}
1217
Jin Qian7480c062017-03-21 00:04:15 +00001218void SurfaceFlinger::updateVrMode() {
1219 bool enteringVrMode = mEnterVrMode;
1220 if (enteringVrMode == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001221 return;
1222 }
Jin Qian7480c062017-03-21 00:04:15 +00001223 if (enteringVrMode && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001224 // Construct new HWComposer without holding any locks.
1225 mVrHwc = new HWComposer(true);
1226 ALOGV("Vr HWC created");
1227 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001228 {
1229 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001230
Jin Qian7480c062017-03-21 00:04:15 +00001231 if (enteringVrMode) {
1232 // Start vrflinger thread, if it hasn't been started already.
1233 if (!mVrFlinger) {
1234 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1235 int err = mVrFlinger->Run(mHwc->getComposer());
1236 if (err != NO_ERROR) {
1237 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1238 mVrFlinger.reset();
1239 mEnterVrMode = false;
1240 return;
1241 }
1242 }
1243
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001244 resetHwc();
1245
1246 mHwc = mVrHwc;
Jin Qian7480c062017-03-21 00:04:15 +00001247 mVrFlinger->EnterVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001248 } else {
Jin Qian7480c062017-03-21 00:04:15 +00001249 mVrFlinger->ExitVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001250
1251 resetHwc();
1252
1253 mHwc = mRealHwc;
1254 enableHardwareVsync();
1255 }
1256
1257 mVisibleRegionsDirty = true;
1258 invalidateHwcGeometry();
1259 android_atomic_or(1, &mRepaintEverything);
1260 setTransactionFlags(eDisplayTransactionNeeded);
1261 }
1262 if (mVrHwc) {
1263 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1264 }
1265}
1266
Mathias Agopian4fec8732012-06-29 14:12:52 -07001267void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001268 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001270 case MessageQueue::INVALIDATE: {
Jin Qian7480c062017-03-21 00:04:15 +00001271 // TODO(eieio): Tied to a conditional until SELinux issues
1272 // are resolved.
1273 if (mVrModeSupported) {
1274 updateVrMode();
1275 }
1276
Dan Stoza50182882016-07-08 12:02:20 -07001277 bool frameMissed = !mHadClientComposition &&
1278 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279 (mPreviousPresentFence->getSignalTime() ==
1280 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001281 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001282 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001283 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001284 signalLayerUpdate();
1285 break;
1286 }
1287
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 bool refreshNeeded = handleMessageTransaction();
1289 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001290 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001292 // Signal a refresh if a transaction modified the window state,
1293 // a new buffer was latched, or if HWC has requested a full
1294 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001295 signalRefresh();
1296 }
1297 break;
1298 }
1299 case MessageQueue::REFRESH: {
1300 handleMessageRefresh();
1301 break;
1302 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001303 }
1304}
1305
Dan Stoza6b9454d2014-11-07 16:00:59 -08001306bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001307 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001308 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001309 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001310 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001311 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001312 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001313}
1314
Dan Stoza6b9454d2014-11-07 16:00:59 -08001315bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001316 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001317 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001318}
1319
1320void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001321 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001322
Pablo Ceballos40845df2016-01-25 17:41:15 -08001323 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001324
Brian Andersond6927fb2016-07-23 23:37:30 -07001325 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001326 rebuildLayerStacks();
1327 setUpHWComposer();
1328 doDebugFlashRegions();
1329 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001330 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001331
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001332 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001333
1334 mHadClientComposition = false;
1335 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1336 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1337 mHadClientComposition = mHadClientComposition ||
1338 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1339 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001340
Dan Stoza9e56aa02015-11-02 13:00:03 -08001341 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001343
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344void SurfaceFlinger::doDebugFlashRegions()
1345{
1346 // is debugging enabled
1347 if (CC_LIKELY(!mDebugRegion))
1348 return;
1349
1350 const bool repaintEverything = mRepaintEverything;
1351 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1352 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001353 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001354 // transform the dirty region into this screen's coordinate space
1355 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1356 if (!dirtyRegion.isEmpty()) {
1357 // redraw the whole screen
1358 doComposeSurfaces(hw, Region(hw->bounds()));
1359
1360 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001361 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001362 RenderEngine& engine(getRenderEngine());
1363 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1364
Mathias Agopianda27af92012-09-13 18:17:13 -07001365 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001366 }
1367 }
1368 }
1369
1370 postFramebuffer();
1371
1372 if (mDebugRegion > 1) {
1373 usleep(mDebugRegion * 1000);
1374 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001375
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001377 auto& displayDevice = mDisplays[displayId];
1378 if (!displayDevice->isDisplayOn()) {
1379 continue;
1380 }
1381
1382 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1384 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001385 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386}
1387
Brian Andersond6927fb2016-07-23 23:37:30 -07001388void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001390 ATRACE_CALL();
1391 ALOGV("preComposition");
1392
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001394 mDrawingState.traverseInZOrder([&](Layer* layer) {
1395 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001396 needExtraInvalidate = true;
1397 }
Robert Carr2047fae2016-11-28 14:09:09 -08001398 });
1399
Mathias Agopiancd60f992012-08-16 16:28:27 -07001400 if (needExtraInvalidate) {
1401 signalLayerUpdate();
1402 }
1403}
1404
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405void SurfaceFlinger::updateCompositorTiming(
1406 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1407 std::shared_ptr<FenceTime>& presentFenceTime) {
1408 // Update queue of past composite+present times and determine the
1409 // most recently known composite to present latency.
1410 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1411 nsecs_t compositeToPresentLatency = -1;
1412 while (!mCompositePresentTimes.empty()) {
1413 CompositePresentTime& cpt = mCompositePresentTimes.front();
1414 // Cached values should have been updated before calling this method,
1415 // which helps avoid duplicate syscalls.
1416 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1417 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1418 break;
1419 }
1420 compositeToPresentLatency = displayTime - cpt.composite;
1421 mCompositePresentTimes.pop();
1422 }
1423
1424 // Don't let mCompositePresentTimes grow unbounded, just in case.
1425 while (mCompositePresentTimes.size() > 16) {
1426 mCompositePresentTimes.pop();
1427 }
1428
Brian Andersond0010582017-03-07 13:20:31 -08001429 setCompositorTimingSnapped(
1430 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1431}
1432
1433void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1434 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 // Integer division and modulo round toward 0 not -inf, so we need to
1436 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001437 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1439 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1440
Brian Andersond0010582017-03-07 13:20:31 -08001441 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1442 if (idealLatency <= 0) {
1443 idealLatency = vsyncInterval;
1444 }
1445
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446 // Snap the latency to a value that removes scheduling jitter from the
1447 // composition and present times, which often have >1ms of jitter.
1448 // Reducing jitter is important if an app attempts to extrapolate
1449 // something (such as user input) to an accurate diasplay time.
1450 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1451 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001452 nsecs_t bias = vsyncInterval / 2;
1453 int64_t extraVsyncs =
1454 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1455 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1456 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001457
Brian Andersond0010582017-03-07 13:20:31 -08001458 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001459 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1460 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001461 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001462}
1463
1464void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 ATRACE_CALL();
1467 ALOGV("postComposition");
1468
Brian Anderson3546a3f2016-07-14 11:51:14 -07001469 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001470 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001471 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001472 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001473 }
1474
Brian Andersond6927fb2016-07-23 23:37:30 -07001475 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001476
1477 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1478 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1479 glCompositionDoneFenceTime =
1480 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1481 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1482 } else {
1483 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1484 }
1485 mGlCompositionDoneTimeline.updateSignalTimes();
1486
1487 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1488 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1489 mDisplayTimeline.push(displayFenceTime);
1490 mDisplayTimeline.updateSignalTimes();
1491
1492 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1493 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1494 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1495 presentFenceTime = &displayFenceTime;
1496 } else {
1497 retireFenceTime = &displayFenceTime;
1498 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499
1500 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1501 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1502
1503 // We use the refreshStartTime which might be sampled a little later than
1504 // when we started doing work for this frame, but that should be okay
1505 // since updateCompositorTiming has snapping logic.
1506 updateCompositorTiming(
1507 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001508 CompositorTiming compositorTiming;
1509 {
1510 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1511 compositorTiming = mCompositorTiming;
1512 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513
Robert Carr2047fae2016-11-28 14:09:09 -08001514 mDrawingState.traverseInZOrder([&](Layer* layer) {
1515 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Andersond0010582017-03-07 13:20:31 -08001516 *presentFenceTime, *retireFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001517 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001518 recordBufferingStats(layer->getName().string(),
1519 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001520 }
Robert Carr2047fae2016-11-28 14:09:09 -08001521 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001522
Brian Anderson3d4039d2016-09-23 16:31:30 -07001523 if (displayFence->isValid()) {
1524 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001525 enableHardwareVsync();
1526 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001527 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001528 }
1529 }
1530
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001531 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001532 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001533 enableHardwareVsync();
1534 }
1535 }
1536
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001537 if (mAnimCompositionPending) {
1538 mAnimCompositionPending = false;
1539
Brian Anderson3d4039d2016-09-23 16:31:30 -07001540 if (displayFenceTime->isValid()) {
1541 mAnimFrameTracker.setActualPresentFence(
1542 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001543 } else {
1544 // The HWC doesn't support present fences, so use the refresh
1545 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 nsecs_t presentTime =
1547 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001548 mAnimFrameTracker.setActualPresentTime(presentTime);
1549 }
1550 mAnimFrameTracker.advanceFrame();
1551 }
Dan Stozab90cf072015-03-05 11:05:59 -08001552
1553 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1554 return;
1555 }
1556
1557 nsecs_t currentTime = systemTime();
1558 if (mHasPoweredOff) {
1559 mHasPoweredOff = false;
1560 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001561 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001563 if (numPeriods < NUM_BUCKETS - 1) {
1564 mFrameBuckets[numPeriods] += elapsedTime;
1565 } else {
1566 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1567 }
1568 mTotalTime += elapsedTime;
1569 }
1570 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571}
1572
1573void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001574 ATRACE_CALL();
1575 ALOGV("rebuildLayerStacks");
1576
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001578 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1579 ATRACE_CALL();
1580 mVisibleRegionsDirty = false;
1581 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001582
Jeff Sharkey76488112017-02-27 14:15:18 -07001583 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1584 Region opaqueRegion;
1585 Region dirtyRegion;
1586 Vector<sp<Layer>> layersSortedByZ;
1587 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1588 const Transform& tr(displayDevice->getTransform());
1589 const Rect bounds(displayDevice->getBounds());
1590 if (displayDevice->isDisplayOn()) {
1591 computeVisibleRegions(
1592 displayDevice->getLayerStack(), dirtyRegion,
1593 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001594
Jeff Sharkey76488112017-02-27 14:15:18 -07001595 mDrawingState.traverseInZOrder([&](Layer* layer) {
1596 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1597 Region drawRegion(tr.transform(
1598 layer->visibleNonTransparentRegion));
1599 drawRegion.andSelf(bounds);
1600 if (!drawRegion.isEmpty()) {
1601 layersSortedByZ.add(layer);
1602 } else {
1603 // Clear out the HWC layer if this layer was
1604 // previously visible, but no longer is
1605 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1606 nullptr);
1607 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001608 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001609 // WM changes displayDevice->layerStack upon sleep/awake.
1610 // Here we make sure we delete the HWC layers even if
1611 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001612 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1613 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001614 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001615 });
1616 }
1617 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1618 displayDevice->undefinedRegion.set(bounds);
1619 displayDevice->undefinedRegion.subtractSelf(
1620 tr.transform(opaqueRegion));
1621 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001622 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001623 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001625
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 ATRACE_CALL();
1628 ALOGV("setUpHWComposer");
1629
Jesse Hall028dc8f2013-08-20 16:35:32 -07001630 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001631 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1632 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1633 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1634
1635 // If nothing has changed (!dirty), don't recompose.
1636 // If something changed, but we don't currently have any visible layers,
1637 // and didn't when we last did a composition, then skip it this time.
1638 // The second rule does two things:
1639 // - When all layers are removed from a display, we'll emit one black
1640 // frame, then nothing more until we get new layers.
1641 // - When a display is created with a private layer stack, we won't
1642 // emit any black frames until a layer is added to the layer stack.
1643 bool mustRecompose = dirty && !(empty && wasEmpty);
1644
1645 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1646 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1647 mustRecompose ? "doing" : "skipping",
1648 dirty ? "+" : "-",
1649 empty ? "+" : "-",
1650 wasEmpty ? "+" : "-");
1651
Dan Stoza71433162014-02-04 16:22:36 -08001652 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001653
1654 if (mustRecompose) {
1655 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1656 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001657 }
1658
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 // build the h/w work list
1660 if (CC_UNLIKELY(mGeometryInvalid)) {
1661 mGeometryInvalid = false;
1662 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1663 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1664 const auto hwcId = displayDevice->getHwcDisplayId();
1665 if (hwcId >= 0) {
1666 const Vector<sp<Layer>>& currentLayers(
1667 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001668 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001669 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670 if (!layer->hasHwcLayer(hwcId)) {
1671 auto hwcLayer = mHwc->createLayer(hwcId);
1672 if (hwcLayer) {
1673 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1674 } else {
1675 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001676 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001677 }
1678 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001679
Robert Carrae060832016-11-28 10:51:00 -08001680 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001681 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001683 }
1684 }
1685 }
1686 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 }
Riley Andrews03414a12014-07-01 14:22:59 -07001688
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001689
1690 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1691
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 // Set the per-frame data
1693 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1694 auto& displayDevice = mDisplays[displayId];
1695 const auto hwcId = displayDevice->getHwcDisplayId();
1696 if (hwcId < 0) {
1697 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001698 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001699 if (colorMatrix != mPreviousColorMatrix) {
1700 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1701 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1702 "display %zd: %d", displayId, result);
1703 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1705 layer->setPerFrameData(displayDevice);
1706 }
1707 }
1708
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001709 mPreviousColorMatrix = colorMatrix;
1710
Dan Stoza9e56aa02015-11-02 13:00:03 -08001711 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001712 auto& displayDevice = mDisplays[displayId];
1713 if (!displayDevice->isDisplayOn()) {
1714 continue;
1715 }
1716
1717 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1719 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001720 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001722
Mathias Agopiancd60f992012-08-16 16:28:27 -07001723void SurfaceFlinger::doComposition() {
1724 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001725 ALOGV("doComposition");
1726
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001727 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001728 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001729 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001730 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731 // transform the dirty region into this screen's coordinate space
1732 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001733
1734 // repaint the framebuffer (if needed)
1735 doDisplayComposition(hw, dirtyRegion);
1736
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737 hw->dirtyRegion.clear();
1738 hw->flip(hw->swapRegion);
1739 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001740 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001741 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001742 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001743}
1744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001745void SurfaceFlinger::postFramebuffer()
1746{
Mathias Agopian841cde52012-03-01 15:44:37 -08001747 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001748 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001749
Mathias Agopiana44b0412011-10-16 18:46:35 -07001750 const nsecs_t now = systemTime();
1751 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001752
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1754 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001755 if (!displayDevice->isDisplayOn()) {
1756 continue;
1757 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 const auto hwcId = displayDevice->getHwcDisplayId();
1759 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001760 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001761 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001762 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001763 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001764 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1765 sp<Fence> releaseFence = Fence::NO_FENCE;
1766 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1767 releaseFence = displayDevice->getClientTargetAcquireFence();
1768 } else {
1769 auto hwcLayer = layer->getHwcLayer(hwcId);
1770 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001771 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 layer->onLayerDisplayed(releaseFence);
1773 }
1774 if (hwcId >= 0) {
1775 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001776 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001777 }
1778
Mathias Agopiana44b0412011-10-16 18:46:35 -07001779 mLastSwapBufferTime = systemTime() - now;
1780 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001781
1782 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1783 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1784 logFrameStats();
1785 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786}
1787
Mathias Agopian87baae12012-07-31 12:38:26 -07001788void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001789{
Mathias Agopian841cde52012-03-01 15:44:37 -08001790 ATRACE_CALL();
1791
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001792 // here we keep a copy of the drawing state (that is the state that's
1793 // going to be overwritten by handleTransactionLocked()) outside of
1794 // mStateLock so that the side-effects of the State assignment
1795 // don't happen with mStateLock held (which can cause deadlocks).
1796 State drawingState(mDrawingState);
1797
Mathias Agopianca4d3602011-05-19 15:38:14 -07001798 Mutex::Autolock _l(mStateLock);
1799 const nsecs_t now = systemTime();
1800 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801
Mathias Agopianca4d3602011-05-19 15:38:14 -07001802 // Here we're guaranteed that some transaction flags are set
1803 // so we can call handleTransactionLocked() unconditionally.
1804 // We call getTransactionFlags(), which will also clear the flags,
1805 // with mStateLock held to guarantee that mCurrentState won't change
1806 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001807
Mathias Agopiane57f2922012-08-09 16:29:12 -07001808 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001809 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001810
Mathias Agopianca4d3602011-05-19 15:38:14 -07001811 mLastTransactionTime = systemTime() - now;
1812 mDebugInTransaction = 0;
1813 invalidateHwcGeometry();
1814 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001815}
1816
Mathias Agopian87baae12012-07-31 12:38:26 -07001817void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001818{
Dan Stoza7dde5992015-05-22 09:51:44 -07001819 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001820 mCurrentState.traverseInZOrder([](Layer* layer) {
1821 layer->notifyAvailableFrames();
1822 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001823
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824 /*
1825 * Traversal of the children
1826 * (perform the transaction for each of them if needed)
1827 */
1828
Mathias Agopian3559b072012-08-15 13:46:03 -07001829 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001830 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001832 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001833
1834 const uint32_t flags = layer->doTransaction(0);
1835 if (flags & Layer::eVisibleRegion)
1836 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001837 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001838 }
1839
1840 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001841 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001842 */
1843
Mathias Agopiane57f2922012-08-09 16:29:12 -07001844 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001845 // here we take advantage of Vector's copy-on-write semantics to
1846 // improve performance by skipping the transaction entirely when
1847 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001848 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1849 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001850 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001851 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001852 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001853 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001854
1855 // find the displays that were removed
1856 // (ie: in drawing state but not in current state)
1857 // also handle displays that changed
1858 // (ie: displays that are in both lists)
1859 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001860 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1861 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001862 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001863 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001864 // Call makeCurrent() on the primary display so we can
1865 // be sure that nothing associated with this display
1866 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001867 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001868 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001869 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1870 if (hw != NULL)
1871 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001872 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001873 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001874 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001875 } else {
1876 ALOGW("trying to remove the main display");
1877 }
1878 } else {
1879 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001880 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001881 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001882 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1883 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001884 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001885 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001886 // recreating the DisplayDevice, so we just remove it
1887 // from the drawing state, so that it get re-added
1888 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001889 sp<DisplayDevice> hw(getDisplayDevice(display));
1890 if (hw != NULL)
1891 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001892 mDisplays.removeItem(display);
1893 mDrawingState.displays.removeItemsAt(i);
1894 dc--; i--;
1895 // at this point we must loop to the next item
1896 continue;
1897 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001898
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001899 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001900 if (disp != NULL) {
1901 if (state.layerStack != draw[i].layerStack) {
1902 disp->setLayerStack(state.layerStack);
1903 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001904 if ((state.orientation != draw[i].orientation)
1905 || (state.viewport != draw[i].viewport)
1906 || (state.frame != draw[i].frame))
1907 {
1908 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001909 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001910 }
Michael Lentine47e45402014-07-18 15:34:25 -07001911 if (state.width != draw[i].width || state.height != draw[i].height) {
1912 disp->setDisplaySize(state.width, state.height);
1913 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001914 }
1915 }
1916 }
1917
1918 // find displays that were added
1919 // (ie: in current state but not in drawing state)
1920 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001921 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001922 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001923
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001924 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001925 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001926 sp<IGraphicBufferProducer> bqProducer;
1927 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001928 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1929 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001932 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001933 // Virtual displays without a surface are dormant:
1934 // they have external state (layer stack, projection,
1935 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001936 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001937
Dan Stoza8cf150a2016-08-02 10:27:31 -07001938 if (mUseHwcVirtualDisplays) {
1939 int width = 0;
1940 int status = state.surface->query(
1941 NATIVE_WINDOW_WIDTH, &width);
1942 ALOGE_IF(status != NO_ERROR,
1943 "Unable to query width (%d)", status);
1944 int height = 0;
1945 status = state.surface->query(
1946 NATIVE_WINDOW_HEIGHT, &height);
1947 ALOGE_IF(status != NO_ERROR,
1948 "Unable to query height (%d)", status);
1949 int intFormat = 0;
1950 status = state.surface->query(
1951 NATIVE_WINDOW_FORMAT, &intFormat);
1952 ALOGE_IF(status != NO_ERROR,
1953 "Unable to query format (%d)", status);
1954 auto format = static_cast<android_pixel_format_t>(
1955 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001956
Dan Stoza8cf150a2016-08-02 10:27:31 -07001957 mHwc->allocateVirtualDisplay(width, height, &format,
1958 &hwcId);
1959 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960
Dan Stoza5cf424b2016-05-20 14:02:39 -07001961 // TODO: Plumb requested format back up to consumer
1962
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 sp<VirtualDisplaySurface> vds =
1964 new VirtualDisplaySurface(*mHwc,
1965 hwcId, state.surface, bqProducer,
1966 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001967
1968 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001969 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001970 }
1971 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001972 ALOGE_IF(state.surface!=NULL,
1973 "adding a supported display, but rendering "
1974 "surface is provided (%p), ignoring it",
1975 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001976
1977 hwcId = state.type;
1978 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1979 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001980 }
1981
1982 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001983 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001984 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 state.type, hwcId, state.isSecure, display,
1986 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001987 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001988 hw->setLayerStack(state.layerStack);
1989 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001990 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001991 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001992 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001994 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001995 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001996 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001997 }
1998 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001
Mathias Agopian84300952012-11-21 16:02:13 -08002002 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2003 // The transform hint might have changed for some layers
2004 // (either because a display has changed, or because a layer
2005 // as changed).
2006 //
2007 // Walk through all the layers in currentLayers,
2008 // and update their transform hint.
2009 //
2010 // If a layer is visible only on a single display, then that
2011 // display is used to calculate the hint, otherwise we use the
2012 // default display.
2013 //
2014 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2015 // the hint is set before we acquire a buffer from the surface texture.
2016 //
2017 // NOTE: layer transactions have taken place already, so we use their
2018 // drawing state. However, SurfaceFlinger's own transaction has not
2019 // happened yet, so we must use the current state layer list
2020 // (soon to become the drawing state list).
2021 //
2022 sp<const DisplayDevice> disp;
2023 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002024 bool first = true;
2025 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002026 // NOTE: we rely on the fact that layers are sorted by
2027 // layerStack first (so we don't have to traverse the list
2028 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002029 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002030 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002031 currentlayerStack = layerStack;
2032 // figure out if this layerstack is mirrored
2033 // (more than one display) if so, pick the default display,
2034 // if not, pick the only display it's on.
2035 disp.clear();
2036 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2037 sp<const DisplayDevice> hw(mDisplays[dpy]);
2038 if (hw->getLayerStack() == currentlayerStack) {
2039 if (disp == NULL) {
2040 disp = hw;
2041 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002042 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002043 break;
2044 }
2045 }
2046 }
2047 }
Chet Haase91d25932013-04-11 15:24:55 -07002048 if (disp == NULL) {
2049 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2050 // redraw after transform hint changes. See bug 8508397.
2051
2052 // could be null when this layer is using a layerStack
2053 // that is not visible on any display. Also can occur at
2054 // screen off/on times.
2055 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002056 }
Chet Haase91d25932013-04-11 15:24:55 -07002057 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002058
2059 first = false;
2060 });
Mathias Agopian84300952012-11-21 16:02:13 -08002061 }
2062
2063
Mathias Agopian3559b072012-08-15 13:46:03 -07002064 /*
2065 * Perform our own transaction if needed
2066 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002067
2068 if (mLayersAdded) {
2069 mLayersAdded = false;
2070 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002071 mVisibleRegionsDirty = true;
2072 }
2073
2074 // some layers might have been removed, so
2075 // we need to update the regions they're exposing.
2076 if (mLayersRemoved) {
2077 mLayersRemoved = false;
2078 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002079 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002080 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002081 // this layer is not visible anymore
2082 // TODO: we could traverse the tree from front to back and
2083 // compute the actual visible region
2084 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002085 Region visibleReg;
2086 visibleReg.set(layer->computeScreenBounds());
2087 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002088 }
Robert Carr2047fae2016-11-28 14:09:09 -08002089 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 }
2091
2092 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002093
2094 updateCursorAsync();
2095}
2096
2097void SurfaceFlinger::updateCursorAsync()
2098{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2100 auto& displayDevice = mDisplays[displayId];
2101 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002102 continue;
2103 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104
2105 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2106 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002107 }
2108 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002109}
2110
2111void SurfaceFlinger::commitTransaction()
2112{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002113 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002114 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002115 for (const auto& l : mLayersPendingRemoval) {
2116 recordBufferingStats(l->getName().string(),
2117 l->getOccupancyHistory(true));
2118 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002119 }
2120 mLayersPendingRemoval.clear();
2121 }
2122
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002123 // If this transaction is part of a window animation then the next frame
2124 // we composite should be considered an animation as well.
2125 mAnimCompositionPending = mAnimTransactionPending;
2126
Mathias Agopian4fec8732012-06-29 14:12:52 -07002127 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002128 mDrawingState.traverseInZOrder([](Layer* layer) {
2129 layer->commitChildList();
2130 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002131 mTransactionPending = false;
2132 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002133 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134}
2135
Robert Carr2047fae2016-11-28 14:09:09 -08002136void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002137 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138{
Mathias Agopian841cde52012-03-01 15:44:37 -08002139 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142 Region aboveOpaqueLayers;
2143 Region aboveCoveredLayers;
2144 Region dirty;
2145
Mathias Agopian87baae12012-07-31 12:38:26 -07002146 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147
Robert Carr2047fae2016-11-28 14:09:09 -08002148 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002150 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151
Jesse Hall01e29052013-02-19 16:13:35 -08002152 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002153 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002154 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002155
Mathias Agopianab028732010-03-16 16:41:46 -07002156 /*
2157 * opaqueRegion: area of a surface that is fully opaque.
2158 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002160
2161 /*
2162 * visibleRegion: area of a surface that is visible on screen
2163 * and not fully transparent. This is essentially the layer's
2164 * footprint minus the opaque regions above it.
2165 * Areas covered by a translucent surface are considered visible.
2166 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002168
2169 /*
2170 * coveredRegion: area of a surface that is covered by all
2171 * visible regions above it (which includes the translucent areas).
2172 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002174
Jesse Halla8026d22012-09-25 13:25:04 -07002175 /*
2176 * transparentRegion: area of a surface that is hinted to be completely
2177 * transparent. This is only used to tell when the layer has no visible
2178 * non-transparent regions and can be removed from the layer list. It
2179 * does not affect the visibleRegion of this layer or any layers
2180 * beneath it. The hint may not be correct if apps don't respect the
2181 * SurfaceView restrictions (which, sadly, some don't).
2182 */
2183 Region transparentRegion;
2184
Mathias Agopianab028732010-03-16 16:41:46 -07002185
2186 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002187 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002188 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002189 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002190 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002191 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002192 if (!visibleRegion.isEmpty()) {
2193 // Remove the transparent area from the visible region
2194 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002195 if (tr.preserveRects()) {
2196 // transform the transparent region
2197 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002198 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002199 // transformation too complex, can't do the
2200 // transparent region optimization.
2201 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002202 }
Mathias Agopianab028732010-03-16 16:41:46 -07002203 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002204
Mathias Agopianab028732010-03-16 16:41:46 -07002205 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002206 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002208 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2209 // the opaque region is the layer's footprint
2210 opaqueRegion = visibleRegion;
2211 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212 }
2213 }
2214
Mathias Agopianab028732010-03-16 16:41:46 -07002215 // Clip the covered region to the visible region
2216 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2217
2218 // Update aboveCoveredLayers for next (lower) layer
2219 aboveCoveredLayers.orSelf(visibleRegion);
2220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221 // subtract the opaque region covered by the layers above us
2222 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223
2224 // compute this layer's dirty region
2225 if (layer->contentDirty) {
2226 // we need to invalidate the whole region
2227 dirty = visibleRegion;
2228 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 layer->contentDirty = false;
2231 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002232 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002233 * the exposed region consists of two components:
2234 * 1) what's VISIBLE now and was COVERED before
2235 * 2) what's EXPOSED now less what was EXPOSED before
2236 *
2237 * note that (1) is conservative, we start with the whole
2238 * visible region but only keep what used to be covered by
2239 * something -- which mean it may have been exposed.
2240 *
2241 * (2) handles areas that were not covered by anything but got
2242 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002243 */
Mathias Agopianab028732010-03-16 16:41:46 -07002244 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002245 const Region oldVisibleRegion = layer->visibleRegion;
2246 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002247 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2248 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002249 }
2250 dirty.subtractSelf(aboveOpaqueLayers);
2251
2252 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002253 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Mathias Agopianab028732010-03-16 16:41:46 -07002255 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002257
Jesse Halla8026d22012-09-25 13:25:04 -07002258 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259 layer->setVisibleRegion(visibleRegion);
2260 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002261 layer->setVisibleNonTransparentRegion(
2262 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002263 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002264
Mathias Agopian87baae12012-07-31 12:38:26 -07002265 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002266}
2267
Mathias Agopian87baae12012-07-31 12:38:26 -07002268void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2269 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002270 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002271 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2272 if (hw->getLayerStack() == layerStack) {
2273 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002274 }
2275 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002276}
2277
Dan Stoza6b9454d2014-11-07 16:00:59 -08002278bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002279{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002280 ALOGV("handlePageFlip");
2281
Brian Andersond6927fb2016-07-23 23:37:30 -07002282 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283
Mathias Agopian4fec8732012-06-29 14:12:52 -07002284 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002286
2287 // Store the set of layers that need updates. This set must not change as
2288 // buffers are being latched, as this could result in a deadlock.
2289 // Example: Two producers share the same command stream and:
2290 // 1.) Layer 0 is latched
2291 // 2.) Layer 0 gets a new frame
2292 // 2.) Layer 1 gets a new frame
2293 // 3.) Layer 1 is latched.
2294 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2295 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002296 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002297 if (layer->hasQueuedFrame()) {
2298 frameQueued = true;
2299 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002300 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002301 } else {
2302 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002303 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002304 } else {
2305 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002306 }
Robert Carr2047fae2016-11-28 14:09:09 -08002307 });
2308
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002310 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002311 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002312 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002313 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002314
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002315 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002316
2317 // If we will need to wake up at some time in the future to deal with a
2318 // queued frame that shouldn't be displayed during this vsync period, wake
2319 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002320 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002321 signalLayerUpdate();
2322 }
2323
2324 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002325 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326}
2327
Mathias Agopianad456f92011-01-13 17:53:01 -08002328void SurfaceFlinger::invalidateHwcGeometry()
2329{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002330 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002331}
2332
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002333
Fabien Sanglard830b8472016-11-30 16:35:58 -08002334void SurfaceFlinger::doDisplayComposition(
2335 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002336 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337{
Dan Stoza71433162014-02-04 16:22:36 -08002338 // We only need to actually compose the display if:
2339 // 1) It is being handled by hardware composer, which may need this to
2340 // keep its virtual display state machine in sync, or
2341 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002343 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002345 return;
2346 }
2347
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348 ALOGV("doDisplayComposition");
2349
Mathias Agopian87baae12012-07-31 12:38:26 -07002350 Region dirtyRegion(inDirtyRegion);
2351
Mathias Agopianb8a55602009-06-26 19:06:36 -07002352 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002353 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354
Fabien Sanglard830b8472016-11-30 16:35:58 -08002355 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002356 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002357 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2358 // takes a rectangle, we must make sure to update that whole
2359 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002360 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002361 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002362 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002363 // We need to redraw the rectangle that will be updated
2364 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002365 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002366 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002367 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002368 } else {
2369 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002370 dirtyRegion.set(displayDevice->bounds());
2371 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372 }
2373 }
2374
Fabien Sanglard830b8472016-11-30 16:35:58 -08002375 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002377 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002378 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002379
2380 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002381 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382}
2383
Dan Stoza9e56aa02015-11-02 13:00:03 -08002384bool SurfaceFlinger::doComposeSurfaces(
2385 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002386{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002388
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002390
2391 mat4 oldColorMatrix;
2392 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2393 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2394 if (applyColorMatrix) {
2395 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2396 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2397 }
2398
Dan Stoza9e56aa02015-11-02 13:00:03 -08002399 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2400 if (hasClientComposition) {
2401 ALOGV("hasClientComposition");
2402
2403 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002404 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002406 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2407 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2408 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2409 }
2410 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002411 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002412
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002413 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2415 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002416 // when using overlays, we assume a fully transparent framebuffer
2417 // NOTE: we could reduce how much we need to clear, for instance
2418 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002419 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002420 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002422 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002423 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002424 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002425
2426 // we remove the scissor part
2427 // we're left with the letterbox region
2428 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002430
2431 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002433
2434 // but limit it to the dirty region
2435 region.andSelf(dirty);
2436
Mathias Agopianb9494d52012-04-18 02:28:45 -07002437 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002438 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002439 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002441 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002442 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002443
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002445 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002446 // scissor on the main display. It should never be needed
2447 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 const Rect& bounds(displayDevice->getBounds());
2449 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002450 if (scissor != bounds) {
2451 // scissor doesn't match the screen's dimensions, so we
2452 // need to clear everything outside of it and enable
2453 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002454
Mathias Agopianf45c5102012-10-24 16:29:17 -07002455 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 const uint32_t height = displayDevice->getHeight();
2457 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002458 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002459 }
2460 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002461 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002462
Mathias Agopian85d751c2012-08-29 16:59:24 -07002463 /*
2464 * and then, render the layers targeted at the framebuffer
2465 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002466
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 ALOGV("Rendering client layers");
2468 const Transform& displayTransform = displayDevice->getTransform();
2469 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002470 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 bool firstLayer = true;
2472 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2473 const Region clip(dirty.intersect(
2474 displayTransform.transform(layer->visibleRegion)));
2475 ALOGV("Layer: %s", layer->getName().string());
2476 ALOGV(" Composition type: %s",
2477 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002478 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 switch (layer->getCompositionType(hwcId)) {
2480 case HWC2::Composition::Cursor:
2481 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002482 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002484 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2486 layer->isOpaque(state) && (state.alpha == 1.0f)
2487 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002488 // never clear the very first layer since we're
2489 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002490 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002491 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002492 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002493 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 case HWC2::Composition::Client: {
2495 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002496 break;
2497 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002499 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002500 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 } else {
2502 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002503 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002505 }
2506 } else {
2507 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002508 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002509 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002510 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002511 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002513 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002514 }
2515 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002516
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002517 if (applyColorMatrix) {
2518 getRenderEngine().setupColorTransform(oldColorMatrix);
2519 }
2520
Mathias Agopianf45c5102012-10-24 16:29:17 -07002521 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002523 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524}
2525
Fabien Sanglard830b8472016-11-30 16:35:58 -08002526void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2527 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002528 RenderEngine& engine(getRenderEngine());
2529 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530}
2531
Dan Stoza7d89d062015-04-30 13:29:25 -07002532status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002533 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002534 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 const sp<Layer>& lbc,
2536 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002537{
Dan Stoza7d89d062015-04-30 13:29:25 -07002538 // add this layer to the current state list
2539 {
2540 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002541 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002542 return NO_MEMORY;
2543 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 if (parent == nullptr) {
2545 mCurrentState.layersSortedByZ.add(lbc);
2546 } else {
2547 parent->addChild(lbc);
2548 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002549 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 mLayersAdded = true;
2551 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002552 }
2553
Mathias Agopian96f08192010-06-02 23:28:45 -07002554 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002555 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002556
Dan Stoza7d89d062015-04-30 13:29:25 -07002557 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002558}
2559
Robert Carr9524cb32017-02-13 11:32:32 -08002560status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002561 Mutex::Autolock _l(mStateLock);
2562
Robert Carr1f0a16a2016-10-24 16:27:39 -07002563 const auto& p = layer->getParent();
2564 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2565 mCurrentState.layersSortedByZ.remove(layer);
2566
Robert Carr136e2f62017-02-08 17:54:29 -08002567 // As a matter of normal operation, the LayerCleaner will produce a second
2568 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2569 // so we will succeed in promoting it, but it's already been removed
2570 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2571 // otherwise something has gone wrong and we are leaking the layer.
2572 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2574 layer->getName().string(),
2575 (p != nullptr) ? p->getName().string() : "no-parent");
2576 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002577 } else if (index < 0) {
2578 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002579 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580
2581 mLayersPendingRemoval.add(layer);
2582 mLayersRemoved = true;
2583 mNumLayers--;
2584 setTransactionFlags(eTransactionNeeded);
2585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586}
2587
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002588uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002589 return android_atomic_release_load(&mTransactionFlags);
2590}
2591
Mathias Agopian3f844832013-08-07 21:24:32 -07002592uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2594}
2595
Mathias Agopian3f844832013-08-07 21:24:32 -07002596uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2598 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002599 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 }
2601 return old;
2602}
2603
Mathias Agopian8b33f032012-07-24 20:43:54 -07002604void SurfaceFlinger::setTransactionState(
2605 const Vector<ComposerState>& state,
2606 const Vector<DisplayState>& displays,
2607 uint32_t flags)
2608{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002609 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002610 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002611 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002612
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002613 if (flags & eAnimation) {
2614 // For window updates that are part of an animation we must wait for
2615 // previous animation "frames" to be handled.
2616 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002617 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002618 if (CC_UNLIKELY(err != NO_ERROR)) {
2619 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002620 // caller after a few seconds.
2621 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2622 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002623 mAnimTransactionPending = false;
2624 break;
2625 }
2626 }
2627 }
2628
Mathias Agopiane57f2922012-08-09 16:29:12 -07002629 size_t count = displays.size();
2630 for (size_t i=0 ; i<count ; i++) {
2631 const DisplayState& s(displays[i]);
2632 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002633 }
2634
Mathias Agopiane57f2922012-08-09 16:29:12 -07002635 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002636 for (size_t i=0 ; i<count ; i++) {
2637 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002638 // Here we need to check that the interface we're given is indeed
2639 // one of our own. A malicious client could give us a NULL
2640 // IInterface, or one of its own or even one of our own but a
2641 // different type. All these situations would cause us to crash.
2642 //
2643 // NOTE: it would be better to use RTTI as we could directly check
2644 // that we have a Client*. however, RTTI is disabled in Android.
2645 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002646 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002647 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002648 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002649 sp<Client> client( static_cast<Client *>(s.client.get()) );
2650 transactionFlags |= setClientStateLocked(client, s.state);
2651 }
2652 }
2653 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002654 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002655
Robert Carr2a7dbb42016-05-24 11:41:28 -07002656 // If a synchronous transaction is explicitly requested without any changes,
2657 // force a transaction anyway. This can be used as a flush mechanism for
2658 // previous async transactions.
2659 if (transactionFlags == 0 && (flags & eSynchronous)) {
2660 transactionFlags = eTransactionNeeded;
2661 }
2662
Mathias Agopian386aa982011-11-07 21:58:03 -08002663 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002664 if (mInterceptor.isEnabled()) {
2665 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2666 }
Irvel468051e2016-06-13 16:44:44 -07002667
Mathias Agopian386aa982011-11-07 21:58:03 -08002668 // this triggers the transaction
2669 setTransactionFlags(transactionFlags);
2670
2671 // if this is a synchronous transaction, wait for it to take effect
2672 // before returning.
2673 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002674 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002675 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002676 if (flags & eAnimation) {
2677 mAnimTransactionPending = true;
2678 }
2679 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002680 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2681 if (CC_UNLIKELY(err != NO_ERROR)) {
2682 // just in case something goes wrong in SF, return to the
2683 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002684 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2685 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002686 break;
2687 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 }
2690}
2691
Mathias Agopiane57f2922012-08-09 16:29:12 -07002692uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2693{
Jesse Hall9a143922012-10-04 16:29:19 -07002694 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2695 if (dpyIdx < 0)
2696 return 0;
2697
Mathias Agopiane57f2922012-08-09 16:29:12 -07002698 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002699 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002700 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002701 const uint32_t what = s.what;
2702 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002703 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002704 disp.surface = s.surface;
2705 flags |= eDisplayTransactionNeeded;
2706 }
2707 }
2708 if (what & DisplayState::eLayerStackChanged) {
2709 if (disp.layerStack != s.layerStack) {
2710 disp.layerStack = s.layerStack;
2711 flags |= eDisplayTransactionNeeded;
2712 }
2713 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002714 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 if (disp.orientation != s.orientation) {
2716 disp.orientation = s.orientation;
2717 flags |= eDisplayTransactionNeeded;
2718 }
2719 if (disp.frame != s.frame) {
2720 disp.frame = s.frame;
2721 flags |= eDisplayTransactionNeeded;
2722 }
2723 if (disp.viewport != s.viewport) {
2724 disp.viewport = s.viewport;
2725 flags |= eDisplayTransactionNeeded;
2726 }
2727 }
Michael Lentine47e45402014-07-18 15:34:25 -07002728 if (what & DisplayState::eDisplaySizeChanged) {
2729 if (disp.width != s.width) {
2730 disp.width = s.width;
2731 flags |= eDisplayTransactionNeeded;
2732 }
2733 if (disp.height != s.height) {
2734 disp.height = s.height;
2735 flags |= eDisplayTransactionNeeded;
2736 }
2737 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 }
2739 return flags;
2740}
2741
2742uint32_t SurfaceFlinger::setClientStateLocked(
2743 const sp<Client>& client,
2744 const layer_state_t& s)
2745{
2746 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002747 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002748 if (layer != 0) {
2749 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002750 bool geometryAppliesWithResize =
2751 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002752 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002753 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002754 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002755 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002756 }
2757 if (what & layer_state_t::eLayerChanged) {
2758 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 const auto& p = layer->getParent();
2760 if (p == nullptr) {
2761 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2762 if (layer->setLayer(s.z) && idx >= 0) {
2763 mCurrentState.layersSortedByZ.removeAt(idx);
2764 mCurrentState.layersSortedByZ.add(layer);
2765 // we need traversal (state changed)
2766 // AND transaction (list changed)
2767 flags |= eTransactionNeeded|eTraversalNeeded;
2768 }
2769 } else {
2770 if (p->setChildLayer(layer, s.z)) {
2771 flags |= eTransactionNeeded|eTraversalNeeded;
2772 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 }
2774 }
2775 if (what & layer_state_t::eSizeChanged) {
2776 if (layer->setSize(s.w, s.h)) {
2777 flags |= eTraversalNeeded;
2778 }
2779 }
2780 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 flags |= eTraversalNeeded;
2783 }
2784 if (what & layer_state_t::eMatrixChanged) {
2785 if (layer->setMatrix(s.matrix))
2786 flags |= eTraversalNeeded;
2787 }
2788 if (what & layer_state_t::eTransparentRegionChanged) {
2789 if (layer->setTransparentRegionHint(s.transparentRegion))
2790 flags |= eTraversalNeeded;
2791 }
Dan Stoza23116082015-06-18 14:58:39 -07002792 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793 if (layer->setFlags(s.flags, s.mask))
2794 flags |= eTraversalNeeded;
2795 }
2796 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002797 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002798 flags |= eTraversalNeeded;
2799 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002800 if (what & layer_state_t::eFinalCropChanged) {
2801 if (layer->setFinalCrop(s.finalCrop))
2802 flags |= eTraversalNeeded;
2803 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002804 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002805 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 // We only allow setting layer stacks for top level layers,
2807 // everything else inherits layer stack from its parent.
2808 if (layer->hasParent()) {
2809 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2810 layer->getName().string());
2811 } else if (idx < 0) {
2812 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2813 "that also does not appear in the top level layer list. Something"
2814 " has gone wrong.", layer->getName().string());
2815 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 mCurrentState.layersSortedByZ.removeAt(idx);
2817 mCurrentState.layersSortedByZ.add(layer);
2818 // we need traversal (state changed)
2819 // AND transaction (list changed)
2820 flags |= eTransactionNeeded|eTraversalNeeded;
2821 }
2822 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002823 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002824 if (s.barrierHandle != nullptr) {
2825 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2826 } else if (s.barrierGbp != nullptr) {
2827 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2828 if (authenticateSurfaceTextureLocked(gbp)) {
2829 const auto& otherLayer =
2830 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2831 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2832 } else {
2833 ALOGE("Attempt to defer transaction to to an"
2834 " unrecognized GraphicBufferProducer");
2835 }
2836 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002837 // We don't trigger a traversal here because if no other state is
2838 // changed, we don't want this to cause any more work
2839 }
Robert Carr1db73f62016-12-21 12:58:51 -08002840 if (what & layer_state_t::eReparentChildren) {
2841 if (layer->reparentChildren(s.reparentHandle)) {
2842 flags |= eTransactionNeeded|eTraversalNeeded;
2843 }
2844 }
Robert Carr9524cb32017-02-13 11:32:32 -08002845 if (what & layer_state_t::eDetachChildren) {
2846 layer->detachChildren();
2847 }
Robert Carrc3574f72016-03-24 12:19:32 -07002848 if (what & layer_state_t::eOverrideScalingModeChanged) {
2849 layer->setOverrideScalingMode(s.overrideScalingMode);
2850 // We don't trigger a traversal here because if no other state is
2851 // changed, we don't want this to cause any more work
2852 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002853 }
2854 return flags;
2855}
2856
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002857status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002858 const String8& name,
2859 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002860 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002861 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2862 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002864 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002865 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002866 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002867 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002868 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002869
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002870 status_t result = NO_ERROR;
2871
2872 sp<Layer> layer;
2873
Mathias Agopian3165cc22012-08-08 19:42:09 -07002874 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2875 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002876 result = createNormalLayer(client,
2877 name, w, h, flags, format,
2878 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002880 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002881 result = createDimLayer(client,
2882 name, w, h, flags,
2883 handle, gbp, &layer);
2884 break;
2885 default:
2886 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 break;
2888 }
2889
Dan Stoza7d89d062015-04-30 13:29:25 -07002890 if (result != NO_ERROR) {
2891 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002893
Albert Chaulk479c60c2017-01-27 14:21:34 -05002894 layer->setInfo(windowType, ownerUid);
2895
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002897 if (result != NO_ERROR) {
2898 return result;
2899 }
Irvelffc9efc2016-07-27 15:16:37 -07002900 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002901
2902 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002903 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904}
2905
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002906status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2907 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2908 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
2910 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002911 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 case PIXEL_FORMAT_TRANSPARENT:
2913 case PIXEL_FORMAT_TRANSLUCENT:
2914 format = PIXEL_FORMAT_RGBA_8888;
2915 break;
2916 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002917 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918 break;
2919 }
2920
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002921 *outLayer = new Layer(this, client, name, w, h, flags);
2922 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2923 if (err == NO_ERROR) {
2924 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002925 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002927
2928 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2929 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002932status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2933 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2934 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002936 *outLayer = new LayerDim(this, client, name, w, h, flags);
2937 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002938 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002939 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002940}
2941
Mathias Agopianac9fa422013-02-11 16:40:36 -08002942status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943{
Robert Carr9524cb32017-02-13 11:32:32 -08002944 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002945 status_t err = NO_ERROR;
2946 sp<Layer> l(client->getLayerUser(handle));
2947 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002948 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002949 err = removeLayer(l);
2950 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2951 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002952 }
2953 return err;
2954}
2955
Mathias Agopian13127d82013-03-05 17:47:11 -08002956status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002957{
Mathias Agopian67106042013-03-14 19:18:13 -07002958 // called by ~LayerCleaner() when all references to the IBinder (handle)
2959 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002960 sp<Layer> l = layer.promote();
2961 if (l == nullptr) {
2962 // The layer has already been removed, carry on
2963 return NO_ERROR;
2964 } if (l->getParent() != nullptr) {
2965 // If we have a parent, then we can continue to live as long as it does.
2966 return NO_ERROR;
2967 }
2968 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969}
2970
Mathias Agopianb60314a2012-04-10 22:09:54 -07002971// ---------------------------------------------------------------------------
2972
Andy McFadden13a082e2012-08-24 10:16:42 -07002973void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002974 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002975 Vector<ComposerState> state;
2976 Vector<DisplayState> displays;
2977 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002978 d.what = DisplayState::eDisplayProjectionChanged |
2979 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002980 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002981 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002982 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002983 d.frame.makeInvalid();
2984 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002985 d.width = 0;
2986 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002987 displays.add(d);
2988 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002989 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002990
Dan Stoza9e56aa02015-11-02 13:00:03 -08002991 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2992 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002993 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002994
Brian Andersond0010582017-03-07 13:20:31 -08002995 // Use phase of 0 since phase is not known.
2996 // Use latency of 0, which will snap to the ideal latency.
2997 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002998}
2999
3000void SurfaceFlinger::initializeDisplays() {
3001 class MessageScreenInitialized : public MessageBase {
3002 SurfaceFlinger* flinger;
3003 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003004 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003005 virtual bool handler() {
3006 flinger->onInitializeDisplays();
3007 return true;
3008 }
3009 };
3010 sp<MessageBase> msg = new MessageScreenInitialized(this);
3011 postMessageAsync(msg); // we may be called from main thread, use async message
3012}
3013
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003014void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3015 int mode) {
3016 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3017 this);
3018 int32_t type = hw->getDisplayType();
3019 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003020
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003021 if (mode == currentMode) {
3022 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003023 return;
3024 }
3025
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003026 hw->setPowerMode(mode);
3027 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3028 ALOGW("Trying to set power mode for virtual display");
3029 return;
3030 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003031
Irvelffc9efc2016-07-27 15:16:37 -07003032 if (mInterceptor.isEnabled()) {
3033 Mutex::Autolock _l(mStateLock);
3034 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3035 if (idx < 0) {
3036 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3037 return;
3038 }
3039 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3040 }
3041
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003042 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003043 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003045 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3046 // FIXME: eventthread only knows about the main display right now
3047 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003048 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003052 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003053 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003054
3055 struct sched_param param = {0};
3056 param.sched_priority = 1;
3057 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3058 ALOGW("Couldn't set SCHED_FIFO on display on");
3059 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003060 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003061 // Turn off the display
3062 struct sched_param param = {0};
3063 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3064 ALOGW("Couldn't set SCHED_OTHER on display off");
3065 }
3066
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003068 disableHardwareVsync(true); // also cancels any in-progress resync
3069
Mathias Agopiancde87a32012-09-13 14:09:01 -07003070 // FIXME: eventthread only knows about the main display right now
3071 mEventThread->onScreenReleased();
3072 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003073
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 getHwComposer().setPowerMode(type, mode);
3075 mVisibleRegionsDirty = true;
3076 // from this point on, SF will stop drawing on this display
3077 } else {
3078 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003079 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003080}
3081
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003082void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3083 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003084 SurfaceFlinger& mFlinger;
3085 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003086 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003087 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088 MessageSetPowerMode(SurfaceFlinger& flinger,
3089 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3090 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003091 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003092 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003093 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003094 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003095 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003096 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003097 ALOGW("Attempt to set power mode = %d for virtual display",
3098 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003099 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003100 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003101 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003102 return true;
3103 }
3104 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003105 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003106 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003107}
3108
3109// ---------------------------------------------------------------------------
3110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3112{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003114
Mathias Agopianbd115332013-04-18 16:41:04 -07003115 IPCThreadState* ipc = IPCThreadState::self();
3116 const int pid = ipc->getCallingPid();
3117 const int uid = ipc->getCallingUid();
3118 if ((uid != AID_SHELL) &&
3119 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003120 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003121 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003123 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003124 // (this would indicate SF is stuck, but we want to be able to
3125 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003126 status_t err = mStateLock.timedLock(s2ns(1));
3127 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003128 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003129 result.appendFormat(
3130 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3131 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003132 }
3133
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003134 bool dumpAll = true;
3135 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003136 size_t numArgs = args.size();
3137 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003138 if ((index < numArgs) &&
3139 (args[index] == String16("--list"))) {
3140 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003141 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003142 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003143 }
3144
3145 if ((index < numArgs) &&
3146 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003147 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003148 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003149 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003151
3152 if ((index < numArgs) &&
3153 (args[index] == String16("--latency-clear"))) {
3154 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003155 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003156 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003157 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003158
3159 if ((index < numArgs) &&
3160 (args[index] == String16("--dispsync"))) {
3161 index++;
3162 mPrimaryDispSync.dump(result);
3163 dumpAll = false;
3164 }
Dan Stozab90cf072015-03-05 11:05:59 -08003165
3166 if ((index < numArgs) &&
3167 (args[index] == String16("--static-screen"))) {
3168 index++;
3169 dumpStaticScreenStats(result);
3170 dumpAll = false;
3171 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003172
3173 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003174 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003175 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003176 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003177 dumpAll = false;
3178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003180
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003181 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003182 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003183 }
3184
Mathias Agopian9795c422009-08-26 16:36:26 -07003185 if (locked) {
3186 mStateLock.unlock();
3187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188 }
3189 write(fd, result.string(), result.size());
3190 return NO_ERROR;
3191}
3192
Dan Stozac7014012014-02-14 15:03:43 -08003193void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3194 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003195{
Robert Carr2047fae2016-11-28 14:09:09 -08003196 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003197 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003198 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003199}
3200
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003201void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003202 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003203{
3204 String8 name;
3205 if (index < args.size()) {
3206 name = String8(args[index]);
3207 index++;
3208 }
3209
Dan Stoza9e56aa02015-11-02 13:00:03 -08003210 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3211 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003212 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003213
3214 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003215 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003216 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003217 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003218 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003219 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003220 }
Robert Carr2047fae2016-11-28 14:09:09 -08003221 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003222 }
3223}
3224
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003225void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003226 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003227{
3228 String8 name;
3229 if (index < args.size()) {
3230 name = String8(args[index]);
3231 index++;
3232 }
3233
Robert Carr2047fae2016-11-28 14:09:09 -08003234 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003235 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003236 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003237 }
Robert Carr2047fae2016-11-28 14:09:09 -08003238 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003239
Svetoslavd85084b2014-03-20 10:28:31 -07003240 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003241}
3242
Jamie Gennis6547ff42013-07-16 20:12:42 -07003243// This should only be called from the main thread. Otherwise it would need
3244// the lock and should use mCurrentState rather than mDrawingState.
3245void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003246 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003247 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003248 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003249
3250 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3251}
3252
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003253void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003254{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003255 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003256 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3257
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003258 if (isLayerTripleBufferingDisabled())
3259 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003260
3261 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003262 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003263 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003264 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003265 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003266}
3267
Dan Stozab90cf072015-03-05 11:05:59 -08003268void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3269{
3270 result.appendFormat("Static screen stats:\n");
3271 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3272 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3273 float percent = 100.0f *
3274 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3275 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3276 b + 1, bucketTimeSec, percent);
3277 }
3278 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3279 float percent = 100.0f *
3280 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3281 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3282 NUM_BUCKETS - 1, bucketTimeSec, percent);
3283}
3284
Dan Stozae77c7662016-05-13 11:37:28 -07003285void SurfaceFlinger::recordBufferingStats(const char* layerName,
3286 std::vector<OccupancyTracker::Segment>&& history) {
3287 Mutex::Autolock lock(mBufferingStatsMutex);
3288 auto& stats = mBufferingStats[layerName];
3289 for (const auto& segment : history) {
3290 if (!segment.usedThirdBuffer) {
3291 stats.twoBufferTime += segment.totalTime;
3292 }
3293 if (segment.occupancyAverage < 1.0f) {
3294 stats.doubleBufferedTime += segment.totalTime;
3295 } else if (segment.occupancyAverage < 2.0f) {
3296 stats.tripleBufferedTime += segment.totalTime;
3297 }
3298 ++stats.numSegments;
3299 stats.totalTime += segment.totalTime;
3300 }
3301}
3302
Brian Andersond6927fb2016-07-23 23:37:30 -07003303void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3304 result.appendFormat("Layer frame timestamps:\n");
3305
3306 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3307 const size_t count = currentLayers.size();
3308 for (size_t i=0 ; i<count ; i++) {
3309 currentLayers[i]->dumpFrameEvents(result);
3310 }
3311}
3312
Dan Stozae77c7662016-05-13 11:37:28 -07003313void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3314 result.append("Buffering stats:\n");
3315 result.append(" [Layer name] <Active time> <Two buffer> "
3316 "<Double buffered> <Triple buffered>\n");
3317 Mutex::Autolock lock(mBufferingStatsMutex);
3318 typedef std::tuple<std::string, float, float, float> BufferTuple;
3319 std::map<float, BufferTuple, std::greater<float>> sorted;
3320 for (const auto& statsPair : mBufferingStats) {
3321 const char* name = statsPair.first.c_str();
3322 const BufferingStats& stats = statsPair.second;
3323 if (stats.numSegments == 0) {
3324 continue;
3325 }
3326 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3327 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3328 stats.totalTime;
3329 float doubleBufferRatio = static_cast<float>(
3330 stats.doubleBufferedTime) / stats.totalTime;
3331 float tripleBufferRatio = static_cast<float>(
3332 stats.tripleBufferedTime) / stats.totalTime;
3333 sorted.insert({activeTime, {name, twoBufferRatio,
3334 doubleBufferRatio, tripleBufferRatio}});
3335 }
3336 for (const auto& sortedPair : sorted) {
3337 float activeTime = sortedPair.first;
3338 const BufferTuple& values = sortedPair.second;
3339 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3340 std::get<0>(values).c_str(), activeTime,
3341 std::get<1>(values), std::get<2>(values),
3342 std::get<3>(values));
3343 }
3344 result.append("\n");
3345}
3346
3347
Mathias Agopian74d211a2013-04-22 16:55:35 +02003348void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3349 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003350{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003351 bool colorize = false;
3352 if (index < args.size()
3353 && (args[index] == String16("--color"))) {
3354 colorize = true;
3355 index++;
3356 }
3357
3358 Colorizer colorizer(colorize);
3359
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003360 // figure out if we're stuck somewhere
3361 const nsecs_t now = systemTime();
3362 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3363 const nsecs_t inTransaction(mDebugInTransaction);
3364 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3365 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3366
3367 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003368 * Dump library configuration.
3369 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370
3371 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003372 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003373 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003374 appendSfConfigString(result);
3375 appendUiConfigString(result);
3376 appendGuiConfigString(result);
3377 result.append("\n");
3378
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003379 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003380 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003382 result.append(SyncFeatures::getInstance().toString());
3383 result.append("\n");
3384
Dan Stoza9e56aa02015-11-02 13:00:03 -08003385 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3386
Andy McFadden41d67d72014-04-25 16:58:34 -07003387 colorizer.bold(result);
3388 result.append("DispSync configuration: ");
3389 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003390 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003391 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003392 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003393 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003394 result.append("\n");
3395
Dan Stozab90cf072015-03-05 11:05:59 -08003396 // Dump static screen stats
3397 result.append("\n");
3398 dumpStaticScreenStats(result);
3399 result.append("\n");
3400
Dan Stozae77c7662016-05-13 11:37:28 -07003401 dumpBufferingStats(result);
3402
Andy McFadden4803b742012-09-24 19:07:20 -07003403 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003404 * Dump the visible layer list
3405 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003406 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003407 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003408 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003409 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003410 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003411 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412
3413 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003414 * Dump Display state
3415 */
3416
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003417 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003418 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003419 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003420 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3421 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003422 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003423 }
3424
3425 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003426 * Dump SurfaceFlinger global state
3427 */
3428
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003429 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003430 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003431 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003432
Mathias Agopian888c8222012-08-04 21:10:38 -07003433 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003434 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003435
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003436 colorizer.bold(result);
3437 result.appendFormat("EGL implementation : %s\n",
3438 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3439 colorizer.reset(result);
3440 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003441 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003442
Mathias Agopian875d8e12013-06-07 15:35:48 -07003443 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003444
Mathias Agopian42977342012-08-05 00:40:46 -07003445 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3447 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003448 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003449 " last eglSwapBuffers() time: %f us\n"
3450 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003451 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003452 " refresh-rate : %f fps\n"
3453 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003454 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003455 " gpu_to_cpu_unsupported : %d\n"
3456 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457 mLastSwapBufferTime/1000.0,
3458 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003459 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003460 1e9 / activeConfig->getVsyncPeriod(),
3461 activeConfig->getDpiX(),
3462 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003463 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003464
Mathias Agopian74d211a2013-04-22 16:55:35 +02003465 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003466 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003467
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003470
3471 /*
3472 * VSYNC state
3473 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003474 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003475 result.append("\n");
3476
3477 /*
3478 * HWC layer minidump
3479 */
3480 for (size_t d = 0; d < mDisplays.size(); d++) {
3481 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3482 int32_t hwcId = displayDevice->getHwcDisplayId();
3483 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3484 continue;
3485 }
3486
3487 result.appendFormat("Display %d HWC layers:\n", hwcId);
3488 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003489 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003490 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 });
Dan Stozae22aec72016-08-01 13:20:59 -07003492 result.append("\n");
3493 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003494
3495 /*
3496 * Dump HWComposer state
3497 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003498 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003499 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003500 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003501 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003502 result.appendFormat(" h/w composer %s\n",
3503 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003504 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003505
3506 /*
3507 * Dump gralloc state
3508 */
3509 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3510 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003511}
3512
Mathias Agopian13127d82013-03-05 17:47:11 -08003513const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003514SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003515 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003516 wp<IBinder> dpy;
3517 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3518 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3519 dpy = mDisplays.keyAt(i);
3520 break;
3521 }
3522 }
3523 if (dpy == NULL) {
3524 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3525 // Just use the primary display so we have something to return
3526 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3527 }
3528 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003529}
3530
Keun young Park63f165f2012-08-31 10:53:36 -07003531bool SurfaceFlinger::startDdmConnection()
3532{
3533 void* libddmconnection_dso =
3534 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3535 if (!libddmconnection_dso) {
3536 return false;
3537 }
3538 void (*DdmConnection_start)(const char* name);
3539 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003540 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003541 if (!DdmConnection_start) {
3542 dlclose(libddmconnection_dso);
3543 return false;
3544 }
3545 (*DdmConnection_start)(getServiceName());
3546 return true;
3547}
3548
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003549status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550 switch (code) {
3551 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003552 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003554 case CLEAR_ANIMATION_FRAME_STATS:
3555 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003556 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003557 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003558 {
3559 // codes that require permission check
3560 IPCThreadState* ipc = IPCThreadState::self();
3561 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003562 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003563 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003564 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003565 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003566 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003568 break;
3569 }
Robert Carr1db73f62016-12-21 12:58:51 -08003570 /*
3571 * Calling setTransactionState is safe, because you need to have been
3572 * granted a reference to Client* and Handle* to do anything with it.
3573 *
3574 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3575 */
3576 case SET_TRANSACTION_STATE:
3577 case CREATE_SCOPED_CONNECTION:
3578 {
3579 return OK;
3580 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003581 case CAPTURE_SCREEN:
3582 {
3583 // codes that require permission check
3584 IPCThreadState* ipc = IPCThreadState::self();
3585 const int pid = ipc->getCallingPid();
3586 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003587 if ((uid != AID_GRAPHICS) &&
3588 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003589 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003590 return PERMISSION_DENIED;
3591 }
3592 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593 }
3594 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003595 return OK;
3596}
3597
3598status_t SurfaceFlinger::onTransact(
3599 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3600{
3601 status_t credentialCheck = CheckTransactCodeCredentials(code);
3602 if (credentialCheck != OK) {
3603 return credentialCheck;
3604 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003605
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3607 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003608 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003609 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003610 IPCThreadState* ipc = IPCThreadState::self();
3611 const int pid = ipc->getCallingPid();
3612 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003613 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003614 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 return PERMISSION_DENIED;
3616 }
3617 int n;
3618 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003619 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003620 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621 return NO_ERROR;
3622 case 1002: // SHOW_UPDATES
3623 n = data.readInt32();
3624 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003625 invalidateHwcGeometry();
3626 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003629 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003630 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003632 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003633 setTransactionFlags(
3634 eTransactionNeeded|
3635 eDisplayTransactionNeeded|
3636 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003637 return NO_ERROR;
3638 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003639 case 1006:{ // send empty update
3640 signalRefresh();
3641 return NO_ERROR;
3642 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003643 case 1008: // toggle use of hw composer
3644 n = data.readInt32();
3645 mDebugDisableHWC = n ? 1 : 0;
3646 invalidateHwcGeometry();
3647 repaintEverything();
3648 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003649 case 1009: // toggle use of transform hint
3650 n = data.readInt32();
3651 mDebugDisableTransformHint = n ? 1 : 0;
3652 invalidateHwcGeometry();
3653 repaintEverything();
3654 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003656 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657 reply->writeInt32(0);
3658 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003659 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003660 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661 return NO_ERROR;
3662 case 1013: {
3663 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003664 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3665 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003666 return NO_ERROR;
3667 }
3668 case 1014: {
3669 // daltonize
3670 n = data.readInt32();
3671 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003672 case 1:
3673 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3674 break;
3675 case 2:
3676 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3677 break;
3678 case 3:
3679 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3680 break;
3681 default:
3682 mDaltonizer.setType(ColorBlindnessType::None);
3683 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003684 }
3685 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003686 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003687 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003688 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003689 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003690 invalidateHwcGeometry();
3691 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003692 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003694 case 1015: {
3695 // apply a color matrix
3696 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003697 if (n) {
3698 // color matrix is sent as mat3 matrix followed by vec3
3699 // offset, then packed into a mat4 where the last row is
3700 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003701 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003702 for (size_t j = 0; j < 4; j++) {
3703 mColorMatrix[i][j] = data.readFloat();
3704 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003705 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003706 } else {
3707 mColorMatrix = mat4();
3708 }
3709 invalidateHwcGeometry();
3710 repaintEverything();
3711 return NO_ERROR;
3712 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003713 // This is an experimental interface
3714 // Needs to be shifted to proper binder interface when we productize
3715 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003716 n = data.readInt32();
3717 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003718 return NO_ERROR;
3719 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003720 case 1017: {
3721 n = data.readInt32();
3722 mForceFullDamage = static_cast<bool>(n);
3723 return NO_ERROR;
3724 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003725 case 1018: { // Modify Choreographer's phase offset
3726 n = data.readInt32();
3727 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3728 return NO_ERROR;
3729 }
3730 case 1019: { // Modify SurfaceFlinger's phase offset
3731 n = data.readInt32();
3732 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3733 return NO_ERROR;
3734 }
Irvel468051e2016-06-13 16:44:44 -07003735 case 1020: { // Layer updates interceptor
3736 n = data.readInt32();
3737 if (n) {
3738 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003739 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003740 }
3741 else{
3742 ALOGV("Interceptor disabled");
3743 mInterceptor.disable();
3744 }
3745 return NO_ERROR;
3746 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003747 case 1021: { // Disable HWC virtual displays
3748 n = data.readInt32();
3749 mUseHwcVirtualDisplays = !n;
3750 return NO_ERROR;
3751 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003752 }
3753 }
3754 return err;
3755}
3756
Mathias Agopian53331da2011-08-22 21:44:41 -07003757void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003758 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003759 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003760}
3761
Mathias Agopian59119e62010-10-11 12:37:43 -07003762// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003763// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003764// ---------------------------------------------------------------------------
3765
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003766/* The code below is here to handle b/8734824
3767 *
3768 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003769 * from the surfaceflinger thread to the calling binder thread, where they
3770 * are executed. This allows the calling thread in the calling process to be
3771 * reused and not depend on having "enough" binder threads to handle the
3772 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003773 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003774class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003775 /* Parts of GraphicProducerWrapper are run on two different threads,
3776 * communicating by sending messages via Looper but also by shared member
3777 * data. Coherence maintenance is subtle and in places implicit (ugh).
3778 *
3779 * Don't rely on Looper's sendMessage/handleMessage providing
3780 * release/acquire semantics for any data not actually in the Message.
3781 * Data going from surfaceflinger to binder threads needs to be
3782 * synchronized explicitly.
3783 *
3784 * Barrier open/wait do provide release/acquire semantics. This provides
3785 * implicit synchronization for data coming back from binder to
3786 * surfaceflinger threads.
3787 */
3788
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003789 sp<IGraphicBufferProducer> impl;
3790 sp<Looper> looper;
3791 status_t result;
3792 bool exitPending;
3793 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003794 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 uint32_t code;
3796 Parcel const* data;
3797 Parcel* reply;
3798
3799 enum {
3800 MSG_API_CALL,
3801 MSG_EXIT
3802 };
3803
3804 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003805 * Called on surfaceflinger thread. This is called by our "fake"
3806 * BpGraphicBufferProducer. We package the data and reply Parcel and
3807 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003808 */
3809 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003810 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003811 this->code = code;
3812 this->data = &data;
3813 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003815 // if we've exited, we run the message synchronously right here.
3816 // note (JH): as far as I can tell from looking at the code, this
3817 // never actually happens. if it does, i'm not sure if it happens
3818 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003819 handleMessage(Message(MSG_API_CALL));
3820 } else {
3821 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003822 // Prevent stores to this->{code, data, reply} from being
3823 // reordered later than the construction of Message.
3824 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003825 looper->sendMessage(this, Message(MSG_API_CALL));
3826 barrier.wait();
3827 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003828 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829 }
3830
3831 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003832 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003833 * call the real BpGraphicBufferProducer.
3834 */
3835 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003836 int what = message.what;
3837 // Prevent reads below from happening before the read from Message
3838 atomic_thread_fence(memory_order_acquire);
3839 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003840 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003841 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003842 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003843 exitRequested = true;
3844 }
3845 }
3846
3847public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003848 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003849 : impl(impl),
3850 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003851 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003852 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003853 exitRequested(false),
3854 code(0),
3855 data(NULL),
3856 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003857 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003858
Jesse Hallb154c422014-07-13 12:47:02 -07003859 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003860 status_t waitForResponse() {
3861 do {
3862 looper->pollOnce(-1);
3863 } while (!exitRequested);
3864 return result;
3865 }
3866
Jesse Hallb154c422014-07-13 12:47:02 -07003867 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003868 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003869 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003870 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003871 // Ensure this->result is visible to the binder thread before it
3872 // handles the message.
3873 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003874 looper->sendMessage(this, Message(MSG_EXIT));
3875 }
3876};
3877
3878
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003879status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3880 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003881 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003882 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003883 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003884
3885 if (CC_UNLIKELY(display == 0))
3886 return BAD_VALUE;
3887
3888 if (CC_UNLIKELY(producer == 0))
3889 return BAD_VALUE;
3890
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003891 // if we have secure windows on this display, never allow the screen capture
3892 // unless the producer interface is local (i.e.: we can take a screenshot for
3893 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003894 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003895
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003896 // Convert to surfaceflinger's internal rotation type.
3897 Transform::orientation_flags rotationFlags;
3898 switch (rotation) {
3899 case ISurfaceComposer::eRotateNone:
3900 rotationFlags = Transform::ROT_0;
3901 break;
3902 case ISurfaceComposer::eRotate90:
3903 rotationFlags = Transform::ROT_90;
3904 break;
3905 case ISurfaceComposer::eRotate180:
3906 rotationFlags = Transform::ROT_180;
3907 break;
3908 case ISurfaceComposer::eRotate270:
3909 rotationFlags = Transform::ROT_270;
3910 break;
3911 default:
3912 rotationFlags = Transform::ROT_0;
3913 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3914 break;
3915 }
3916
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003917 class MessageCaptureScreen : public MessageBase {
3918 SurfaceFlinger* flinger;
3919 sp<IBinder> display;
3920 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003921 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003922 uint32_t reqWidth, reqHeight;
3923 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003924 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003925 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003927 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 public:
3929 MessageCaptureScreen(SurfaceFlinger* flinger,
3930 const sp<IBinder>& display,
3931 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003932 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003933 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003934 bool useIdentityTransform,
3935 Transform::orientation_flags rotation,
3936 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003937 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003938 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003939 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003940 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003941 rotation(rotation), result(PERMISSION_DENIED),
3942 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003943 {
3944 }
3945 status_t getResult() const {
3946 return result;
3947 }
3948 virtual bool handler() {
3949 Mutex::Autolock _l(flinger->mStateLock);
3950 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003951 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003952 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003953 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003954 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003955 return true;
3956 }
3957 };
3958
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003959 // this creates a "fake" BBinder which will serve as a "fake" remote
3960 // binder to receive the marshaled calls and forward them to the
3961 // real remote (a BpGraphicBufferProducer)
3962 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3963
3964 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3965 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003966 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003967 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003968 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003969 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003970
3971 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003972 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003973 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003974 }
3975 return res;
3976}
3977
Mathias Agopian180f10d2013-04-10 22:55:41 -07003978
3979void SurfaceFlinger::renderScreenImplLocked(
3980 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003981 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003982 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003983 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003984{
3985 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003986 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003987
3988 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003989 const int32_t hw_w = hw->getWidth();
3990 const int32_t hw_h = hw->getHeight();
3991 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003992 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003993
Dan Stozac1879002014-05-22 15:59:05 -07003994 // if a default or invalid sourceCrop is passed in, set reasonable values
3995 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3996 !sourceCrop.isValid()) {
3997 sourceCrop.setLeftTop(Point(0, 0));
3998 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3999 }
4000
4001 // ensure that sourceCrop is inside screen
4002 if (sourceCrop.left < 0) {
4003 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4004 }
Dan Stozabe31f442014-06-11 11:20:54 -07004005 if (sourceCrop.right > hw_w) {
4006 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004007 }
4008 if (sourceCrop.top < 0) {
4009 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4010 }
Dan Stozabe31f442014-06-11 11:20:54 -07004011 if (sourceCrop.bottom > hw_h) {
4012 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004013 }
4014
Mathias Agopian180f10d2013-04-10 22:55:41 -07004015 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004016 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004017
4018 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004019 engine.setViewportAndProjection(
4020 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004021 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022
4023 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004024 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004025
Robert Carr1f0a16a2016-10-24 16:27:39 -07004026 // We loop through the first level of layers without traversing,
4027 // as we need to interpret min/max layer Z in the top level Z space.
4028 for (const auto& layer : mDrawingState.layersSortedByZ) {
4029 if (layer->getLayerStack() != hw->getLayerStack()) {
4030 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004031 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004032 const Layer::State& state(layer->getDrawingState());
4033 if (state.z < minLayerZ || state.z > maxLayerZ) {
4034 continue;
4035 }
4036 layer->traverseInZOrder([&](Layer* layer) {
4037 if (!layer->isVisible()) {
4038 return;
4039 }
4040 if (filtering) layer->setFiltering(true);
4041 layer->draw(hw, useIdentityTransform);
4042 if (filtering) layer->setFiltering(false);
4043 });
4044 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004045
Mathias Agopian931bda12013-08-28 18:11:46 -07004046 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004047}
4048
4049
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004050status_t SurfaceFlinger::captureScreenImplLocked(
4051 const sp<const DisplayDevice>& hw,
4052 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004053 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004054 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004055 bool useIdentityTransform, Transform::orientation_flags rotation,
4056 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004057{
4058 ATRACE_CALL();
4059
Mathias Agopian180f10d2013-04-10 22:55:41 -07004060 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004061 uint32_t hw_w = hw->getWidth();
4062 uint32_t hw_h = hw->getHeight();
4063
4064 if (rotation & Transform::ROT_90) {
4065 std::swap(hw_w, hw_h);
4066 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004067
Mathias Agopian180f10d2013-04-10 22:55:41 -07004068 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4069 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4070 reqWidth, reqHeight, hw_w, hw_h);
4071 return BAD_VALUE;
4072 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004073
Mathias Agopian180f10d2013-04-10 22:55:41 -07004074 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4075 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4076
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004077 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004078 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004079 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004080 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4081 (state.z < minLayerZ || state.z > maxLayerZ)) {
4082 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004083 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004084 layer->traverseInZOrder([&](Layer *layer) {
4085 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4086 layer->isSecure());
4087 });
4088 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004089
4090 if (!isLocalScreenshot && secureLayerIsVisible) {
4091 ALOGW("FB is protected: PERMISSION_DENIED");
4092 return PERMISSION_DENIED;
4093 }
4094
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004095 // create a surface (because we're a producer, and we need to
4096 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004097 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004098
4099 // Put the screenshot Surface into async mode so that
4100 // Layer::headFenceHasSignaled will always return true and we'll latch the
4101 // first buffer regardless of whether or not its acquire fence has
4102 // signaled. This is needed to avoid a race condition in the rotation
4103 // animation. See b/30209608
4104 sur->setAsyncMode(true);
4105
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004106 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004107
Michael Lentine5a16a622015-05-21 13:48:24 -07004108 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4109 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004110 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4111 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004112
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004113 int err = 0;
4114 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004115 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004116 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4117 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004118
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004119 if (err == NO_ERROR) {
4120 ANativeWindowBuffer* buffer;
4121 /* TODO: Once we have the sync framework everywhere this can use
4122 * server-side waits on the fence that dequeueBuffer returns.
4123 */
4124 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4125 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004126 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004127 // create an EGLImage from the buffer so we can later
4128 // turn it into a texture
4129 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4130 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4131 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004132 // this binds the given EGLImage as a framebuffer for the
4133 // duration of this scope.
4134 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4135 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004136 // this will in fact render into our dequeued buffer
4137 // via an FBO, which means we didn't have to create
4138 // an EGLSurface and therefore we're not
4139 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004140 renderScreenImplLocked(
4141 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4142 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004143
Riley Andrews86639902014-08-15 12:27:24 -07004144 // Attempt to create a sync khr object that can produce a sync point. If that
4145 // isn't available, create a non-dupable sync object in the fallback path and
4146 // wait on it directly.
4147 EGLSyncKHR sync;
4148 if (!DEBUG_SCREENSHOTS) {
4149 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004150 // native fence fd will not be populated until flush() is done.
4151 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004152 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004153 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004154 }
Riley Andrews86639902014-08-15 12:27:24 -07004155 if (sync != EGL_NO_SYNC_KHR) {
4156 // get the sync fd
4157 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4158 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4159 ALOGW("captureScreen: failed to dup sync khr object");
4160 syncFd = -1;
4161 }
4162 eglDestroySyncKHR(mEGLDisplay, sync);
4163 } else {
4164 // fallback path
4165 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4166 if (sync != EGL_NO_SYNC_KHR) {
4167 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4168 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4169 EGLint eglErr = eglGetError();
4170 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4171 ALOGW("captureScreen: fence wait timed out");
4172 } else {
4173 ALOGW_IF(eglErr != EGL_SUCCESS,
4174 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4175 }
4176 eglDestroySyncKHR(mEGLDisplay, sync);
4177 } else {
4178 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4179 }
4180 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004181 if (DEBUG_SCREENSHOTS) {
4182 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4183 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4184 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4185 hw, minLayerZ, maxLayerZ);
4186 delete [] pixels;
4187 }
4188
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004189 } else {
4190 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4191 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004192 window->cancelBuffer(window, buffer, syncFd);
4193 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004194 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004195 // destroy our image
4196 eglDestroyImageKHR(mEGLDisplay, image);
4197 } else {
4198 result = BAD_VALUE;
4199 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004200 if (buffer) {
4201 // queueBuffer takes ownership of syncFd
4202 result = window->queueBuffer(window, buffer, syncFd);
4203 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004204 }
4205 } else {
4206 result = BAD_VALUE;
4207 }
4208 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4209 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004210
Mathias Agopian74c40c02010-09-29 13:02:36 -07004211 return result;
4212}
4213
Mathias Agopiand5556842013-09-19 17:08:37 -07004214void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004215 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004216 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004217 for (size_t y=0 ; y<h ; y++) {
4218 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4219 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004220 if (p[x] != 0xFF000000) return;
4221 }
4222 }
4223 ALOGE("*** we just took a black screenshot ***\n"
4224 "requested minz=%d, maxz=%d, layerStack=%d",
4225 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004226
Robert Carr2047fae2016-11-28 14:09:09 -08004227 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004228 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004229 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004230 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4231 state.z <= maxLayerZ) {
4232 layer->traverseInZOrder([&](Layer* layer) {
4233 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4234 layer->isVisible() ? '+' : '-',
4235 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004236 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004237 i++;
4238 });
4239 }
4240 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004241 }
4242}
4243
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004244// ---------------------------------------------------------------------------
4245
Robert Carr2047fae2016-11-28 14:09:09 -08004246void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4247 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004248}
4249
Robert Carr2047fae2016-11-28 14:09:09 -08004250void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4251 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004252}
4253
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004254}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004255
4256
4257#if defined(__gl_h_)
4258#error "don't include gl/gl.h in this file"
4259#endif
4260
4261#if defined(__gl2_h_)
4262#error "don't include gl2/gl2.h in this file"
4263#endif