blob: 98f6a70020115f4144d5639bbc9f10ba5d7157de [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>
Chia-I Wu527747d2017-03-13 20:38:48 +000047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080076#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Mathias Agopian99b49842011-06-27 16:05:52 -0700116
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700118 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700120 mTransactionPending(false),
121 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700122 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700123 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700124 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800125 mHwc(nullptr),
126 mRealHwc(nullptr),
127 mVrHwc(nullptr),
128 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800130 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800132 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800133 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800134 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700136 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700137 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700138 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700139 mDebugInSwapBuffers(0),
140 mLastSwapBufferTime(0),
141 mDebugInTransaction(0),
142 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700143 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700144 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800145 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000146 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700147 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700148 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800149 mHasColorMatrix(false),
150 mHasPoweredOff(false),
151 mFrameBuckets(),
152 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700153 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800154 mNumLayers(0)
155#ifdef USE_HWC2
156 ,mEnterVrMode(false)
157#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158{
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800159
160 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
161 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
162
163 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
164 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
165
Steve Blocka19954a2012-01-04 20:05:49 +0000166 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700168 useContextPriority = getBool< ISurfaceFlingerConfigs,
169 &ISurfaceFlingerConfigs::useContextPriority>(false);
170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 // debugging stuff...
172 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800174 // TODO (urbanus): remove once b/35319396 is fixed.
175 property_get("ro.boot.vr", value, "0");
176 mVrModeSupported = atoi(value);
177
Mathias Agopianb4b17302013-03-20 18:36:41 -0700178 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700179 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 property_get("debug.sf.showupdates", value, "0");
182 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700183
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700184 property_get("debug.sf.ddms", value, "0");
185 mDebugDDMS = atoi(value);
186 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700187 if (!startDdmConnection()) {
188 // start failed, and DDMS debugging not enabled
189 mDebugDDMS = 0;
190 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700191 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700192 ALOGI_IF(mDebugRegion, "showupdates enabled");
193 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700194
195 property_get("debug.sf.disable_backpressure", value, "0");
196 mPropagateBackpressure = !atoi(value);
197 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700198
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800199 property_get("debug.sf.enable_hwc_vds", value, "0");
200 mUseHwcVirtualDisplays = atoi(value);
201 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800202
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800203 property_get("ro.sf.disable_triple_buffer", value, "1");
204 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800205 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206}
207
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800208void SurfaceFlinger::onFirstRef()
209{
210 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800211}
212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213SurfaceFlinger::~SurfaceFlinger()
214{
Mathias Agopiana4912602012-07-12 14:25:33 -0700215 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
216 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
217 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800218
219 if (mVrStateCallbacks.get()) {
220 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
221 defaultServiceManager()->checkService(String16("vrmanager")));
222 if (vrManagerService.get()) {
223 vrManagerService->unregisterListener(mVrStateCallbacks);
224 }
225 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226}
227
Dan Stozac7014012014-02-14 15:03:43 -0800228void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229{
230 // the window manager died on us. prepare its eulogy.
231
Andy McFadden13a082e2012-08-24 10:16:42 -0700232 // restore initial conditions (default device unblank, etc)
233 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800234
235 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700236 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800237}
238
Robert Carr1db73f62016-12-21 12:58:51 -0800239static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700240 status_t err = client->initCheck();
241 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800242 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243 }
Robert Carr1db73f62016-12-21 12:58:51 -0800244 return nullptr;
245}
246
247sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
248 return initClient(new Client(this));
249}
250
251sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
252 const sp<IGraphicBufferProducer>& gbp) {
253 if (authenticateSurfaceTexture(gbp) == false) {
254 return nullptr;
255 }
256 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
257 if (layer == nullptr) {
258 return nullptr;
259 }
260
261 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262}
263
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700264sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
265 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700266{
267 class DisplayToken : public BBinder {
268 sp<SurfaceFlinger> flinger;
269 virtual ~DisplayToken() {
270 // no more references, this display must be terminated
271 Mutex::Autolock _l(flinger->mStateLock);
272 flinger->mCurrentState.displays.removeItem(this);
273 flinger->setTransactionFlags(eDisplayTransactionNeeded);
274 }
275 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700276 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277 : flinger(flinger) {
278 }
279 };
280
281 sp<BBinder> token = new DisplayToken(this);
282
283 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700284 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700285 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700286 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700287 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288 return token;
289}
290
Jesse Hall6c913be2013-08-08 12:15:49 -0700291void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
292 Mutex::Autolock _l(mStateLock);
293
294 ssize_t idx = mCurrentState.displays.indexOfKey(display);
295 if (idx < 0) {
296 ALOGW("destroyDisplay: invalid display token");
297 return;
298 }
299
300 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
301 if (!info.isVirtualDisplay()) {
302 ALOGE("destroyDisplay called for non-virtual display");
303 return;
304 }
Irvelffc9efc2016-07-27 15:16:37 -0700305 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700306 mCurrentState.displays.removeItemsAt(idx);
307 setTransactionFlags(eDisplayTransactionNeeded);
308}
309
Jesse Hall692c7232012-11-08 15:41:56 -0800310void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800311 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800312 ALOGW_IF(mBuiltinDisplays[type],
313 "Overwriting display token for display type %d", type);
314 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800315 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700316 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800317 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800319}
320
Mathias Agopiane57f2922012-08-09 16:29:12 -0700321sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700322 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700323 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
324 return NULL;
325 }
Jesse Hall692c7232012-11-08 15:41:56 -0800326 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700327}
328
Chia-I Wu527747d2017-03-13 20:38:48 +0000329sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
330{
331 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
332 return gba;
333}
334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335void SurfaceFlinger::bootFinished()
336{
Wei Wangb254fa32017-01-31 17:43:23 -0800337 if (mStartBootAnimThread->join() != NO_ERROR) {
338 ALOGE("Join StartBootAnimThread failed!");
339 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 const nsecs_t now = systemTime();
341 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000342 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700343 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700344
345 // wait patiently for the window manager death
346 const String16 name("window");
347 sp<IBinder> window(defaultServiceManager()->getService(name));
348 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700349 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700350 }
351
352 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700353 // formerly we would just kill the process, but we now ask it to exit so it
354 // can choose where to stop the animation.
355 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700356
357 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
358 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
359 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800360
361 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
362 defaultServiceManager()->checkService(String16("vrmanager")));
363 if (vrManagerService.get()) {
364 mVrStateCallbacks = new VrStateCallbacks(*this);
365 vrManagerService->registerListener(mVrStateCallbacks);
366 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800367}
368
Mathias Agopian3f844832013-08-07 21:24:32 -0700369void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700370 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700371 RenderEngine& engine;
372 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700373 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700374 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
375 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376 }
377 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 return true;
380 }
381 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383}
384
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700385class DispSyncSource : public VSyncSource, private DispSync::Callback {
386public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700387 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000388 const char* name) :
389 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700390 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700391 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000392 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
393 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700394 mDispSync(dispSync),
395 mCallbackMutex(),
396 mCallback(),
397 mVsyncMutex(),
398 mPhaseOffset(phaseOffset),
399 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401 virtual ~DispSyncSource() {}
402
403 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700404 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700405 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000406 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700407 static_cast<DispSync::Callback*>(this));
408 if (err != NO_ERROR) {
409 ALOGE("error registering vsync callback: %s (%d)",
410 strerror(-err), err);
411 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700412 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700413 } else {
414 status_t err = mDispSync->removeEventListener(
415 static_cast<DispSync::Callback*>(this));
416 if (err != NO_ERROR) {
417 ALOGE("error unregistering vsync callback: %s (%d)",
418 strerror(-err), err);
419 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700420 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700422 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 }
424
425 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700426 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 mCallback = callback;
428 }
429
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 virtual void setPhaseOffset(nsecs_t phaseOffset) {
431 Mutex::Autolock lock(mVsyncMutex);
432
433 // Normalize phaseOffset to [0, period)
434 auto period = mDispSync->getPeriod();
435 phaseOffset %= period;
436 if (phaseOffset < 0) {
437 // If we're here, then phaseOffset is in (-period, 0). After this
438 // operation, it will be in (0, period)
439 phaseOffset += period;
440 }
441 mPhaseOffset = phaseOffset;
442
443 // If we're not enabled, we don't need to mess with the listeners
444 if (!mEnabled) {
445 return;
446 }
447
448 // Remove the listener with the old offset
449 status_t err = mDispSync->removeEventListener(
450 static_cast<DispSync::Callback*>(this));
451 if (err != NO_ERROR) {
452 ALOGE("error unregistering vsync callback: %s (%d)",
453 strerror(-err), err);
454 }
455
456 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000457 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700458 static_cast<DispSync::Callback*>(this));
459 if (err != NO_ERROR) {
460 ALOGE("error registering vsync callback: %s (%d)",
461 strerror(-err), err);
462 }
463 }
464
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465private:
466 virtual void onDispSyncEvent(nsecs_t when) {
467 sp<VSyncSource::Callback> callback;
468 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 callback = mCallback;
471
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700472 if (mTraceVsync) {
473 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700474 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700475 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476 }
477
478 if (callback != NULL) {
479 callback->onVSyncEvent(when);
480 }
481 }
482
Tim Murray4a4e4a22016-04-19 16:29:23 +0000483 const char* const mName;
484
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 int mValue;
486
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700487 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700488 const String8 mVsyncOnLabel;
489 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700490
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700492
493 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700495
496 Mutex mVsyncMutex; // Protects the following
497 nsecs_t mPhaseOffset;
498 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499};
500
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700501class InjectVSyncSource : public VSyncSource {
502public:
503 InjectVSyncSource() {}
504
505 virtual ~InjectVSyncSource() {}
506
507 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
508 std::lock_guard<std::mutex> lock(mCallbackMutex);
509 mCallback = callback;
510 }
511
512 virtual void onInjectSyncEvent(nsecs_t when) {
513 std::lock_guard<std::mutex> lock(mCallbackMutex);
514 mCallback->onVSyncEvent(when);
515 }
516
517 virtual void setVSyncEnabled(bool) {}
518 virtual void setPhaseOffset(nsecs_t) {}
519
520private:
521 std::mutex mCallbackMutex; // Protects the following
522 sp<VSyncSource::Callback> mCallback;
523};
524
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700526 ALOGI( "SurfaceFlinger's main thread ready to run. "
527 "Initializing graphics H/W...");
528
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900529 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
530
Dan Stoza9e56aa02015-11-02 13:00:03 -0800531 { // Autolock scope
532 Mutex::Autolock _l(mStateLock);
533
534 // initialize EGL for the default display
535 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
536 eglInitialize(mEGLDisplay, NULL, NULL);
537
538 // start the EventThread
539 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
540 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700541 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
543 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700544 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800545 mEventQueue.setEventThread(mSFEventThread);
546
Tim Murrayacff43d2016-07-29 13:57:24 -0700547 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700548 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700549 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700550 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
551 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
552 }
553
Dan Stoza9e56aa02015-11-02 13:00:03 -0800554 // Get a RenderEngine for the given display / config (can't fail)
555 mRenderEngine = RenderEngine::create(mEGLDisplay,
556 HAL_PIXEL_FORMAT_RGBA_8888);
557 }
558
559 // Drop the state lock while we initialize the hardware composer. We drop
560 // the lock because on creation, it will call back into SurfaceFlinger to
561 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800562 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800563 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800564 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
566
Jesse Hall692c7232012-11-08 15:41:56 -0800567 Mutex::Autolock _l(mStateLock);
568
Mathias Agopian875d8e12013-06-07 15:35:48 -0700569 // retrieve the EGL context that was selected/created
570 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700571
Mathias Agopianda27af92012-09-13 18:17:13 -0700572 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
573 "couldn't create EGLContext");
574
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575 // make the GLContext current so that we can create textures when creating
576 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700577 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
578
Jamie Gennisd1700752013-10-14 12:22:52 -0700579 mEventControlThread = new EventControlThread(this);
580 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
581
Mathias Agopian92a979a2012-08-02 18:32:23 -0700582 // initialize our drawing state
583 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700584
Andy McFadden13a082e2012-08-24 10:16:42 -0700585 // set initial conditions (e.g. unblank default device)
586 initializeDisplays();
587
Dan Stoza4e637772016-07-28 13:31:51 -0700588 mRenderEngine->primeCache();
589
Wei Wangb254fa32017-01-31 17:43:23 -0800590 mStartBootAnimThread = new StartBootAnimThread();
591 if (mStartBootAnimThread->Start() != NO_ERROR) {
592 ALOGE("Run StartBootAnimThread failed!");
593 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700596}
597
Mathias Agopiana67e4182012-06-19 17:26:12 -0700598void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800599 // Start boot animation service by setting a property mailbox
600 // if property setting thread is already running, Start() will be just a NOP
601 mStartBootAnimThread->Start();
602 // Wait until property was set
603 if (mStartBootAnimThread->join() != NO_ERROR) {
604 ALOGE("Join StartBootAnimThread failed!");
605 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700606}
607
Mathias Agopian875d8e12013-06-07 15:35:48 -0700608size_t SurfaceFlinger::getMaxTextureSize() const {
609 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700610}
611
Mathias Agopian875d8e12013-06-07 15:35:48 -0700612size_t SurfaceFlinger::getMaxViewportDims() const {
613 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700614}
615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800616// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800617
Jamie Gennis582270d2011-08-17 18:19:00 -0700618bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800619 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800620 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800621 return authenticateSurfaceTextureLocked(bufferProducer);
622}
623
624bool SurfaceFlinger::authenticateSurfaceTextureLocked(
625 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800626 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700627 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800628}
629
Brian Anderson069b3652016-07-22 10:32:47 -0700630status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700631 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700632 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700633 FrameEvent::REQUESTED_PRESENT,
634 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700635 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700636 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700637 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700638 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700639 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700640 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700641 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700642 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700643 };
644 return NO_ERROR;
645}
646
Dan Stoza7f7da322014-05-02 15:26:25 -0700647status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
648 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700649 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700650 return BAD_VALUE;
651 }
652
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500653 if (!display.get())
654 return NAME_NOT_FOUND;
655
Jesse Hall692c7232012-11-08 15:41:56 -0800656 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700657 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800658 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700659 type = i;
660 break;
661 }
662 }
663
664 if (type < 0) {
665 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700666 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700667
Mathias Agopian8b736f12012-08-13 17:54:26 -0700668 // TODO: Not sure if display density should handled by SF any longer
669 class Density {
670 static int getDensityFromProperty(char const* propName) {
671 char property[PROPERTY_VALUE_MAX];
672 int density = 0;
673 if (property_get(propName, property, NULL) > 0) {
674 density = atoi(property);
675 }
676 return density;
677 }
678 public:
679 static int getEmuDensity() {
680 return getDensityFromProperty("qemu.sf.lcd_density"); }
681 static int getBuildDensity() {
682 return getDensityFromProperty("ro.sf.lcd_density"); }
683 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700684
Dan Stoza7f7da322014-05-02 15:26:25 -0700685 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700686
Dan Stoza9e56aa02015-11-02 13:00:03 -0800687 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700688 DisplayInfo info = DisplayInfo();
689
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 float xdpi = hwConfig->getDpiX();
691 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700692
693 if (type == DisplayDevice::DISPLAY_PRIMARY) {
694 // The density of the device is provided by a build property
695 float density = Density::getBuildDensity() / 160.0f;
696 if (density == 0) {
697 // the build doesn't provide a density -- this is wrong!
698 // use xdpi instead
699 ALOGE("ro.sf.lcd_density must be defined as a build property");
700 density = xdpi / 160.0f;
701 }
702 if (Density::getEmuDensity()) {
703 // if "qemu.sf.lcd_density" is specified, it overrides everything
704 xdpi = ydpi = density = Density::getEmuDensity();
705 density /= 160.0f;
706 }
707 info.density = density;
708
709 // TODO: this needs to go away (currently needed only by webkit)
710 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
711 info.orientation = hw->getOrientation();
712 } else {
713 // TODO: where should this value come from?
714 static const int TV_DENSITY = 213;
715 info.density = TV_DENSITY / 160.0f;
716 info.orientation = 0;
717 }
718
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 info.w = hwConfig->getWidth();
720 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700721 info.xdpi = xdpi;
722 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900724 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725
Andy McFadden91b2ca82014-06-13 14:04:23 -0700726 // This is how far in advance a buffer must be queued for
727 // presentation at a given time. If you want a buffer to appear
728 // on the screen at time N, you must submit the buffer before
729 // (N - presentationDeadline).
730 //
731 // Normally it's one full refresh period (to give SF a chance to
732 // latch the buffer), but this can be reduced by configuring a
733 // DispSync offset. Any additional delays introduced by the hardware
734 // composer or panel must be accounted for here.
735 //
736 // We add an additional 1ms to allow for processing time and
737 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800739 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700740
741 // All non-virtual displays are currently considered secure.
742 info.secure = true;
743
Michael Wright28f24d02016-07-12 13:30:53 -0700744 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 }
746
Dan Stoza7f7da322014-05-02 15:26:25 -0700747 return NO_ERROR;
748}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700749
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800750status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700751 DisplayStatInfo* stats) {
752 if (stats == NULL) {
753 return BAD_VALUE;
754 }
755
756 // FIXME for now we always return stats for the primary display
757 memset(stats, 0, sizeof(*stats));
758 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
759 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
760 return NO_ERROR;
761}
762
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700763int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800764 if (display == NULL) {
765 ALOGE("%s : display is NULL", __func__);
766 return BAD_VALUE;
767 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700768 sp<DisplayDevice> device(getDisplayDevice(display));
769 if (device != NULL) {
770 return device->getActiveConfig();
771 }
772 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700773}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700774
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700775void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
776 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
777 this);
778 int32_t type = hw->getDisplayType();
779 int currentMode = hw->getActiveConfig();
780
781 if (mode == currentMode) {
782 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
783 return;
784 }
785
786 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
787 ALOGW("Trying to set config for virtual display");
788 return;
789 }
790
791 hw->setActiveConfig(mode);
792 getHwComposer().setActiveConfig(type, mode);
793}
794
795status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
796 class MessageSetActiveConfig: public MessageBase {
797 SurfaceFlinger& mFlinger;
798 sp<IBinder> mDisplay;
799 int mMode;
800 public:
801 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
802 int mode) :
803 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
804 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700805 Vector<DisplayInfo> configs;
806 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700807 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700808 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700809 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700810 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700811 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700812 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
813 if (hw == NULL) {
814 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700815 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700816 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
817 ALOGW("Attempt to set active config = %d for virtual display",
818 mMode);
819 } else {
820 mFlinger.setActiveConfigInternal(hw, mMode);
821 }
822 return true;
823 }
824 };
825 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
826 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700827 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700828}
Michael Wright28f24d02016-07-12 13:30:53 -0700829status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
830 Vector<android_color_mode_t>* outColorModes) {
831 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
832 return BAD_VALUE;
833 }
834
835 if (!display.get()) {
836 return NAME_NOT_FOUND;
837 }
838
839 int32_t type = NAME_NOT_FOUND;
840 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
841 if (display == mBuiltinDisplays[i]) {
842 type = i;
843 break;
844 }
845 }
846
847 if (type < 0) {
848 return type;
849 }
850
851 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
852 outColorModes->clear();
853 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
854
855 return NO_ERROR;
856}
857
858android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
859 sp<DisplayDevice> device(getDisplayDevice(display));
860 if (device != nullptr) {
861 return device->getActiveColorMode();
862 }
863 return static_cast<android_color_mode_t>(BAD_VALUE);
864}
865
866void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
867 android_color_mode_t mode) {
868 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 android_color_mode_t currentMode = hw->getActiveColorMode();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveColorMode(mode);
884 getHwComposer().setActiveColorMode(type, mode);
885}
886
887
888status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
889 android_color_mode_t colorMode) {
890 class MessageSetActiveColorMode: public MessageBase {
891 SurfaceFlinger& mFlinger;
892 sp<IBinder> mDisplay;
893 android_color_mode_t mMode;
894 public:
895 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
896 android_color_mode_t mode) :
897 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
898 virtual bool handler() {
899 Vector<android_color_mode_t> modes;
900 mFlinger.getDisplayColorModes(mDisplay, &modes);
901 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
902 if (mMode < 0 || !exists) {
903 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
904 mDisplay.get());
905 return true;
906 }
907 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
908 if (hw == nullptr) {
909 ALOGE("Attempt to set active color mode = %d for null display %p",
910 mMode, mDisplay.get());
911 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
912 ALOGW("Attempt to set active color mode= %d for virtual display",
913 mMode);
914 } else {
915 mFlinger.setActiveColorModeInternal(hw, mMode);
916 }
917 return true;
918 }
919 };
920 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
921 postMessageSync(msg);
922 return NO_ERROR;
923}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700924
Svetoslavd85084b2014-03-20 10:28:31 -0700925status_t SurfaceFlinger::clearAnimationFrameStats() {
926 Mutex::Autolock _l(mStateLock);
927 mAnimFrameTracker.clearStats();
928 return NO_ERROR;
929}
930
931status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
932 Mutex::Autolock _l(mStateLock);
933 mAnimFrameTracker.getStats(outStats);
934 return NO_ERROR;
935}
936
Dan Stozac4f471e2016-03-24 09:31:08 -0700937status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
938 HdrCapabilities* outCapabilities) const {
939 Mutex::Autolock _l(mStateLock);
940
941 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
942 if (displayDevice == nullptr) {
943 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
944 return BAD_VALUE;
945 }
946
947 std::unique_ptr<HdrCapabilities> capabilities =
948 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
949 if (capabilities) {
950 std::swap(*outCapabilities, *capabilities);
951 } else {
952 return BAD_VALUE;
953 }
954
955 return NO_ERROR;
956}
957
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700958status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
959 if (enable == mInjectVSyncs) {
960 return NO_ERROR;
961 }
962
963 if (enable) {
964 mInjectVSyncs = enable;
965 ALOGV("VSync Injections enabled");
966 if (mVSyncInjector.get() == nullptr) {
967 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700968 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700969 }
970 mEventQueue.setEventThread(mInjectorEventThread);
971 } else {
972 mInjectVSyncs = enable;
973 ALOGV("VSync Injections disabled");
974 mEventQueue.setEventThread(mSFEventThread);
975 mVSyncInjector.clear();
976 }
977 return NO_ERROR;
978}
979
980status_t SurfaceFlinger::injectVSync(nsecs_t when) {
981 if (!mInjectVSyncs) {
982 ALOGE("VSync Injections not enabled");
983 return BAD_VALUE;
984 }
985 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
986 ALOGV("Injecting VSync inside SurfaceFlinger");
987 mVSyncInjector->onInjectSyncEvent(when);
988 }
989 return NO_ERROR;
990}
991
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800992// ----------------------------------------------------------------------------
993
994sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800995 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700996}
997
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800998// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800999
1000void SurfaceFlinger::waitForEvent() {
1001 mEventQueue.waitMessage();
1002}
1003
1004void SurfaceFlinger::signalTransaction() {
1005 mEventQueue.invalidate();
1006}
1007
1008void SurfaceFlinger::signalLayerUpdate() {
1009 mEventQueue.invalidate();
1010}
1011
1012void SurfaceFlinger::signalRefresh() {
1013 mEventQueue.refresh();
1014}
1015
1016status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001017 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001018 return mEventQueue.postMessage(msg, reltime);
1019}
1020
1021status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001022 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001023 status_t res = mEventQueue.postMessage(msg, reltime);
1024 if (res == NO_ERROR) {
1025 msg->wait();
1026 }
1027 return res;
1028}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001030void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001031 do {
1032 waitForEvent();
1033 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001034}
1035
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001036void SurfaceFlinger::enableHardwareVsync() {
1037 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001038 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001039 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001040 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1041 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001042 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001043 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001044}
1045
Jesse Hall948fe0c2013-10-14 12:56:09 -07001046void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001047 Mutex::Autolock _l(mHWVsyncLock);
1048
Jesse Hall948fe0c2013-10-14 12:56:09 -07001049 if (makeAvailable) {
1050 mHWVsyncAvailable = true;
1051 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001052 // Hardware vsync is not currently available, so abort the resync
1053 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001054 return;
1055 }
1056
Dan Stoza9e56aa02015-11-02 13:00:03 -08001057 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1058 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059
1060 mPrimaryDispSync.reset();
1061 mPrimaryDispSync.setPeriod(period);
1062
1063 if (!mPrimaryHWVsyncEnabled) {
1064 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001065 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1066 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001067 mPrimaryHWVsyncEnabled = true;
1068 }
1069}
1070
Jesse Hall948fe0c2013-10-14 12:56:09 -07001071void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072 Mutex::Autolock _l(mHWVsyncLock);
1073 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001074 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1075 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 mPrimaryDispSync.endResync();
1077 mPrimaryHWVsyncEnabled = false;
1078 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079 if (makeUnavailable) {
1080 mHWVsyncAvailable = false;
1081 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082}
1083
Tim Murray4a4e4a22016-04-19 16:29:23 +00001084void SurfaceFlinger::resyncWithRateLimit() {
1085 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1086 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001087 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001088 }
1089}
1090
Steven Thomas3cfac282017-02-06 12:29:30 -08001091void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1092 nsecs_t timestamp) {
1093 Mutex::Autolock lock(mStateLock);
1094 // Ignore any vsyncs from the non-active hardware composer.
1095 if (composer != mHwc) {
1096 return;
1097 }
1098
Jamie Gennisd1700752013-10-14 12:22:52 -07001099 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100
Jamie Gennisd1700752013-10-14 12:22:52 -07001101 { // Scope for the lock
1102 Mutex::Autolock _l(mHWVsyncLock);
1103 if (type == 0 && mPrimaryHWVsyncEnabled) {
1104 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001106 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001107
1108 if (needsHwVsync) {
1109 enableHardwareVsync();
1110 } else {
1111 disableHardwareVsync(false);
1112 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001113}
1114
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001115void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001116 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001117 *compositorTiming = mCompositorTiming;
1118}
1119
Dan Stoza9e56aa02015-11-02 13:00:03 -08001120void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1121 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1122 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1123 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001124
Dan Stoza9e56aa02015-11-02 13:00:03 -08001125 // All non-virtual displays are currently considered secure.
1126 bool isSecure = true;
1127
1128 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001129
1130 // When we're using the vr composer, the assumption is that we've
1131 // already created the IBinder object for the primary display.
1132 if (!mHwc->isUsingVrComposer()) {
1133 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1134 }
1135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136 wp<IBinder> token = mBuiltinDisplays[type];
1137
1138 sp<IGraphicBufferProducer> producer;
1139 sp<IGraphicBufferConsumer> consumer;
Chia-I Wu527747d2017-03-13 20:38:48 +00001140 BufferQueue::createBufferQueue(&producer, &consumer,
1141 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001142
1143 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1144 DisplayDevice::DISPLAY_PRIMARY, consumer);
1145 sp<DisplayDevice> hw = new DisplayDevice(this,
1146 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1147 producer, mRenderEngine->getEGLConfig());
1148 mDisplays.add(token, hw);
1149 } else {
1150 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001151 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001152 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001153 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001154 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001155 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1156 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001157 }
1158 setTransactionFlags(eDisplayTransactionNeeded);
1159
Andy McFadden9e9689c2012-10-10 18:17:51 -07001160 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001161 }
Mathias Agopian86303202012-07-24 22:46:10 -07001162}
1163
Steven Thomas3cfac282017-02-06 12:29:30 -08001164void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1165 Mutex::Autolock lock(mStateLock);
1166 if (composer == mHwc) {
1167 repaintEverything();
1168 } else {
1169 // This isn't from our current hardware composer. If it's a callback
1170 // from the real composer, forward the refresh request to vr
1171 // flinger. Otherwise ignore it.
1172 if (!composer->isUsingVrComposer()) {
1173 mVrFlinger->OnHardwareComposerRefresh();
1174 }
1175 }
1176}
1177
Dan Stoza9e56aa02015-11-02 13:00:03 -08001178void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001180 getHwComposer().setVsyncEnabled(disp,
1181 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001182}
1183
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001184void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1185 for (size_t i = 0; i < layers.size(); ++i) {
1186 layers[i]->clearHwcLayers();
1187 }
1188}
1189
1190void SurfaceFlinger::resetHwc() {
1191 disableHardwareVsync(true);
1192 clearHwcLayers(mDrawingState.layersSortedByZ);
1193 clearHwcLayers(mCurrentState.layersSortedByZ);
1194 // Clear the drawing state so that the logic inside of
1195 // handleTransactionLocked will fire. It will determine the delta between
1196 // mCurrentState and mDrawingState and re-apply all changes when we make the
1197 // transition.
1198 mDrawingState.displays.clear();
1199 mDisplays.clear();
1200}
1201
1202void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001203 bool enteringVrMode = mEnterVrMode;
1204 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1205 return;
1206 }
1207 if (enteringVrMode && !mVrHwc) {
1208 // Construct new HWComposer without holding any locks.
1209 mVrHwc = new HWComposer(true);
1210 ALOGV("Vr HWC created");
1211 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001212 {
1213 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001214
1215 if (enteringVrMode) {
1216 // Start vrflinger thread, if it hasn't been started already.
1217 if (!mVrFlinger) {
1218 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1219 int err = mVrFlinger->Run(mHwc->getComposer());
1220 if (err != NO_ERROR) {
1221 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1222 mVrFlinger.reset();
1223 mEnterVrMode = false;
1224 return;
1225 }
1226 }
1227
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001228 resetHwc();
1229
1230 mHwc = mVrHwc;
1231 mVrFlinger->EnterVrMode();
1232 } else {
1233 mVrFlinger->ExitVrMode();
1234
1235 resetHwc();
1236
1237 mHwc = mRealHwc;
1238 enableHardwareVsync();
1239 }
1240
1241 mVisibleRegionsDirty = true;
1242 invalidateHwcGeometry();
1243 android_atomic_or(1, &mRepaintEverything);
1244 setTransactionFlags(eDisplayTransactionNeeded);
1245 }
1246 if (mVrHwc) {
1247 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1248 }
1249}
1250
Mathias Agopian4fec8732012-06-29 14:12:52 -07001251void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001252 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001254 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001255 // TODO(eieio): Tied to a conditional until SELinux issues
1256 // are resolved.
1257 if (mVrModeSupported) {
1258 updateVrMode();
1259 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001260
Dan Stoza50182882016-07-08 12:02:20 -07001261 bool frameMissed = !mHadClientComposition &&
1262 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001263 (mPreviousPresentFence->getSignalTime() ==
1264 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001265 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001266 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001267 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001268 signalLayerUpdate();
1269 break;
1270 }
1271
Dan Stoza6b9454d2014-11-07 16:00:59 -08001272 bool refreshNeeded = handleMessageTransaction();
1273 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001274 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001275 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001276 // Signal a refresh if a transaction modified the window state,
1277 // a new buffer was latched, or if HWC has requested a full
1278 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001279 signalRefresh();
1280 }
1281 break;
1282 }
1283 case MessageQueue::REFRESH: {
1284 handleMessageRefresh();
1285 break;
1286 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287 }
1288}
1289
Dan Stoza6b9454d2014-11-07 16:00:59 -08001290bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001291 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001292 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001293 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001294 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001295 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001296 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001297}
1298
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001300 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001301 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001302}
1303
1304void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001305 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001306
Pablo Ceballos40845df2016-01-25 17:41:15 -08001307 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001308
Brian Andersond6927fb2016-07-23 23:37:30 -07001309 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001310 rebuildLayerStacks();
1311 setUpHWComposer();
1312 doDebugFlashRegions();
1313 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001314 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001315
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001316 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001317
1318 mHadClientComposition = false;
1319 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1320 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1321 mHadClientComposition = mHadClientComposition ||
1322 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1323 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001324
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001326}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001327
Mathias Agopiancd60f992012-08-16 16:28:27 -07001328void SurfaceFlinger::doDebugFlashRegions()
1329{
1330 // is debugging enabled
1331 if (CC_LIKELY(!mDebugRegion))
1332 return;
1333
1334 const bool repaintEverything = mRepaintEverything;
1335 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1336 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001337 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338 // transform the dirty region into this screen's coordinate space
1339 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1340 if (!dirtyRegion.isEmpty()) {
1341 // redraw the whole screen
1342 doComposeSurfaces(hw, Region(hw->bounds()));
1343
1344 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001345 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001346 RenderEngine& engine(getRenderEngine());
1347 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1348
Mathias Agopianda27af92012-09-13 18:17:13 -07001349 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001350 }
1351 }
1352 }
1353
1354 postFramebuffer();
1355
1356 if (mDebugRegion > 1) {
1357 usleep(mDebugRegion * 1000);
1358 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001359
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001361 auto& displayDevice = mDisplays[displayId];
1362 if (!displayDevice->isDisplayOn()) {
1363 continue;
1364 }
1365
1366 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1368 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001369 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001370}
1371
Brian Andersond6927fb2016-07-23 23:37:30 -07001372void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 ATRACE_CALL();
1375 ALOGV("preComposition");
1376
Mathias Agopiancd60f992012-08-16 16:28:27 -07001377 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001378 mDrawingState.traverseInZOrder([&](Layer* layer) {
1379 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380 needExtraInvalidate = true;
1381 }
Robert Carr2047fae2016-11-28 14:09:09 -08001382 });
1383
Mathias Agopiancd60f992012-08-16 16:28:27 -07001384 if (needExtraInvalidate) {
1385 signalLayerUpdate();
1386 }
1387}
1388
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389void SurfaceFlinger::updateCompositorTiming(
1390 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1391 std::shared_ptr<FenceTime>& presentFenceTime) {
1392 // Update queue of past composite+present times and determine the
1393 // most recently known composite to present latency.
1394 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1395 nsecs_t compositeToPresentLatency = -1;
1396 while (!mCompositePresentTimes.empty()) {
1397 CompositePresentTime& cpt = mCompositePresentTimes.front();
1398 // Cached values should have been updated before calling this method,
1399 // which helps avoid duplicate syscalls.
1400 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1401 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1402 break;
1403 }
1404 compositeToPresentLatency = displayTime - cpt.composite;
1405 mCompositePresentTimes.pop();
1406 }
1407
1408 // Don't let mCompositePresentTimes grow unbounded, just in case.
1409 while (mCompositePresentTimes.size() > 16) {
1410 mCompositePresentTimes.pop();
1411 }
1412
Brian Andersond0010582017-03-07 13:20:31 -08001413 setCompositorTimingSnapped(
1414 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1415}
1416
1417void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1418 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001419 // Integer division and modulo round toward 0 not -inf, so we need to
1420 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001421 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001422 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1423 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1424
Brian Andersond0010582017-03-07 13:20:31 -08001425 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1426 if (idealLatency <= 0) {
1427 idealLatency = vsyncInterval;
1428 }
1429
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 // Snap the latency to a value that removes scheduling jitter from the
1431 // composition and present times, which often have >1ms of jitter.
1432 // Reducing jitter is important if an app attempts to extrapolate
1433 // something (such as user input) to an accurate diasplay time.
1434 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1435 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001436 nsecs_t bias = vsyncInterval / 2;
1437 int64_t extraVsyncs =
1438 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1439 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1440 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001441
Brian Andersond0010582017-03-07 13:20:31 -08001442 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001443 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1444 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001445 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446}
1447
1448void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 ATRACE_CALL();
1451 ALOGV("postComposition");
1452
Brian Anderson3546a3f2016-07-14 11:51:14 -07001453 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001454 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001455 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001456 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001457 }
1458
Brian Andersond6927fb2016-07-23 23:37:30 -07001459 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001460
1461 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1462 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1463 glCompositionDoneFenceTime =
1464 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1465 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1466 } else {
1467 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1468 }
1469 mGlCompositionDoneTimeline.updateSignalTimes();
1470
1471 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1472 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1473 mDisplayTimeline.push(displayFenceTime);
1474 mDisplayTimeline.updateSignalTimes();
1475
1476 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1477 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1478 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1479 presentFenceTime = &displayFenceTime;
1480 } else {
1481 retireFenceTime = &displayFenceTime;
1482 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001483
1484 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1485 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1486
1487 // We use the refreshStartTime which might be sampled a little later than
1488 // when we started doing work for this frame, but that should be okay
1489 // since updateCompositorTiming has snapping logic.
1490 updateCompositorTiming(
1491 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001492 CompositorTiming compositorTiming;
1493 {
1494 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1495 compositorTiming = mCompositorTiming;
1496 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497
Robert Carr2047fae2016-11-28 14:09:09 -08001498 mDrawingState.traverseInZOrder([&](Layer* layer) {
1499 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Andersond0010582017-03-07 13:20:31 -08001500 *presentFenceTime, *retireFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001501 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001502 recordBufferingStats(layer->getName().string(),
1503 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001504 }
Robert Carr2047fae2016-11-28 14:09:09 -08001505 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001506
Brian Anderson3d4039d2016-09-23 16:31:30 -07001507 if (displayFence->isValid()) {
1508 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001509 enableHardwareVsync();
1510 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001511 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001512 }
1513 }
1514
Andy McFadden5167ec62014-05-22 13:08:43 -07001515 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001516 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001517 enableHardwareVsync();
1518 }
1519 }
1520
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001521 if (mAnimCompositionPending) {
1522 mAnimCompositionPending = false;
1523
Brian Anderson3d4039d2016-09-23 16:31:30 -07001524 if (displayFenceTime->isValid()) {
1525 mAnimFrameTracker.setActualPresentFence(
1526 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001527 } else {
1528 // The HWC doesn't support present fences, so use the refresh
1529 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001530 nsecs_t presentTime =
1531 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001532 mAnimFrameTracker.setActualPresentTime(presentTime);
1533 }
1534 mAnimFrameTracker.advanceFrame();
1535 }
Dan Stozab90cf072015-03-05 11:05:59 -08001536
1537 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1538 return;
1539 }
1540
1541 nsecs_t currentTime = systemTime();
1542 if (mHasPoweredOff) {
1543 mHasPoweredOff = false;
1544 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001545 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001547 if (numPeriods < NUM_BUCKETS - 1) {
1548 mFrameBuckets[numPeriods] += elapsedTime;
1549 } else {
1550 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1551 }
1552 mTotalTime += elapsedTime;
1553 }
1554 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
1556
1557void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 ATRACE_CALL();
1559 ALOGV("rebuildLayerStacks");
1560
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001562 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1563 ATRACE_CALL();
1564 mVisibleRegionsDirty = false;
1565 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001566
Jeff Sharkey76488112017-02-27 14:15:18 -07001567 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1568 Region opaqueRegion;
1569 Region dirtyRegion;
1570 Vector<sp<Layer>> layersSortedByZ;
1571 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1572 const Transform& tr(displayDevice->getTransform());
1573 const Rect bounds(displayDevice->getBounds());
1574 if (displayDevice->isDisplayOn()) {
1575 computeVisibleRegions(
1576 displayDevice->getLayerStack(), dirtyRegion,
1577 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001578
Jeff Sharkey76488112017-02-27 14:15:18 -07001579 mDrawingState.traverseInZOrder([&](Layer* layer) {
1580 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1581 Region drawRegion(tr.transform(
1582 layer->visibleNonTransparentRegion));
1583 drawRegion.andSelf(bounds);
1584 if (!drawRegion.isEmpty()) {
1585 layersSortedByZ.add(layer);
1586 } else {
1587 // Clear out the HWC layer if this layer was
1588 // previously visible, but no longer is
1589 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1590 nullptr);
1591 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001592 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001593 // WM changes displayDevice->layerStack upon sleep/awake.
1594 // Here we make sure we delete the HWC layers even if
1595 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001596 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1597 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001598 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001599 });
1600 }
1601 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1602 displayDevice->undefinedRegion.set(bounds);
1603 displayDevice->undefinedRegion.subtractSelf(
1604 tr.transform(opaqueRegion));
1605 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001606 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001607 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001609
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001611 ATRACE_CALL();
1612 ALOGV("setUpHWComposer");
1613
Jesse Hall028dc8f2013-08-20 16:35:32 -07001614 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001615 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1616 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1617 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1618
1619 // If nothing has changed (!dirty), don't recompose.
1620 // If something changed, but we don't currently have any visible layers,
1621 // and didn't when we last did a composition, then skip it this time.
1622 // The second rule does two things:
1623 // - When all layers are removed from a display, we'll emit one black
1624 // frame, then nothing more until we get new layers.
1625 // - When a display is created with a private layer stack, we won't
1626 // emit any black frames until a layer is added to the layer stack.
1627 bool mustRecompose = dirty && !(empty && wasEmpty);
1628
1629 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1630 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1631 mustRecompose ? "doing" : "skipping",
1632 dirty ? "+" : "-",
1633 empty ? "+" : "-",
1634 wasEmpty ? "+" : "-");
1635
Dan Stoza71433162014-02-04 16:22:36 -08001636 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001637
1638 if (mustRecompose) {
1639 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1640 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001641 }
1642
Dan Stoza9e56aa02015-11-02 13:00:03 -08001643 // build the h/w work list
1644 if (CC_UNLIKELY(mGeometryInvalid)) {
1645 mGeometryInvalid = false;
1646 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1647 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1648 const auto hwcId = displayDevice->getHwcDisplayId();
1649 if (hwcId >= 0) {
1650 const Vector<sp<Layer>>& currentLayers(
1651 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001652 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001653 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 if (!layer->hasHwcLayer(hwcId)) {
1655 auto hwcLayer = mHwc->createLayer(hwcId);
1656 if (hwcLayer) {
1657 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1658 } else {
1659 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001661 }
1662 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001663
Robert Carrae060832016-11-28 10:51:00 -08001664 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001665 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001667 }
1668 }
1669 }
1670 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 }
Riley Andrews03414a12014-07-01 14:22:59 -07001672
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001673
1674 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1675
Dan Stoza9e56aa02015-11-02 13:00:03 -08001676 // Set the per-frame data
1677 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1678 auto& displayDevice = mDisplays[displayId];
1679 const auto hwcId = displayDevice->getHwcDisplayId();
1680 if (hwcId < 0) {
1681 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001682 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001683 if (colorMatrix != mPreviousColorMatrix) {
1684 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1685 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1686 "display %zd: %d", displayId, result);
1687 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001688 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1689 layer->setPerFrameData(displayDevice);
1690 }
1691 }
1692
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001693 mPreviousColorMatrix = colorMatrix;
1694
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001696 auto& displayDevice = mDisplays[displayId];
1697 if (!displayDevice->isDisplayOn()) {
1698 continue;
1699 }
1700
1701 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1703 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001704 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001706
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707void SurfaceFlinger::doComposition() {
1708 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 ALOGV("doComposition");
1710
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001711 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001712 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001713 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001714 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 // transform the dirty region into this screen's coordinate space
1716 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001717
1718 // repaint the framebuffer (if needed)
1719 doDisplayComposition(hw, dirtyRegion);
1720
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721 hw->dirtyRegion.clear();
1722 hw->flip(hw->swapRegion);
1723 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001724 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001726 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001727}
1728
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001729void SurfaceFlinger::postFramebuffer()
1730{
Mathias Agopian841cde52012-03-01 15:44:37 -08001731 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001733
Mathias Agopiana44b0412011-10-16 18:46:35 -07001734 const nsecs_t now = systemTime();
1735 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001736
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1738 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001739 if (!displayDevice->isDisplayOn()) {
1740 continue;
1741 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 const auto hwcId = displayDevice->getHwcDisplayId();
1743 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001744 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001745 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001746 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001747 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001748 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1749 sp<Fence> releaseFence = Fence::NO_FENCE;
1750 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1751 releaseFence = displayDevice->getClientTargetAcquireFence();
1752 } else {
1753 auto hwcLayer = layer->getHwcLayer(hwcId);
1754 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001755 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 layer->onLayerDisplayed(releaseFence);
1757 }
1758 if (hwcId >= 0) {
1759 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001760 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001761 }
1762
Mathias Agopiana44b0412011-10-16 18:46:35 -07001763 mLastSwapBufferTime = systemTime() - now;
1764 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001765
1766 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1767 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1768 logFrameStats();
1769 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001770}
1771
Mathias Agopian87baae12012-07-31 12:38:26 -07001772void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773{
Mathias Agopian841cde52012-03-01 15:44:37 -08001774 ATRACE_CALL();
1775
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001776 // here we keep a copy of the drawing state (that is the state that's
1777 // going to be overwritten by handleTransactionLocked()) outside of
1778 // mStateLock so that the side-effects of the State assignment
1779 // don't happen with mStateLock held (which can cause deadlocks).
1780 State drawingState(mDrawingState);
1781
Mathias Agopianca4d3602011-05-19 15:38:14 -07001782 Mutex::Autolock _l(mStateLock);
1783 const nsecs_t now = systemTime();
1784 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001785
Mathias Agopianca4d3602011-05-19 15:38:14 -07001786 // Here we're guaranteed that some transaction flags are set
1787 // so we can call handleTransactionLocked() unconditionally.
1788 // We call getTransactionFlags(), which will also clear the flags,
1789 // with mStateLock held to guarantee that mCurrentState won't change
1790 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001791
Mathias Agopiane57f2922012-08-09 16:29:12 -07001792 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001793 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001794
Mathias Agopianca4d3602011-05-19 15:38:14 -07001795 mLastTransactionTime = systemTime() - now;
1796 mDebugInTransaction = 0;
1797 invalidateHwcGeometry();
1798 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001799}
1800
Mathias Agopian87baae12012-07-31 12:38:26 -07001801void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001802{
Dan Stoza7dde5992015-05-22 09:51:44 -07001803 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001804 mCurrentState.traverseInZOrder([](Layer* layer) {
1805 layer->notifyAvailableFrames();
1806 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001807
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001808 /*
1809 * Traversal of the children
1810 * (perform the transaction for each of them if needed)
1811 */
1812
Mathias Agopian3559b072012-08-15 13:46:03 -07001813 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001814 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001816 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001817
1818 const uint32_t flags = layer->doTransaction(0);
1819 if (flags & Layer::eVisibleRegion)
1820 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001821 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822 }
1823
1824 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001825 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001826 */
1827
Mathias Agopiane57f2922012-08-09 16:29:12 -07001828 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001829 // here we take advantage of Vector's copy-on-write semantics to
1830 // improve performance by skipping the transaction entirely when
1831 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001832 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1833 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001835 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001836 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001837 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001838
1839 // find the displays that were removed
1840 // (ie: in drawing state but not in current state)
1841 // also handle displays that changed
1842 // (ie: displays that are in both lists)
1843 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001844 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1845 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001846 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001847 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001848 // Call makeCurrent() on the primary display so we can
1849 // be sure that nothing associated with this display
1850 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001851 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001852 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001853 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1854 if (hw != NULL)
1855 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001856 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001857 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001858 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001859 } else {
1860 ALOGW("trying to remove the main display");
1861 }
1862 } else {
1863 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001864 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001865 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001866 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1867 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001868 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001869 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001870 // recreating the DisplayDevice, so we just remove it
1871 // from the drawing state, so that it get re-added
1872 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001873 sp<DisplayDevice> hw(getDisplayDevice(display));
1874 if (hw != NULL)
1875 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001876 mDisplays.removeItem(display);
1877 mDrawingState.displays.removeItemsAt(i);
1878 dc--; i--;
1879 // at this point we must loop to the next item
1880 continue;
1881 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001882
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001883 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001884 if (disp != NULL) {
1885 if (state.layerStack != draw[i].layerStack) {
1886 disp->setLayerStack(state.layerStack);
1887 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001888 if ((state.orientation != draw[i].orientation)
1889 || (state.viewport != draw[i].viewport)
1890 || (state.frame != draw[i].frame))
1891 {
1892 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001893 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001894 }
Michael Lentine47e45402014-07-18 15:34:25 -07001895 if (state.width != draw[i].width || state.height != draw[i].height) {
1896 disp->setDisplaySize(state.width, state.height);
1897 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001898 }
1899 }
1900 }
1901
1902 // find displays that were added
1903 // (ie: in current state but not in drawing state)
1904 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001905 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001906 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001907
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001908 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001909 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001910 sp<IGraphicBufferProducer> bqProducer;
1911 sp<IGraphicBufferConsumer> bqConsumer;
Chia-I Wu527747d2017-03-13 20:38:48 +00001912 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1913 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001914
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001916 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001917 // Virtual displays without a surface are dormant:
1918 // they have external state (layer stack, projection,
1919 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001920 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001921
Dan Stoza8cf150a2016-08-02 10:27:31 -07001922 if (mUseHwcVirtualDisplays) {
1923 int width = 0;
1924 int status = state.surface->query(
1925 NATIVE_WINDOW_WIDTH, &width);
1926 ALOGE_IF(status != NO_ERROR,
1927 "Unable to query width (%d)", status);
1928 int height = 0;
1929 status = state.surface->query(
1930 NATIVE_WINDOW_HEIGHT, &height);
1931 ALOGE_IF(status != NO_ERROR,
1932 "Unable to query height (%d)", status);
1933 int intFormat = 0;
1934 status = state.surface->query(
1935 NATIVE_WINDOW_FORMAT, &intFormat);
1936 ALOGE_IF(status != NO_ERROR,
1937 "Unable to query format (%d)", status);
1938 auto format = static_cast<android_pixel_format_t>(
1939 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001940
Dan Stoza8cf150a2016-08-02 10:27:31 -07001941 mHwc->allocateVirtualDisplay(width, height, &format,
1942 &hwcId);
1943 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944
Dan Stoza5cf424b2016-05-20 14:02:39 -07001945 // TODO: Plumb requested format back up to consumer
1946
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 sp<VirtualDisplaySurface> vds =
1948 new VirtualDisplaySurface(*mHwc,
1949 hwcId, state.surface, bqProducer,
1950 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001951
1952 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001953 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001954 }
1955 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001956 ALOGE_IF(state.surface!=NULL,
1957 "adding a supported display, but rendering "
1958 "surface is provided (%p), ignoring it",
1959 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001960
1961 hwcId = state.type;
1962 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1963 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001964 }
1965
1966 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001967 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001968 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969 state.type, hwcId, state.isSecure, display,
1970 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001971 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001972 hw->setLayerStack(state.layerStack);
1973 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001974 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001975 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001976 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001978 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001979 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001980 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001981 }
1982 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001984 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985
Mathias Agopian84300952012-11-21 16:02:13 -08001986 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1987 // The transform hint might have changed for some layers
1988 // (either because a display has changed, or because a layer
1989 // as changed).
1990 //
1991 // Walk through all the layers in currentLayers,
1992 // and update their transform hint.
1993 //
1994 // If a layer is visible only on a single display, then that
1995 // display is used to calculate the hint, otherwise we use the
1996 // default display.
1997 //
1998 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1999 // the hint is set before we acquire a buffer from the surface texture.
2000 //
2001 // NOTE: layer transactions have taken place already, so we use their
2002 // drawing state. However, SurfaceFlinger's own transaction has not
2003 // happened yet, so we must use the current state layer list
2004 // (soon to become the drawing state list).
2005 //
2006 sp<const DisplayDevice> disp;
2007 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002008 bool first = true;
2009 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002010 // NOTE: we rely on the fact that layers are sorted by
2011 // layerStack first (so we don't have to traverse the list
2012 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002013 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002014 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002015 currentlayerStack = layerStack;
2016 // figure out if this layerstack is mirrored
2017 // (more than one display) if so, pick the default display,
2018 // if not, pick the only display it's on.
2019 disp.clear();
2020 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2021 sp<const DisplayDevice> hw(mDisplays[dpy]);
2022 if (hw->getLayerStack() == currentlayerStack) {
2023 if (disp == NULL) {
2024 disp = hw;
2025 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002026 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002027 break;
2028 }
2029 }
2030 }
2031 }
Chet Haase91d25932013-04-11 15:24:55 -07002032 if (disp == NULL) {
2033 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2034 // redraw after transform hint changes. See bug 8508397.
2035
2036 // could be null when this layer is using a layerStack
2037 // that is not visible on any display. Also can occur at
2038 // screen off/on times.
2039 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002040 }
Chet Haase91d25932013-04-11 15:24:55 -07002041 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002042
2043 first = false;
2044 });
Mathias Agopian84300952012-11-21 16:02:13 -08002045 }
2046
2047
Mathias Agopian3559b072012-08-15 13:46:03 -07002048 /*
2049 * Perform our own transaction if needed
2050 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002051
2052 if (mLayersAdded) {
2053 mLayersAdded = false;
2054 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002055 mVisibleRegionsDirty = true;
2056 }
2057
2058 // some layers might have been removed, so
2059 // we need to update the regions they're exposing.
2060 if (mLayersRemoved) {
2061 mLayersRemoved = false;
2062 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002063 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002064 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002065 // this layer is not visible anymore
2066 // TODO: we could traverse the tree from front to back and
2067 // compute the actual visible region
2068 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002069 Region visibleReg;
2070 visibleReg.set(layer->computeScreenBounds());
2071 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002072 }
Robert Carr2047fae2016-11-28 14:09:09 -08002073 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 }
2075
2076 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002077
2078 updateCursorAsync();
2079}
2080
2081void SurfaceFlinger::updateCursorAsync()
2082{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2084 auto& displayDevice = mDisplays[displayId];
2085 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002086 continue;
2087 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088
2089 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2090 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002091 }
2092 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002093}
2094
2095void SurfaceFlinger::commitTransaction()
2096{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002097 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002099 for (const auto& l : mLayersPendingRemoval) {
2100 recordBufferingStats(l->getName().string(),
2101 l->getOccupancyHistory(true));
2102 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 }
2104 mLayersPendingRemoval.clear();
2105 }
2106
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002107 // If this transaction is part of a window animation then the next frame
2108 // we composite should be considered an animation as well.
2109 mAnimCompositionPending = mAnimTransactionPending;
2110
Mathias Agopian4fec8732012-06-29 14:12:52 -07002111 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002112 mDrawingState.traverseInZOrder([](Layer* layer) {
2113 layer->commitChildList();
2114 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002115 mTransactionPending = false;
2116 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002117 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118}
2119
Robert Carr2047fae2016-11-28 14:09:09 -08002120void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002121 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122{
Mathias Agopian841cde52012-03-01 15:44:37 -08002123 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 Region aboveOpaqueLayers;
2127 Region aboveCoveredLayers;
2128 Region dirty;
2129
Mathias Agopian87baae12012-07-31 12:38:26 -07002130 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131
Robert Carr2047fae2016-11-28 14:09:09 -08002132 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002134 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135
Jesse Hall01e29052013-02-19 16:13:35 -08002136 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002137 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002138 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002139
Mathias Agopianab028732010-03-16 16:41:46 -07002140 /*
2141 * opaqueRegion: area of a surface that is fully opaque.
2142 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002144
2145 /*
2146 * visibleRegion: area of a surface that is visible on screen
2147 * and not fully transparent. This is essentially the layer's
2148 * footprint minus the opaque regions above it.
2149 * Areas covered by a translucent surface are considered visible.
2150 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002152
2153 /*
2154 * coveredRegion: area of a surface that is covered by all
2155 * visible regions above it (which includes the translucent areas).
2156 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002158
Jesse Halla8026d22012-09-25 13:25:04 -07002159 /*
2160 * transparentRegion: area of a surface that is hinted to be completely
2161 * transparent. This is only used to tell when the layer has no visible
2162 * non-transparent regions and can be removed from the layer list. It
2163 * does not affect the visibleRegion of this layer or any layers
2164 * beneath it. The hint may not be correct if apps don't respect the
2165 * SurfaceView restrictions (which, sadly, some don't).
2166 */
2167 Region transparentRegion;
2168
Mathias Agopianab028732010-03-16 16:41:46 -07002169
2170 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002171 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002172 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002173 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002175 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002176 if (!visibleRegion.isEmpty()) {
2177 // Remove the transparent area from the visible region
2178 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002179 if (tr.preserveRects()) {
2180 // transform the transparent region
2181 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002182 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002183 // transformation too complex, can't do the
2184 // transparent region optimization.
2185 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002186 }
Mathias Agopianab028732010-03-16 16:41:46 -07002187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188
Mathias Agopianab028732010-03-16 16:41:46 -07002189 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002190 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002192 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2193 // the opaque region is the layer's footprint
2194 opaqueRegion = visibleRegion;
2195 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002196 }
2197 }
2198
Mathias Agopianab028732010-03-16 16:41:46 -07002199 // Clip the covered region to the visible region
2200 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2201
2202 // Update aboveCoveredLayers for next (lower) layer
2203 aboveCoveredLayers.orSelf(visibleRegion);
2204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205 // subtract the opaque region covered by the layers above us
2206 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002207
2208 // compute this layer's dirty region
2209 if (layer->contentDirty) {
2210 // we need to invalidate the whole region
2211 dirty = visibleRegion;
2212 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002213 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214 layer->contentDirty = false;
2215 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002216 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002217 * the exposed region consists of two components:
2218 * 1) what's VISIBLE now and was COVERED before
2219 * 2) what's EXPOSED now less what was EXPOSED before
2220 *
2221 * note that (1) is conservative, we start with the whole
2222 * visible region but only keep what used to be covered by
2223 * something -- which mean it may have been exposed.
2224 *
2225 * (2) handles areas that were not covered by anything but got
2226 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002227 */
Mathias Agopianab028732010-03-16 16:41:46 -07002228 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229 const Region oldVisibleRegion = layer->visibleRegion;
2230 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002231 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2232 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233 }
2234 dirty.subtractSelf(aboveOpaqueLayers);
2235
2236 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002237 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238
Mathias Agopianab028732010-03-16 16:41:46 -07002239 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002241
Jesse Halla8026d22012-09-25 13:25:04 -07002242 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243 layer->setVisibleRegion(visibleRegion);
2244 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002245 layer->setVisibleNonTransparentRegion(
2246 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002247 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248
Mathias Agopian87baae12012-07-31 12:38:26 -07002249 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250}
2251
Mathias Agopian87baae12012-07-31 12:38:26 -07002252void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2253 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002254 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002255 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2256 if (hw->getLayerStack() == layerStack) {
2257 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002258 }
2259 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002260}
2261
Dan Stoza6b9454d2014-11-07 16:00:59 -08002262bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002263{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264 ALOGV("handlePageFlip");
2265
Brian Andersond6927fb2016-07-23 23:37:30 -07002266 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002267
Mathias Agopian4fec8732012-06-29 14:12:52 -07002268 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002269 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002270
2271 // Store the set of layers that need updates. This set must not change as
2272 // buffers are being latched, as this could result in a deadlock.
2273 // Example: Two producers share the same command stream and:
2274 // 1.) Layer 0 is latched
2275 // 2.) Layer 0 gets a new frame
2276 // 2.) Layer 1 gets a new frame
2277 // 3.) Layer 1 is latched.
2278 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2279 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002280 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002281 if (layer->hasQueuedFrame()) {
2282 frameQueued = true;
2283 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002284 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002285 } else {
2286 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002287 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002288 } else {
2289 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002290 }
Robert Carr2047fae2016-11-28 14:09:09 -08002291 });
2292
Dan Stoza9e56aa02015-11-02 13:00:03 -08002293 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002294 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002295 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002296 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002297 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002298
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002299 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002300
2301 // If we will need to wake up at some time in the future to deal with a
2302 // queued frame that shouldn't be displayed during this vsync period, wake
2303 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002305 signalLayerUpdate();
2306 }
2307
2308 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310}
2311
Mathias Agopianad456f92011-01-13 17:53:01 -08002312void SurfaceFlinger::invalidateHwcGeometry()
2313{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002315}
2316
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002317
Fabien Sanglard830b8472016-11-30 16:35:58 -08002318void SurfaceFlinger::doDisplayComposition(
2319 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002320 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321{
Dan Stoza71433162014-02-04 16:22:36 -08002322 // We only need to actually compose the display if:
2323 // 1) It is being handled by hardware composer, which may need this to
2324 // keep its virtual display state machine in sync, or
2325 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002326 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002327 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002328 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002329 return;
2330 }
2331
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 ALOGV("doDisplayComposition");
2333
Mathias Agopian87baae12012-07-31 12:38:26 -07002334 Region dirtyRegion(inDirtyRegion);
2335
Mathias Agopianb8a55602009-06-26 19:06:36 -07002336 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002340 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002341 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2342 // takes a rectangle, we must make sure to update that whole
2343 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002344 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002345 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002346 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002347 // We need to redraw the rectangle that will be updated
2348 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002349 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002350 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002351 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002352 } else {
2353 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002354 dirtyRegion.set(displayDevice->bounds());
2355 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 }
2357 }
2358
Fabien Sanglard830b8472016-11-30 16:35:58 -08002359 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002361 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002362 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002363
2364 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002365 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366}
2367
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368bool SurfaceFlinger::doComposeSurfaces(
2369 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002370{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002372
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002374
2375 mat4 oldColorMatrix;
2376 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2377 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2378 if (applyColorMatrix) {
2379 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2380 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2381 }
2382
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2384 if (hasClientComposition) {
2385 ALOGV("hasClientComposition");
2386
2387 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002388 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002390 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2391 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2392 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2393 }
2394 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002395 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002396
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002397 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2399 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002400 // when using overlays, we assume a fully transparent framebuffer
2401 // NOTE: we could reduce how much we need to clear, for instance
2402 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002403 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002404 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002406 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002407 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002409
2410 // we remove the scissor part
2411 // we're left with the letterbox region
2412 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002414
2415 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002417
2418 // but limit it to the dirty region
2419 region.andSelf(dirty);
2420
Mathias Agopianb9494d52012-04-18 02:28:45 -07002421 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002422 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002423 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002424 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002425 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002426 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002427
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002429 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002430 // scissor on the main display. It should never be needed
2431 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 const Rect& bounds(displayDevice->getBounds());
2433 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002434 if (scissor != bounds) {
2435 // scissor doesn't match the screen's dimensions, so we
2436 // need to clear everything outside of it and enable
2437 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002438
Mathias Agopianf45c5102012-10-24 16:29:17 -07002439 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 const uint32_t height = displayDevice->getHeight();
2441 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002442 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002443 }
2444 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002445 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002446
Mathias Agopian85d751c2012-08-29 16:59:24 -07002447 /*
2448 * and then, render the layers targeted at the framebuffer
2449 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002450
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 ALOGV("Rendering client layers");
2452 const Transform& displayTransform = displayDevice->getTransform();
2453 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002454 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 bool firstLayer = true;
2456 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2457 const Region clip(dirty.intersect(
2458 displayTransform.transform(layer->visibleRegion)));
2459 ALOGV("Layer: %s", layer->getName().string());
2460 ALOGV(" Composition type: %s",
2461 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002462 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 switch (layer->getCompositionType(hwcId)) {
2464 case HWC2::Composition::Cursor:
2465 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002466 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002468 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2470 layer->isOpaque(state) && (state.alpha == 1.0f)
2471 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002472 // never clear the very first layer since we're
2473 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002474 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002475 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002476 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002477 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 case HWC2::Composition::Client: {
2479 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002480 break;
2481 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002483 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002484 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 } else {
2486 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002487 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002489 }
2490 } else {
2491 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002493 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002495 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002497 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002498 }
2499 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002500
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002501 if (applyColorMatrix) {
2502 getRenderEngine().setupColorTransform(oldColorMatrix);
2503 }
2504
Mathias Agopianf45c5102012-10-24 16:29:17 -07002505 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002506 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002507 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508}
2509
Fabien Sanglard830b8472016-11-30 16:35:58 -08002510void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2511 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002512 RenderEngine& engine(getRenderEngine());
2513 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514}
2515
Dan Stoza7d89d062015-04-30 13:29:25 -07002516status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002517 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002518 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519 const sp<Layer>& lbc,
2520 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002521{
Dan Stoza7d89d062015-04-30 13:29:25 -07002522 // add this layer to the current state list
2523 {
2524 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002526 return NO_MEMORY;
2527 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 if (parent == nullptr) {
2529 mCurrentState.layersSortedByZ.add(lbc);
2530 } else {
2531 parent->addChild(lbc);
2532 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002533 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002534 mLayersAdded = true;
2535 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002536 }
2537
Mathias Agopian96f08192010-06-02 23:28:45 -07002538 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002539 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002540
Dan Stoza7d89d062015-04-30 13:29:25 -07002541 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002542}
2543
Robert Carr9524cb32017-02-13 11:32:32 -08002544status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002545 Mutex::Autolock _l(mStateLock);
2546
Robert Carr1f0a16a2016-10-24 16:27:39 -07002547 const auto& p = layer->getParent();
2548 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2549 mCurrentState.layersSortedByZ.remove(layer);
2550
Robert Carr136e2f62017-02-08 17:54:29 -08002551 // As a matter of normal operation, the LayerCleaner will produce a second
2552 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2553 // so we will succeed in promoting it, but it's already been removed
2554 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2555 // otherwise something has gone wrong and we are leaking the layer.
2556 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2558 layer->getName().string(),
2559 (p != nullptr) ? p->getName().string() : "no-parent");
2560 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002561 } else if (index < 0) {
2562 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002563 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002564
2565 mLayersPendingRemoval.add(layer);
2566 mLayersRemoved = true;
2567 mNumLayers--;
2568 setTransactionFlags(eTransactionNeeded);
2569 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570}
2571
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002572uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002573 return android_atomic_release_load(&mTransactionFlags);
2574}
2575
Mathias Agopian3f844832013-08-07 21:24:32 -07002576uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2578}
2579
Mathias Agopian3f844832013-08-07 21:24:32 -07002580uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2582 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002583 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 }
2585 return old;
2586}
2587
Mathias Agopian8b33f032012-07-24 20:43:54 -07002588void SurfaceFlinger::setTransactionState(
2589 const Vector<ComposerState>& state,
2590 const Vector<DisplayState>& displays,
2591 uint32_t flags)
2592{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002593 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002594 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002595 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002596
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002597 if (flags & eAnimation) {
2598 // For window updates that are part of an animation we must wait for
2599 // previous animation "frames" to be handled.
2600 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002601 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002602 if (CC_UNLIKELY(err != NO_ERROR)) {
2603 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002604 // caller after a few seconds.
2605 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2606 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002607 mAnimTransactionPending = false;
2608 break;
2609 }
2610 }
2611 }
2612
Mathias Agopiane57f2922012-08-09 16:29:12 -07002613 size_t count = displays.size();
2614 for (size_t i=0 ; i<count ; i++) {
2615 const DisplayState& s(displays[i]);
2616 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002617 }
2618
Mathias Agopiane57f2922012-08-09 16:29:12 -07002619 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002620 for (size_t i=0 ; i<count ; i++) {
2621 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002622 // Here we need to check that the interface we're given is indeed
2623 // one of our own. A malicious client could give us a NULL
2624 // IInterface, or one of its own or even one of our own but a
2625 // different type. All these situations would cause us to crash.
2626 //
2627 // NOTE: it would be better to use RTTI as we could directly check
2628 // that we have a Client*. however, RTTI is disabled in Android.
2629 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002630 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002631 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002632 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002633 sp<Client> client( static_cast<Client *>(s.client.get()) );
2634 transactionFlags |= setClientStateLocked(client, s.state);
2635 }
2636 }
2637 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002638 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002639
Robert Carr2a7dbb42016-05-24 11:41:28 -07002640 // If a synchronous transaction is explicitly requested without any changes,
2641 // force a transaction anyway. This can be used as a flush mechanism for
2642 // previous async transactions.
2643 if (transactionFlags == 0 && (flags & eSynchronous)) {
2644 transactionFlags = eTransactionNeeded;
2645 }
2646
Mathias Agopian386aa982011-11-07 21:58:03 -08002647 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002648 if (mInterceptor.isEnabled()) {
2649 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2650 }
Irvel468051e2016-06-13 16:44:44 -07002651
Mathias Agopian386aa982011-11-07 21:58:03 -08002652 // this triggers the transaction
2653 setTransactionFlags(transactionFlags);
2654
2655 // if this is a synchronous transaction, wait for it to take effect
2656 // before returning.
2657 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002658 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002659 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002660 if (flags & eAnimation) {
2661 mAnimTransactionPending = true;
2662 }
2663 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002664 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2665 if (CC_UNLIKELY(err != NO_ERROR)) {
2666 // just in case something goes wrong in SF, return to the
2667 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002668 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2669 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002670 break;
2671 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 }
2674}
2675
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2677{
Jesse Hall9a143922012-10-04 16:29:19 -07002678 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2679 if (dpyIdx < 0)
2680 return 0;
2681
Mathias Agopiane57f2922012-08-09 16:29:12 -07002682 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002683 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002684 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002685 const uint32_t what = s.what;
2686 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002687 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002688 disp.surface = s.surface;
2689 flags |= eDisplayTransactionNeeded;
2690 }
2691 }
2692 if (what & DisplayState::eLayerStackChanged) {
2693 if (disp.layerStack != s.layerStack) {
2694 disp.layerStack = s.layerStack;
2695 flags |= eDisplayTransactionNeeded;
2696 }
2697 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002698 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002699 if (disp.orientation != s.orientation) {
2700 disp.orientation = s.orientation;
2701 flags |= eDisplayTransactionNeeded;
2702 }
2703 if (disp.frame != s.frame) {
2704 disp.frame = s.frame;
2705 flags |= eDisplayTransactionNeeded;
2706 }
2707 if (disp.viewport != s.viewport) {
2708 disp.viewport = s.viewport;
2709 flags |= eDisplayTransactionNeeded;
2710 }
2711 }
Michael Lentine47e45402014-07-18 15:34:25 -07002712 if (what & DisplayState::eDisplaySizeChanged) {
2713 if (disp.width != s.width) {
2714 disp.width = s.width;
2715 flags |= eDisplayTransactionNeeded;
2716 }
2717 if (disp.height != s.height) {
2718 disp.height = s.height;
2719 flags |= eDisplayTransactionNeeded;
2720 }
2721 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002722 }
2723 return flags;
2724}
2725
2726uint32_t SurfaceFlinger::setClientStateLocked(
2727 const sp<Client>& client,
2728 const layer_state_t& s)
2729{
2730 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002731 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002732 if (layer != 0) {
2733 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002734 bool geometryAppliesWithResize =
2735 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002736 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002737 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002739 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002740 }
2741 if (what & layer_state_t::eLayerChanged) {
2742 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 const auto& p = layer->getParent();
2744 if (p == nullptr) {
2745 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2746 if (layer->setLayer(s.z) && idx >= 0) {
2747 mCurrentState.layersSortedByZ.removeAt(idx);
2748 mCurrentState.layersSortedByZ.add(layer);
2749 // we need traversal (state changed)
2750 // AND transaction (list changed)
2751 flags |= eTransactionNeeded|eTraversalNeeded;
2752 }
2753 } else {
2754 if (p->setChildLayer(layer, s.z)) {
2755 flags |= eTransactionNeeded|eTraversalNeeded;
2756 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 }
2758 }
2759 if (what & layer_state_t::eSizeChanged) {
2760 if (layer->setSize(s.w, s.h)) {
2761 flags |= eTraversalNeeded;
2762 }
2763 }
2764 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002766 flags |= eTraversalNeeded;
2767 }
2768 if (what & layer_state_t::eMatrixChanged) {
2769 if (layer->setMatrix(s.matrix))
2770 flags |= eTraversalNeeded;
2771 }
2772 if (what & layer_state_t::eTransparentRegionChanged) {
2773 if (layer->setTransparentRegionHint(s.transparentRegion))
2774 flags |= eTraversalNeeded;
2775 }
Dan Stoza23116082015-06-18 14:58:39 -07002776 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002777 if (layer->setFlags(s.flags, s.mask))
2778 flags |= eTraversalNeeded;
2779 }
2780 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002781 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 flags |= eTraversalNeeded;
2783 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002784 if (what & layer_state_t::eFinalCropChanged) {
2785 if (layer->setFinalCrop(s.finalCrop))
2786 flags |= eTraversalNeeded;
2787 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002788 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002789 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 // We only allow setting layer stacks for top level layers,
2791 // everything else inherits layer stack from its parent.
2792 if (layer->hasParent()) {
2793 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2794 layer->getName().string());
2795 } else if (idx < 0) {
2796 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2797 "that also does not appear in the top level layer list. Something"
2798 " has gone wrong.", layer->getName().string());
2799 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002800 mCurrentState.layersSortedByZ.removeAt(idx);
2801 mCurrentState.layersSortedByZ.add(layer);
2802 // we need traversal (state changed)
2803 // AND transaction (list changed)
2804 flags |= eTransactionNeeded|eTraversalNeeded;
2805 }
2806 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002807 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002808 if (s.barrierHandle != nullptr) {
2809 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2810 } else if (s.barrierGbp != nullptr) {
2811 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2812 if (authenticateSurfaceTextureLocked(gbp)) {
2813 const auto& otherLayer =
2814 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2815 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2816 } else {
2817 ALOGE("Attempt to defer transaction to to an"
2818 " unrecognized GraphicBufferProducer");
2819 }
2820 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002821 // We don't trigger a traversal here because if no other state is
2822 // changed, we don't want this to cause any more work
2823 }
Robert Carr1db73f62016-12-21 12:58:51 -08002824 if (what & layer_state_t::eReparentChildren) {
2825 if (layer->reparentChildren(s.reparentHandle)) {
2826 flags |= eTransactionNeeded|eTraversalNeeded;
2827 }
2828 }
Robert Carr9524cb32017-02-13 11:32:32 -08002829 if (what & layer_state_t::eDetachChildren) {
2830 layer->detachChildren();
2831 }
Robert Carrc3574f72016-03-24 12:19:32 -07002832 if (what & layer_state_t::eOverrideScalingModeChanged) {
2833 layer->setOverrideScalingMode(s.overrideScalingMode);
2834 // We don't trigger a traversal here because if no other state is
2835 // changed, we don't want this to cause any more work
2836 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002837 }
2838 return flags;
2839}
2840
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002841status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002842 const String8& name,
2843 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002844 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002845 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2846 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002848 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002849 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002850 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002851 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002852 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002853
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002854 status_t result = NO_ERROR;
2855
2856 sp<Layer> layer;
2857
Mathias Agopian3165cc22012-08-08 19:42:09 -07002858 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2859 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002860 result = createNormalLayer(client,
2861 name, w, h, flags, format,
2862 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002864 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002865 result = createDimLayer(client,
2866 name, w, h, flags,
2867 handle, gbp, &layer);
2868 break;
2869 default:
2870 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 break;
2872 }
2873
Dan Stoza7d89d062015-04-30 13:29:25 -07002874 if (result != NO_ERROR) {
2875 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002877
Albert Chaulk479c60c2017-01-27 14:21:34 -05002878 layer->setInfo(windowType, ownerUid);
2879
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002881 if (result != NO_ERROR) {
2882 return result;
2883 }
Irvelffc9efc2016-07-27 15:16:37 -07002884 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002885
2886 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002887 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002890status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2891 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2892 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893{
2894 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002895 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 case PIXEL_FORMAT_TRANSPARENT:
2897 case PIXEL_FORMAT_TRANSLUCENT:
2898 format = PIXEL_FORMAT_RGBA_8888;
2899 break;
2900 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002901 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902 break;
2903 }
2904
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002905 *outLayer = new Layer(this, client, name, w, h, flags);
2906 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2907 if (err == NO_ERROR) {
2908 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002909 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002911
2912 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2913 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914}
2915
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002916status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2917 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2918 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002920 *outLayer = new LayerDim(this, client, name, w, h, flags);
2921 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002922 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002923 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002924}
2925
Mathias Agopianac9fa422013-02-11 16:40:36 -08002926status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927{
Robert Carr9524cb32017-02-13 11:32:32 -08002928 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002929 status_t err = NO_ERROR;
2930 sp<Layer> l(client->getLayerUser(handle));
2931 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002932 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002933 err = removeLayer(l);
2934 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2935 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002936 }
2937 return err;
2938}
2939
Mathias Agopian13127d82013-03-05 17:47:11 -08002940status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002941{
Mathias Agopian67106042013-03-14 19:18:13 -07002942 // called by ~LayerCleaner() when all references to the IBinder (handle)
2943 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002944 sp<Layer> l = layer.promote();
2945 if (l == nullptr) {
2946 // The layer has already been removed, carry on
2947 return NO_ERROR;
2948 } if (l->getParent() != nullptr) {
2949 // If we have a parent, then we can continue to live as long as it does.
2950 return NO_ERROR;
2951 }
2952 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953}
2954
Mathias Agopianb60314a2012-04-10 22:09:54 -07002955// ---------------------------------------------------------------------------
2956
Andy McFadden13a082e2012-08-24 10:16:42 -07002957void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002958 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002959 Vector<ComposerState> state;
2960 Vector<DisplayState> displays;
2961 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002962 d.what = DisplayState::eDisplayProjectionChanged |
2963 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002964 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002965 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002966 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002967 d.frame.makeInvalid();
2968 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002969 d.width = 0;
2970 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002971 displays.add(d);
2972 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002973 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002974
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2976 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002977 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002978
Brian Andersond0010582017-03-07 13:20:31 -08002979 // Use phase of 0 since phase is not known.
2980 // Use latency of 0, which will snap to the ideal latency.
2981 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002982}
2983
2984void SurfaceFlinger::initializeDisplays() {
2985 class MessageScreenInitialized : public MessageBase {
2986 SurfaceFlinger* flinger;
2987 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002988 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002989 virtual bool handler() {
2990 flinger->onInitializeDisplays();
2991 return true;
2992 }
2993 };
2994 sp<MessageBase> msg = new MessageScreenInitialized(this);
2995 postMessageAsync(msg); // we may be called from main thread, use async message
2996}
2997
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002998void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2999 int mode) {
3000 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3001 this);
3002 int32_t type = hw->getDisplayType();
3003 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003004
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003005 if (mode == currentMode) {
3006 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003007 return;
3008 }
3009
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003010 hw->setPowerMode(mode);
3011 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3012 ALOGW("Trying to set power mode for virtual display");
3013 return;
3014 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003015
Irvelffc9efc2016-07-27 15:16:37 -07003016 if (mInterceptor.isEnabled()) {
3017 Mutex::Autolock _l(mStateLock);
3018 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3019 if (idx < 0) {
3020 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3021 return;
3022 }
3023 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3024 }
3025
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003026 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003027 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003028 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003029 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3030 // FIXME: eventthread only knows about the main display right now
3031 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003032 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003035 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003036 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003037 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003038
3039 struct sched_param param = {0};
3040 param.sched_priority = 1;
3041 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3042 ALOGW("Couldn't set SCHED_FIFO on display on");
3043 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003045 // Turn off the display
3046 struct sched_param param = {0};
3047 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3048 ALOGW("Couldn't set SCHED_OTHER on display off");
3049 }
3050
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003051 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003052 disableHardwareVsync(true); // also cancels any in-progress resync
3053
Mathias Agopiancde87a32012-09-13 14:09:01 -07003054 // FIXME: eventthread only knows about the main display right now
3055 mEventThread->onScreenReleased();
3056 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003057
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003058 getHwComposer().setPowerMode(type, mode);
3059 mVisibleRegionsDirty = true;
3060 // from this point on, SF will stop drawing on this display
3061 } else {
3062 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003063 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003064}
3065
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003066void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3067 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003068 SurfaceFlinger& mFlinger;
3069 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003070 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003071 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003072 MessageSetPowerMode(SurfaceFlinger& flinger,
3073 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3074 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003075 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003076 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003077 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003078 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003079 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003080 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003081 ALOGW("Attempt to set power mode = %d for virtual display",
3082 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003083 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003084 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003085 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003086 return true;
3087 }
3088 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003089 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003090 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003091}
3092
3093// ---------------------------------------------------------------------------
3094
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3096{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003098
Mathias Agopianbd115332013-04-18 16:41:04 -07003099 IPCThreadState* ipc = IPCThreadState::self();
3100 const int pid = ipc->getCallingPid();
3101 const int uid = ipc->getCallingUid();
3102 if ((uid != AID_SHELL) &&
3103 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003104 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003105 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003107 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003108 // (this would indicate SF is stuck, but we want to be able to
3109 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003110 status_t err = mStateLock.timedLock(s2ns(1));
3111 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003112 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003113 result.appendFormat(
3114 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3115 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003116 }
3117
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003118 bool dumpAll = true;
3119 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003120 size_t numArgs = args.size();
3121 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003122 if ((index < numArgs) &&
3123 (args[index] == String16("--list"))) {
3124 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003125 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003126 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003127 }
3128
3129 if ((index < numArgs) &&
3130 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003131 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003132 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003133 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003134 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003135
3136 if ((index < numArgs) &&
3137 (args[index] == String16("--latency-clear"))) {
3138 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003139 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003140 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003141 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003142
3143 if ((index < numArgs) &&
3144 (args[index] == String16("--dispsync"))) {
3145 index++;
3146 mPrimaryDispSync.dump(result);
3147 dumpAll = false;
3148 }
Dan Stozab90cf072015-03-05 11:05:59 -08003149
3150 if ((index < numArgs) &&
3151 (args[index] == String16("--static-screen"))) {
3152 index++;
3153 dumpStaticScreenStats(result);
3154 dumpAll = false;
3155 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003156
3157 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003158 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003159 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003160 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003161 dumpAll = false;
3162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003164
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003165 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003166 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003167 }
3168
Mathias Agopian9795c422009-08-26 16:36:26 -07003169 if (locked) {
3170 mStateLock.unlock();
3171 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 }
3173 write(fd, result.string(), result.size());
3174 return NO_ERROR;
3175}
3176
Dan Stozac7014012014-02-14 15:03:43 -08003177void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3178 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003179{
Robert Carr2047fae2016-11-28 14:09:09 -08003180 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003181 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003182 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003183}
3184
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003185void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003187{
3188 String8 name;
3189 if (index < args.size()) {
3190 name = String8(args[index]);
3191 index++;
3192 }
3193
Dan Stoza9e56aa02015-11-02 13:00:03 -08003194 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3195 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003196 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003197
3198 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003199 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003200 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003201 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003202 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003203 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003204 }
Robert Carr2047fae2016-11-28 14:09:09 -08003205 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003206 }
3207}
3208
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003209void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003210 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003211{
3212 String8 name;
3213 if (index < args.size()) {
3214 name = String8(args[index]);
3215 index++;
3216 }
3217
Robert Carr2047fae2016-11-28 14:09:09 -08003218 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003219 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003220 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003221 }
Robert Carr2047fae2016-11-28 14:09:09 -08003222 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003223
Svetoslavd85084b2014-03-20 10:28:31 -07003224 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003225}
3226
Jamie Gennis6547ff42013-07-16 20:12:42 -07003227// This should only be called from the main thread. Otherwise it would need
3228// the lock and should use mCurrentState rather than mDrawingState.
3229void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003230 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003231 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003232 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003233
3234 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3235}
3236
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003237void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003238{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003239 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003240 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3241
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003242 if (isLayerTripleBufferingDisabled())
3243 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003244 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003245}
3246
Dan Stozab90cf072015-03-05 11:05:59 -08003247void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3248{
3249 result.appendFormat("Static screen stats:\n");
3250 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3251 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3252 float percent = 100.0f *
3253 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3254 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3255 b + 1, bucketTimeSec, percent);
3256 }
3257 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3258 float percent = 100.0f *
3259 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3260 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3261 NUM_BUCKETS - 1, bucketTimeSec, percent);
3262}
3263
Dan Stozae77c7662016-05-13 11:37:28 -07003264void SurfaceFlinger::recordBufferingStats(const char* layerName,
3265 std::vector<OccupancyTracker::Segment>&& history) {
3266 Mutex::Autolock lock(mBufferingStatsMutex);
3267 auto& stats = mBufferingStats[layerName];
3268 for (const auto& segment : history) {
3269 if (!segment.usedThirdBuffer) {
3270 stats.twoBufferTime += segment.totalTime;
3271 }
3272 if (segment.occupancyAverage < 1.0f) {
3273 stats.doubleBufferedTime += segment.totalTime;
3274 } else if (segment.occupancyAverage < 2.0f) {
3275 stats.tripleBufferedTime += segment.totalTime;
3276 }
3277 ++stats.numSegments;
3278 stats.totalTime += segment.totalTime;
3279 }
3280}
3281
Brian Andersond6927fb2016-07-23 23:37:30 -07003282void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3283 result.appendFormat("Layer frame timestamps:\n");
3284
3285 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3286 const size_t count = currentLayers.size();
3287 for (size_t i=0 ; i<count ; i++) {
3288 currentLayers[i]->dumpFrameEvents(result);
3289 }
3290}
3291
Dan Stozae77c7662016-05-13 11:37:28 -07003292void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3293 result.append("Buffering stats:\n");
3294 result.append(" [Layer name] <Active time> <Two buffer> "
3295 "<Double buffered> <Triple buffered>\n");
3296 Mutex::Autolock lock(mBufferingStatsMutex);
3297 typedef std::tuple<std::string, float, float, float> BufferTuple;
3298 std::map<float, BufferTuple, std::greater<float>> sorted;
3299 for (const auto& statsPair : mBufferingStats) {
3300 const char* name = statsPair.first.c_str();
3301 const BufferingStats& stats = statsPair.second;
3302 if (stats.numSegments == 0) {
3303 continue;
3304 }
3305 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3306 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3307 stats.totalTime;
3308 float doubleBufferRatio = static_cast<float>(
3309 stats.doubleBufferedTime) / stats.totalTime;
3310 float tripleBufferRatio = static_cast<float>(
3311 stats.tripleBufferedTime) / stats.totalTime;
3312 sorted.insert({activeTime, {name, twoBufferRatio,
3313 doubleBufferRatio, tripleBufferRatio}});
3314 }
3315 for (const auto& sortedPair : sorted) {
3316 float activeTime = sortedPair.first;
3317 const BufferTuple& values = sortedPair.second;
3318 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3319 std::get<0>(values).c_str(), activeTime,
3320 std::get<1>(values), std::get<2>(values),
3321 std::get<3>(values));
3322 }
3323 result.append("\n");
3324}
3325
3326
Mathias Agopian74d211a2013-04-22 16:55:35 +02003327void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3328 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003329{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003330 bool colorize = false;
3331 if (index < args.size()
3332 && (args[index] == String16("--color"))) {
3333 colorize = true;
3334 index++;
3335 }
3336
3337 Colorizer colorizer(colorize);
3338
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003339 // figure out if we're stuck somewhere
3340 const nsecs_t now = systemTime();
3341 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3342 const nsecs_t inTransaction(mDebugInTransaction);
3343 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3344 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3345
3346 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003347 * Dump library configuration.
3348 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003349
3350 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003351 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003352 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003353 appendSfConfigString(result);
3354 appendUiConfigString(result);
3355 appendGuiConfigString(result);
3356 result.append("\n");
3357
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003358 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003359 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003361 result.append(SyncFeatures::getInstance().toString());
3362 result.append("\n");
3363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3365
Andy McFadden41d67d72014-04-25 16:58:34 -07003366 colorizer.bold(result);
3367 result.append("DispSync configuration: ");
3368 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003369 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3370 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003371 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3372 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003373 result.append("\n");
3374
Dan Stozab90cf072015-03-05 11:05:59 -08003375 // Dump static screen stats
3376 result.append("\n");
3377 dumpStaticScreenStats(result);
3378 result.append("\n");
3379
Dan Stozae77c7662016-05-13 11:37:28 -07003380 dumpBufferingStats(result);
3381
Andy McFadden4803b742012-09-24 19:07:20 -07003382 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003383 * Dump the visible layer list
3384 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003386 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003387 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003388 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003389 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003390 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003391
3392 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003393 * Dump Display state
3394 */
3395
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003396 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003397 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003398 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003399 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3400 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003402 }
3403
3404 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405 * Dump SurfaceFlinger global state
3406 */
3407
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003408 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003409 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003410 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411
Mathias Agopian888c8222012-08-04 21:10:38 -07003412 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003413 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003414
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003415 colorizer.bold(result);
3416 result.appendFormat("EGL implementation : %s\n",
3417 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3418 colorizer.reset(result);
3419 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003420 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003421
Mathias Agopian875d8e12013-06-07 15:35:48 -07003422 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423
Mathias Agopian42977342012-08-05 00:40:46 -07003424 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003425 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3426 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003427 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428 " last eglSwapBuffers() time: %f us\n"
3429 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003430 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431 " refresh-rate : %f fps\n"
3432 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003433 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003434 " gpu_to_cpu_unsupported : %d\n"
3435 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436 mLastSwapBufferTime/1000.0,
3437 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003438 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003439 1e9 / activeConfig->getVsyncPeriod(),
3440 activeConfig->getDpiX(),
3441 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003442 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443
Mathias Agopian74d211a2013-04-22 16:55:35 +02003444 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003445 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003446
Mathias Agopian74d211a2013-04-22 16:55:35 +02003447 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003449
3450 /*
3451 * VSYNC state
3452 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003454 result.append("\n");
3455
3456 /*
3457 * HWC layer minidump
3458 */
3459 for (size_t d = 0; d < mDisplays.size(); d++) {
3460 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3461 int32_t hwcId = displayDevice->getHwcDisplayId();
3462 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3463 continue;
3464 }
3465
3466 result.appendFormat("Display %d HWC layers:\n", hwcId);
3467 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003468 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003469 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003470 });
Dan Stozae22aec72016-08-01 13:20:59 -07003471 result.append("\n");
3472 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003473
3474 /*
3475 * Dump HWComposer state
3476 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003477 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003478 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003479 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003480 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003481 result.appendFormat(" h/w composer %s\n",
3482 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003483 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003484
3485 /*
3486 * Dump gralloc state
3487 */
3488 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3489 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003490}
3491
Mathias Agopian13127d82013-03-05 17:47:11 -08003492const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003493SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003494 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003495 wp<IBinder> dpy;
3496 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3497 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3498 dpy = mDisplays.keyAt(i);
3499 break;
3500 }
3501 }
3502 if (dpy == NULL) {
3503 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3504 // Just use the primary display so we have something to return
3505 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3506 }
3507 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003508}
3509
Keun young Park63f165f2012-08-31 10:53:36 -07003510bool SurfaceFlinger::startDdmConnection()
3511{
3512 void* libddmconnection_dso =
3513 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3514 if (!libddmconnection_dso) {
3515 return false;
3516 }
3517 void (*DdmConnection_start)(const char* name);
3518 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003519 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003520 if (!DdmConnection_start) {
3521 dlclose(libddmconnection_dso);
3522 return false;
3523 }
3524 (*DdmConnection_start)(getServiceName());
3525 return true;
3526}
3527
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003528status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 switch (code) {
3530 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003531 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003533 case CLEAR_ANIMATION_FRAME_STATS:
3534 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003536 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 {
3538 // codes that require permission check
3539 IPCThreadState* ipc = IPCThreadState::self();
3540 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003541 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003542 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003543 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003544 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003545 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003547 break;
3548 }
Robert Carr1db73f62016-12-21 12:58:51 -08003549 /*
3550 * Calling setTransactionState is safe, because you need to have been
3551 * granted a reference to Client* and Handle* to do anything with it.
3552 *
3553 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3554 */
3555 case SET_TRANSACTION_STATE:
3556 case CREATE_SCOPED_CONNECTION:
3557 {
3558 return OK;
3559 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003560 case CAPTURE_SCREEN:
3561 {
3562 // codes that require permission check
3563 IPCThreadState* ipc = IPCThreadState::self();
3564 const int pid = ipc->getCallingPid();
3565 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003566 if ((uid != AID_GRAPHICS) &&
3567 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003568 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003569 return PERMISSION_DENIED;
3570 }
3571 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003574 return OK;
3575}
3576
3577status_t SurfaceFlinger::onTransact(
3578 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3579{
3580 status_t credentialCheck = CheckTransactCodeCredentials(code);
3581 if (credentialCheck != OK) {
3582 return credentialCheck;
3583 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3586 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003587 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003588 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003589 IPCThreadState* ipc = IPCThreadState::self();
3590 const int pid = ipc->getCallingPid();
3591 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003592 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003593 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 return PERMISSION_DENIED;
3595 }
3596 int n;
3597 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003598 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003599 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 return NO_ERROR;
3601 case 1002: // SHOW_UPDATES
3602 n = data.readInt32();
3603 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003604 invalidateHwcGeometry();
3605 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003608 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003611 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003612 setTransactionFlags(
3613 eTransactionNeeded|
3614 eDisplayTransactionNeeded|
3615 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003616 return NO_ERROR;
3617 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003618 case 1006:{ // send empty update
3619 signalRefresh();
3620 return NO_ERROR;
3621 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003622 case 1008: // toggle use of hw composer
3623 n = data.readInt32();
3624 mDebugDisableHWC = n ? 1 : 0;
3625 invalidateHwcGeometry();
3626 repaintEverything();
3627 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003628 case 1009: // toggle use of transform hint
3629 n = data.readInt32();
3630 mDebugDisableTransformHint = n ? 1 : 0;
3631 invalidateHwcGeometry();
3632 repaintEverything();
3633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003635 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 reply->writeInt32(0);
3637 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003638 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003639 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640 return NO_ERROR;
3641 case 1013: {
3642 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003643 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3644 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003645 return NO_ERROR;
3646 }
3647 case 1014: {
3648 // daltonize
3649 n = data.readInt32();
3650 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003651 case 1:
3652 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3653 break;
3654 case 2:
3655 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3656 break;
3657 case 3:
3658 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3659 break;
3660 default:
3661 mDaltonizer.setType(ColorBlindnessType::None);
3662 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003663 }
3664 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003665 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003666 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003667 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003668 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003669 invalidateHwcGeometry();
3670 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003671 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003673 case 1015: {
3674 // apply a color matrix
3675 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003676 if (n) {
3677 // color matrix is sent as mat3 matrix followed by vec3
3678 // offset, then packed into a mat4 where the last row is
3679 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003680 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003681 for (size_t j = 0; j < 4; j++) {
3682 mColorMatrix[i][j] = data.readFloat();
3683 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003684 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003685 } else {
3686 mColorMatrix = mat4();
3687 }
3688 invalidateHwcGeometry();
3689 repaintEverything();
3690 return NO_ERROR;
3691 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003692 // This is an experimental interface
3693 // Needs to be shifted to proper binder interface when we productize
3694 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003695 n = data.readInt32();
3696 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003697 return NO_ERROR;
3698 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003699 case 1017: {
3700 n = data.readInt32();
3701 mForceFullDamage = static_cast<bool>(n);
3702 return NO_ERROR;
3703 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003704 case 1018: { // Modify Choreographer's phase offset
3705 n = data.readInt32();
3706 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3707 return NO_ERROR;
3708 }
3709 case 1019: { // Modify SurfaceFlinger's phase offset
3710 n = data.readInt32();
3711 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3712 return NO_ERROR;
3713 }
Irvel468051e2016-06-13 16:44:44 -07003714 case 1020: { // Layer updates interceptor
3715 n = data.readInt32();
3716 if (n) {
3717 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003718 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003719 }
3720 else{
3721 ALOGV("Interceptor disabled");
3722 mInterceptor.disable();
3723 }
3724 return NO_ERROR;
3725 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003726 case 1021: { // Disable HWC virtual displays
3727 n = data.readInt32();
3728 mUseHwcVirtualDisplays = !n;
3729 return NO_ERROR;
3730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 }
3732 }
3733 return err;
3734}
3735
Mathias Agopian53331da2011-08-22 21:44:41 -07003736void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003737 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003738 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003739}
3740
Mathias Agopian59119e62010-10-11 12:37:43 -07003741// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003742// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003743// ---------------------------------------------------------------------------
3744
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003745/* The code below is here to handle b/8734824
3746 *
3747 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003748 * from the surfaceflinger thread to the calling binder thread, where they
3749 * are executed. This allows the calling thread in the calling process to be
3750 * reused and not depend on having "enough" binder threads to handle the
3751 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003752 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003754 /* Parts of GraphicProducerWrapper are run on two different threads,
3755 * communicating by sending messages via Looper but also by shared member
3756 * data. Coherence maintenance is subtle and in places implicit (ugh).
3757 *
3758 * Don't rely on Looper's sendMessage/handleMessage providing
3759 * release/acquire semantics for any data not actually in the Message.
3760 * Data going from surfaceflinger to binder threads needs to be
3761 * synchronized explicitly.
3762 *
3763 * Barrier open/wait do provide release/acquire semantics. This provides
3764 * implicit synchronization for data coming back from binder to
3765 * surfaceflinger threads.
3766 */
3767
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003768 sp<IGraphicBufferProducer> impl;
3769 sp<Looper> looper;
3770 status_t result;
3771 bool exitPending;
3772 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003773 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003774 uint32_t code;
3775 Parcel const* data;
3776 Parcel* reply;
3777
3778 enum {
3779 MSG_API_CALL,
3780 MSG_EXIT
3781 };
3782
3783 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003784 * Called on surfaceflinger thread. This is called by our "fake"
3785 * BpGraphicBufferProducer. We package the data and reply Parcel and
3786 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 */
3788 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003789 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003790 this->code = code;
3791 this->data = &data;
3792 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003794 // if we've exited, we run the message synchronously right here.
3795 // note (JH): as far as I can tell from looking at the code, this
3796 // never actually happens. if it does, i'm not sure if it happens
3797 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 handleMessage(Message(MSG_API_CALL));
3799 } else {
3800 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003801 // Prevent stores to this->{code, data, reply} from being
3802 // reordered later than the construction of Message.
3803 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003804 looper->sendMessage(this, Message(MSG_API_CALL));
3805 barrier.wait();
3806 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003807 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003808 }
3809
3810 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003811 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 * call the real BpGraphicBufferProducer.
3813 */
3814 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003815 int what = message.what;
3816 // Prevent reads below from happening before the read from Message
3817 atomic_thread_fence(memory_order_acquire);
3818 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003819 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003821 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 exitRequested = true;
3823 }
3824 }
3825
3826public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003827 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003828 : impl(impl),
3829 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003830 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003831 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003832 exitRequested(false),
3833 code(0),
3834 data(NULL),
3835 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003836 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003837
Jesse Hallb154c422014-07-13 12:47:02 -07003838 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003839 status_t waitForResponse() {
3840 do {
3841 looper->pollOnce(-1);
3842 } while (!exitRequested);
3843 return result;
3844 }
3845
Jesse Hallb154c422014-07-13 12:47:02 -07003846 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003847 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003848 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003850 // Ensure this->result is visible to the binder thread before it
3851 // handles the message.
3852 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003853 looper->sendMessage(this, Message(MSG_EXIT));
3854 }
3855};
3856
3857
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003858status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3859 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003860 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003861 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003862 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003863
3864 if (CC_UNLIKELY(display == 0))
3865 return BAD_VALUE;
3866
3867 if (CC_UNLIKELY(producer == 0))
3868 return BAD_VALUE;
3869
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003870 // if we have secure windows on this display, never allow the screen capture
3871 // unless the producer interface is local (i.e.: we can take a screenshot for
3872 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003873 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003874
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003875 // Convert to surfaceflinger's internal rotation type.
3876 Transform::orientation_flags rotationFlags;
3877 switch (rotation) {
3878 case ISurfaceComposer::eRotateNone:
3879 rotationFlags = Transform::ROT_0;
3880 break;
3881 case ISurfaceComposer::eRotate90:
3882 rotationFlags = Transform::ROT_90;
3883 break;
3884 case ISurfaceComposer::eRotate180:
3885 rotationFlags = Transform::ROT_180;
3886 break;
3887 case ISurfaceComposer::eRotate270:
3888 rotationFlags = Transform::ROT_270;
3889 break;
3890 default:
3891 rotationFlags = Transform::ROT_0;
3892 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3893 break;
3894 }
3895
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003896 class MessageCaptureScreen : public MessageBase {
3897 SurfaceFlinger* flinger;
3898 sp<IBinder> display;
3899 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003900 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 uint32_t reqWidth, reqHeight;
3902 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003903 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003904 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003905 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003906 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 public:
3908 MessageCaptureScreen(SurfaceFlinger* flinger,
3909 const sp<IBinder>& display,
3910 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003911 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003912 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003913 bool useIdentityTransform,
3914 Transform::orientation_flags rotation,
3915 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003916 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003917 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003918 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003919 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003920 rotation(rotation), result(PERMISSION_DENIED),
3921 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003922 {
3923 }
3924 status_t getResult() const {
3925 return result;
3926 }
3927 virtual bool handler() {
3928 Mutex::Autolock _l(flinger->mStateLock);
3929 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003930 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003931 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003932 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003933 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003934 return true;
3935 }
3936 };
3937
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938 // this creates a "fake" BBinder which will serve as a "fake" remote
3939 // binder to receive the marshaled calls and forward them to the
3940 // real remote (a BpGraphicBufferProducer)
3941 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3942
3943 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3944 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003945 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003947 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003948 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003949
3950 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003951 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003952 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003953 }
3954 return res;
3955}
3956
Mathias Agopian180f10d2013-04-10 22:55:41 -07003957
3958void SurfaceFlinger::renderScreenImplLocked(
3959 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003960 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003961 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003962 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003963{
3964 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003965 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003966
3967 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003968 const int32_t hw_w = hw->getWidth();
3969 const int32_t hw_h = hw->getHeight();
3970 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003971 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003972
Dan Stozac1879002014-05-22 15:59:05 -07003973 // if a default or invalid sourceCrop is passed in, set reasonable values
3974 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3975 !sourceCrop.isValid()) {
3976 sourceCrop.setLeftTop(Point(0, 0));
3977 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3978 }
3979
3980 // ensure that sourceCrop is inside screen
3981 if (sourceCrop.left < 0) {
3982 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3983 }
Dan Stozabe31f442014-06-11 11:20:54 -07003984 if (sourceCrop.right > hw_w) {
3985 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003986 }
3987 if (sourceCrop.top < 0) {
3988 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3989 }
Dan Stozabe31f442014-06-11 11:20:54 -07003990 if (sourceCrop.bottom > hw_h) {
3991 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003992 }
3993
Mathias Agopian180f10d2013-04-10 22:55:41 -07003994 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003995 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003996
3997 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003998 engine.setViewportAndProjection(
3999 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004000 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001
4002 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004003 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004004
Robert Carr1f0a16a2016-10-24 16:27:39 -07004005 // We loop through the first level of layers without traversing,
4006 // as we need to interpret min/max layer Z in the top level Z space.
4007 for (const auto& layer : mDrawingState.layersSortedByZ) {
4008 if (layer->getLayerStack() != hw->getLayerStack()) {
4009 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004011 const Layer::State& state(layer->getDrawingState());
4012 if (state.z < minLayerZ || state.z > maxLayerZ) {
4013 continue;
4014 }
4015 layer->traverseInZOrder([&](Layer* layer) {
4016 if (!layer->isVisible()) {
4017 return;
4018 }
4019 if (filtering) layer->setFiltering(true);
4020 layer->draw(hw, useIdentityTransform);
4021 if (filtering) layer->setFiltering(false);
4022 });
4023 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004024
Mathias Agopian931bda12013-08-28 18:11:46 -07004025 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004026}
4027
4028
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004029status_t SurfaceFlinger::captureScreenImplLocked(
4030 const sp<const DisplayDevice>& hw,
4031 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004032 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004033 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004034 bool useIdentityTransform, Transform::orientation_flags rotation,
4035 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004036{
4037 ATRACE_CALL();
4038
Mathias Agopian180f10d2013-04-10 22:55:41 -07004039 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004040 uint32_t hw_w = hw->getWidth();
4041 uint32_t hw_h = hw->getHeight();
4042
4043 if (rotation & Transform::ROT_90) {
4044 std::swap(hw_w, hw_h);
4045 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004046
Mathias Agopian180f10d2013-04-10 22:55:41 -07004047 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4048 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4049 reqWidth, reqHeight, hw_w, hw_h);
4050 return BAD_VALUE;
4051 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004052
Mathias Agopian180f10d2013-04-10 22:55:41 -07004053 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4054 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4055
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004056 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004057 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004058 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4060 (state.z < minLayerZ || state.z > maxLayerZ)) {
4061 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004062 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004063 layer->traverseInZOrder([&](Layer *layer) {
4064 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4065 layer->isSecure());
4066 });
4067 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004068
4069 if (!isLocalScreenshot && secureLayerIsVisible) {
4070 ALOGW("FB is protected: PERMISSION_DENIED");
4071 return PERMISSION_DENIED;
4072 }
4073
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 // create a surface (because we're a producer, and we need to
4075 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004076 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004077
4078 // Put the screenshot Surface into async mode so that
4079 // Layer::headFenceHasSignaled will always return true and we'll latch the
4080 // first buffer regardless of whether or not its acquire fence has
4081 // signaled. This is needed to avoid a race condition in the rotation
4082 // animation. See b/30209608
4083 sur->setAsyncMode(true);
4084
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004085 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004086
Michael Lentine5a16a622015-05-21 13:48:24 -07004087 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4088 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004089 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4090 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004091
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004092 int err = 0;
4093 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004094 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004095 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4096 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004097
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004098 if (err == NO_ERROR) {
4099 ANativeWindowBuffer* buffer;
4100 /* TODO: Once we have the sync framework everywhere this can use
4101 * server-side waits on the fence that dequeueBuffer returns.
4102 */
4103 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4104 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004105 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004106 // create an EGLImage from the buffer so we can later
4107 // turn it into a texture
4108 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4109 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4110 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004111 // this binds the given EGLImage as a framebuffer for the
4112 // duration of this scope.
4113 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4114 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004115 // this will in fact render into our dequeued buffer
4116 // via an FBO, which means we didn't have to create
4117 // an EGLSurface and therefore we're not
4118 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004119 renderScreenImplLocked(
4120 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4121 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004122
Riley Andrews86639902014-08-15 12:27:24 -07004123 // Attempt to create a sync khr object that can produce a sync point. If that
4124 // isn't available, create a non-dupable sync object in the fallback path and
4125 // wait on it directly.
4126 EGLSyncKHR sync;
4127 if (!DEBUG_SCREENSHOTS) {
4128 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004129 // native fence fd will not be populated until flush() is done.
4130 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004131 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004132 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004133 }
Riley Andrews86639902014-08-15 12:27:24 -07004134 if (sync != EGL_NO_SYNC_KHR) {
4135 // get the sync fd
4136 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4137 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4138 ALOGW("captureScreen: failed to dup sync khr object");
4139 syncFd = -1;
4140 }
4141 eglDestroySyncKHR(mEGLDisplay, sync);
4142 } else {
4143 // fallback path
4144 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4145 if (sync != EGL_NO_SYNC_KHR) {
4146 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4147 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4148 EGLint eglErr = eglGetError();
4149 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4150 ALOGW("captureScreen: fence wait timed out");
4151 } else {
4152 ALOGW_IF(eglErr != EGL_SUCCESS,
4153 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4154 }
4155 eglDestroySyncKHR(mEGLDisplay, sync);
4156 } else {
4157 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4158 }
4159 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004160 if (DEBUG_SCREENSHOTS) {
4161 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4162 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4163 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4164 hw, minLayerZ, maxLayerZ);
4165 delete [] pixels;
4166 }
4167
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004168 } else {
4169 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4170 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004171 window->cancelBuffer(window, buffer, syncFd);
4172 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004173 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004174 // destroy our image
4175 eglDestroyImageKHR(mEGLDisplay, image);
4176 } else {
4177 result = BAD_VALUE;
4178 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004179 if (buffer) {
4180 // queueBuffer takes ownership of syncFd
4181 result = window->queueBuffer(window, buffer, syncFd);
4182 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004183 }
4184 } else {
4185 result = BAD_VALUE;
4186 }
4187 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4188 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004189
Mathias Agopian74c40c02010-09-29 13:02:36 -07004190 return result;
4191}
4192
Mathias Agopiand5556842013-09-19 17:08:37 -07004193void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004194 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004196 for (size_t y=0 ; y<h ; y++) {
4197 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4198 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004199 if (p[x] != 0xFF000000) return;
4200 }
4201 }
4202 ALOGE("*** we just took a black screenshot ***\n"
4203 "requested minz=%d, maxz=%d, layerStack=%d",
4204 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205
Robert Carr2047fae2016-11-28 14:09:09 -08004206 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004207 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004208 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004209 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4210 state.z <= maxLayerZ) {
4211 layer->traverseInZOrder([&](Layer* layer) {
4212 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4213 layer->isVisible() ? '+' : '-',
4214 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004215 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004216 i++;
4217 });
4218 }
4219 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004220 }
4221}
4222
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004223// ---------------------------------------------------------------------------
4224
Robert Carr2047fae2016-11-28 14:09:09 -08004225void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4226 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004227}
4228
Robert Carr2047fae2016-11-28 14:09:09 -08004229void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4230 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004231}
4232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004234
4235
4236#if defined(__gl_h_)
4237#error "don't include gl/gl.h in this file"
4238#endif
4239
4240#if defined(__gl2_h_)
4241#error "don't include gl2/gl2.h in this file"
4242#endif