blob: 0f0a017f4f7161c6d1eefc2f7f99d41cb2cd2637 [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
Dan Stoza7f7da322014-05-02 15:26:25 -0700630status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
631 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700632 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700633 return BAD_VALUE;
634 }
635
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500636 if (!display.get())
637 return NAME_NOT_FOUND;
638
Jesse Hall692c7232012-11-08 15:41:56 -0800639 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700640 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800641 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700642 type = i;
643 break;
644 }
645 }
646
647 if (type < 0) {
648 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700649 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700650
Mathias Agopian8b736f12012-08-13 17:54:26 -0700651 // TODO: Not sure if display density should handled by SF any longer
652 class Density {
653 static int getDensityFromProperty(char const* propName) {
654 char property[PROPERTY_VALUE_MAX];
655 int density = 0;
656 if (property_get(propName, property, NULL) > 0) {
657 density = atoi(property);
658 }
659 return density;
660 }
661 public:
662 static int getEmuDensity() {
663 return getDensityFromProperty("qemu.sf.lcd_density"); }
664 static int getBuildDensity() {
665 return getDensityFromProperty("ro.sf.lcd_density"); }
666 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700667
Dan Stoza7f7da322014-05-02 15:26:25 -0700668 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700669
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700671 DisplayInfo info = DisplayInfo();
672
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 float xdpi = hwConfig->getDpiX();
674 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700675
676 if (type == DisplayDevice::DISPLAY_PRIMARY) {
677 // The density of the device is provided by a build property
678 float density = Density::getBuildDensity() / 160.0f;
679 if (density == 0) {
680 // the build doesn't provide a density -- this is wrong!
681 // use xdpi instead
682 ALOGE("ro.sf.lcd_density must be defined as a build property");
683 density = xdpi / 160.0f;
684 }
685 if (Density::getEmuDensity()) {
686 // if "qemu.sf.lcd_density" is specified, it overrides everything
687 xdpi = ydpi = density = Density::getEmuDensity();
688 density /= 160.0f;
689 }
690 info.density = density;
691
692 // TODO: this needs to go away (currently needed only by webkit)
693 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
694 info.orientation = hw->getOrientation();
695 } else {
696 // TODO: where should this value come from?
697 static const int TV_DENSITY = 213;
698 info.density = TV_DENSITY / 160.0f;
699 info.orientation = 0;
700 }
701
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 info.w = hwConfig->getWidth();
703 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700704 info.xdpi = xdpi;
705 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900707 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708
Andy McFadden91b2ca82014-06-13 14:04:23 -0700709 // This is how far in advance a buffer must be queued for
710 // presentation at a given time. If you want a buffer to appear
711 // on the screen at time N, you must submit the buffer before
712 // (N - presentationDeadline).
713 //
714 // Normally it's one full refresh period (to give SF a chance to
715 // latch the buffer), but this can be reduced by configuring a
716 // DispSync offset. Any additional delays introduced by the hardware
717 // composer or panel must be accounted for here.
718 //
719 // We add an additional 1ms to allow for processing time and
720 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800722 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700723
724 // All non-virtual displays are currently considered secure.
725 info.secure = true;
726
Michael Wright28f24d02016-07-12 13:30:53 -0700727 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700728 }
729
Dan Stoza7f7da322014-05-02 15:26:25 -0700730 return NO_ERROR;
731}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700732
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800733status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700734 DisplayStatInfo* stats) {
735 if (stats == NULL) {
736 return BAD_VALUE;
737 }
738
739 // FIXME for now we always return stats for the primary display
740 memset(stats, 0, sizeof(*stats));
741 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
742 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
743 return NO_ERROR;
744}
745
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700746int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800747 if (display == NULL) {
748 ALOGE("%s : display is NULL", __func__);
749 return BAD_VALUE;
750 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700751 sp<DisplayDevice> device(getDisplayDevice(display));
752 if (device != NULL) {
753 return device->getActiveConfig();
754 }
755 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700756}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700757
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700758void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
759 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
760 this);
761 int32_t type = hw->getDisplayType();
762 int currentMode = hw->getActiveConfig();
763
764 if (mode == currentMode) {
765 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
766 return;
767 }
768
769 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
770 ALOGW("Trying to set config for virtual display");
771 return;
772 }
773
774 hw->setActiveConfig(mode);
775 getHwComposer().setActiveConfig(type, mode);
776}
777
778status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
779 class MessageSetActiveConfig: public MessageBase {
780 SurfaceFlinger& mFlinger;
781 sp<IBinder> mDisplay;
782 int mMode;
783 public:
784 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
785 int mode) :
786 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
787 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700788 Vector<DisplayInfo> configs;
789 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700790 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700791 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700792 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700793 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700794 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700795 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
796 if (hw == NULL) {
797 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700798 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700799 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
800 ALOGW("Attempt to set active config = %d for virtual display",
801 mMode);
802 } else {
803 mFlinger.setActiveConfigInternal(hw, mMode);
804 }
805 return true;
806 }
807 };
808 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
809 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700810 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700811}
Michael Wright28f24d02016-07-12 13:30:53 -0700812status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
813 Vector<android_color_mode_t>* outColorModes) {
814 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
815 return BAD_VALUE;
816 }
817
818 if (!display.get()) {
819 return NAME_NOT_FOUND;
820 }
821
822 int32_t type = NAME_NOT_FOUND;
823 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
824 if (display == mBuiltinDisplays[i]) {
825 type = i;
826 break;
827 }
828 }
829
830 if (type < 0) {
831 return type;
832 }
833
834 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
835 outColorModes->clear();
836 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
837
838 return NO_ERROR;
839}
840
841android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
842 sp<DisplayDevice> device(getDisplayDevice(display));
843 if (device != nullptr) {
844 return device->getActiveColorMode();
845 }
846 return static_cast<android_color_mode_t>(BAD_VALUE);
847}
848
849void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
850 android_color_mode_t mode) {
851 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
852 this);
853 int32_t type = hw->getDisplayType();
854 android_color_mode_t currentMode = hw->getActiveColorMode();
855
856 if (mode == currentMode) {
857 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
858 return;
859 }
860
861 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
862 ALOGW("Trying to set config for virtual display");
863 return;
864 }
865
866 hw->setActiveColorMode(mode);
867 getHwComposer().setActiveColorMode(type, mode);
868}
869
870
871status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
872 android_color_mode_t colorMode) {
873 class MessageSetActiveColorMode: public MessageBase {
874 SurfaceFlinger& mFlinger;
875 sp<IBinder> mDisplay;
876 android_color_mode_t mMode;
877 public:
878 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
879 android_color_mode_t mode) :
880 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
881 virtual bool handler() {
882 Vector<android_color_mode_t> modes;
883 mFlinger.getDisplayColorModes(mDisplay, &modes);
884 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
885 if (mMode < 0 || !exists) {
886 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
887 mDisplay.get());
888 return true;
889 }
890 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
891 if (hw == nullptr) {
892 ALOGE("Attempt to set active color mode = %d for null display %p",
893 mMode, mDisplay.get());
894 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
895 ALOGW("Attempt to set active color mode= %d for virtual display",
896 mMode);
897 } else {
898 mFlinger.setActiveColorModeInternal(hw, mMode);
899 }
900 return true;
901 }
902 };
903 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
904 postMessageSync(msg);
905 return NO_ERROR;
906}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700907
Svetoslavd85084b2014-03-20 10:28:31 -0700908status_t SurfaceFlinger::clearAnimationFrameStats() {
909 Mutex::Autolock _l(mStateLock);
910 mAnimFrameTracker.clearStats();
911 return NO_ERROR;
912}
913
914status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
915 Mutex::Autolock _l(mStateLock);
916 mAnimFrameTracker.getStats(outStats);
917 return NO_ERROR;
918}
919
Dan Stozac4f471e2016-03-24 09:31:08 -0700920status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
921 HdrCapabilities* outCapabilities) const {
922 Mutex::Autolock _l(mStateLock);
923
924 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
925 if (displayDevice == nullptr) {
926 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
927 return BAD_VALUE;
928 }
929
930 std::unique_ptr<HdrCapabilities> capabilities =
931 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
932 if (capabilities) {
933 std::swap(*outCapabilities, *capabilities);
934 } else {
935 return BAD_VALUE;
936 }
937
938 return NO_ERROR;
939}
940
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700941status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
942 if (enable == mInjectVSyncs) {
943 return NO_ERROR;
944 }
945
946 if (enable) {
947 mInjectVSyncs = enable;
948 ALOGV("VSync Injections enabled");
949 if (mVSyncInjector.get() == nullptr) {
950 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700951 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700952 }
953 mEventQueue.setEventThread(mInjectorEventThread);
954 } else {
955 mInjectVSyncs = enable;
956 ALOGV("VSync Injections disabled");
957 mEventQueue.setEventThread(mSFEventThread);
958 mVSyncInjector.clear();
959 }
960 return NO_ERROR;
961}
962
963status_t SurfaceFlinger::injectVSync(nsecs_t when) {
964 if (!mInjectVSyncs) {
965 ALOGE("VSync Injections not enabled");
966 return BAD_VALUE;
967 }
968 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
969 ALOGV("Injecting VSync inside SurfaceFlinger");
970 mVSyncInjector->onInjectSyncEvent(when);
971 }
972 return NO_ERROR;
973}
974
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800975// ----------------------------------------------------------------------------
976
977sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800978 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700979}
980
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800981// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800982
983void SurfaceFlinger::waitForEvent() {
984 mEventQueue.waitMessage();
985}
986
987void SurfaceFlinger::signalTransaction() {
988 mEventQueue.invalidate();
989}
990
991void SurfaceFlinger::signalLayerUpdate() {
992 mEventQueue.invalidate();
993}
994
995void SurfaceFlinger::signalRefresh() {
996 mEventQueue.refresh();
997}
998
999status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001000 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001001 return mEventQueue.postMessage(msg, reltime);
1002}
1003
1004status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001005 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001006 status_t res = mEventQueue.postMessage(msg, reltime);
1007 if (res == NO_ERROR) {
1008 msg->wait();
1009 }
1010 return res;
1011}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001012
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001013void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001014 do {
1015 waitForEvent();
1016 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001017}
1018
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001019void SurfaceFlinger::enableHardwareVsync() {
1020 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001021 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001022 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001023 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1024 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001025 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001026 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001027}
1028
Jesse Hall948fe0c2013-10-14 12:56:09 -07001029void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001030 Mutex::Autolock _l(mHWVsyncLock);
1031
Jesse Hall948fe0c2013-10-14 12:56:09 -07001032 if (makeAvailable) {
1033 mHWVsyncAvailable = true;
1034 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001035 // Hardware vsync is not currently available, so abort the resync
1036 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001037 return;
1038 }
1039
Dan Stoza9e56aa02015-11-02 13:00:03 -08001040 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1041 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001042
1043 mPrimaryDispSync.reset();
1044 mPrimaryDispSync.setPeriod(period);
1045
1046 if (!mPrimaryHWVsyncEnabled) {
1047 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001048 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1049 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050 mPrimaryHWVsyncEnabled = true;
1051 }
1052}
1053
Jesse Hall948fe0c2013-10-14 12:56:09 -07001054void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055 Mutex::Autolock _l(mHWVsyncLock);
1056 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001057 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1058 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059 mPrimaryDispSync.endResync();
1060 mPrimaryHWVsyncEnabled = false;
1061 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001062 if (makeUnavailable) {
1063 mHWVsyncAvailable = false;
1064 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065}
1066
Tim Murray4a4e4a22016-04-19 16:29:23 +00001067void SurfaceFlinger::resyncWithRateLimit() {
1068 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1069 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001070 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001071 }
1072}
1073
Steven Thomas3cfac282017-02-06 12:29:30 -08001074void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1075 nsecs_t timestamp) {
1076 Mutex::Autolock lock(mStateLock);
1077 // Ignore any vsyncs from the non-active hardware composer.
1078 if (composer != mHwc) {
1079 return;
1080 }
1081
Jamie Gennisd1700752013-10-14 12:22:52 -07001082 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083
Jamie Gennisd1700752013-10-14 12:22:52 -07001084 { // Scope for the lock
1085 Mutex::Autolock _l(mHWVsyncLock);
1086 if (type == 0 && mPrimaryHWVsyncEnabled) {
1087 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001089 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001090
1091 if (needsHwVsync) {
1092 enableHardwareVsync();
1093 } else {
1094 disableHardwareVsync(false);
1095 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001096}
1097
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001098void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001099 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001100 *compositorTiming = mCompositorTiming;
1101}
1102
Dan Stoza9e56aa02015-11-02 13:00:03 -08001103void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1104 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1105 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1106 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001107
Dan Stoza9e56aa02015-11-02 13:00:03 -08001108 // All non-virtual displays are currently considered secure.
1109 bool isSecure = true;
1110
1111 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001112
1113 // When we're using the vr composer, the assumption is that we've
1114 // already created the IBinder object for the primary display.
1115 if (!mHwc->isUsingVrComposer()) {
1116 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1117 }
1118
Dan Stoza9e56aa02015-11-02 13:00:03 -08001119 wp<IBinder> token = mBuiltinDisplays[type];
1120
1121 sp<IGraphicBufferProducer> producer;
1122 sp<IGraphicBufferConsumer> consumer;
Chia-I Wu527747d2017-03-13 20:38:48 +00001123 BufferQueue::createBufferQueue(&producer, &consumer,
1124 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001125
1126 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1127 DisplayDevice::DISPLAY_PRIMARY, consumer);
1128 sp<DisplayDevice> hw = new DisplayDevice(this,
1129 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1130 producer, mRenderEngine->getEGLConfig());
1131 mDisplays.add(token, hw);
1132 } else {
1133 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001134 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001135 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001137 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001138 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1139 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001140 }
1141 setTransactionFlags(eDisplayTransactionNeeded);
1142
Andy McFadden9e9689c2012-10-10 18:17:51 -07001143 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001144 }
Mathias Agopian86303202012-07-24 22:46:10 -07001145}
1146
Steven Thomas3cfac282017-02-06 12:29:30 -08001147void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1148 Mutex::Autolock lock(mStateLock);
1149 if (composer == mHwc) {
1150 repaintEverything();
1151 } else {
1152 // This isn't from our current hardware composer. If it's a callback
1153 // from the real composer, forward the refresh request to vr
1154 // flinger. Otherwise ignore it.
1155 if (!composer->isUsingVrComposer()) {
1156 mVrFlinger->OnHardwareComposerRefresh();
1157 }
1158 }
1159}
1160
Dan Stoza9e56aa02015-11-02 13:00:03 -08001161void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001162 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001163 getHwComposer().setVsyncEnabled(disp,
1164 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001165}
1166
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001167void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1168 for (size_t i = 0; i < layers.size(); ++i) {
1169 layers[i]->clearHwcLayers();
1170 }
1171}
1172
1173void SurfaceFlinger::resetHwc() {
1174 disableHardwareVsync(true);
1175 clearHwcLayers(mDrawingState.layersSortedByZ);
1176 clearHwcLayers(mCurrentState.layersSortedByZ);
1177 // Clear the drawing state so that the logic inside of
1178 // handleTransactionLocked will fire. It will determine the delta between
1179 // mCurrentState and mDrawingState and re-apply all changes when we make the
1180 // transition.
1181 mDrawingState.displays.clear();
1182 mDisplays.clear();
1183}
1184
1185void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001186 bool enteringVrMode = mEnterVrMode;
1187 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1188 return;
1189 }
1190 if (enteringVrMode && !mVrHwc) {
1191 // Construct new HWComposer without holding any locks.
1192 mVrHwc = new HWComposer(true);
1193 ALOGV("Vr HWC created");
1194 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001195 {
1196 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001197
1198 if (enteringVrMode) {
1199 // Start vrflinger thread, if it hasn't been started already.
1200 if (!mVrFlinger) {
1201 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1202 int err = mVrFlinger->Run(mHwc->getComposer());
1203 if (err != NO_ERROR) {
1204 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1205 mVrFlinger.reset();
1206 mEnterVrMode = false;
1207 return;
1208 }
1209 }
1210
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001211 resetHwc();
1212
1213 mHwc = mVrHwc;
1214 mVrFlinger->EnterVrMode();
1215 } else {
1216 mVrFlinger->ExitVrMode();
1217
1218 resetHwc();
1219
1220 mHwc = mRealHwc;
1221 enableHardwareVsync();
1222 }
1223
1224 mVisibleRegionsDirty = true;
1225 invalidateHwcGeometry();
1226 android_atomic_or(1, &mRepaintEverything);
1227 setTransactionFlags(eDisplayTransactionNeeded);
1228 }
1229 if (mVrHwc) {
1230 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1231 }
1232}
1233
Mathias Agopian4fec8732012-06-29 14:12:52 -07001234void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001235 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001237 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001238 // TODO(eieio): Tied to a conditional until SELinux issues
1239 // are resolved.
1240 if (mVrModeSupported) {
1241 updateVrMode();
1242 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001243
Dan Stoza50182882016-07-08 12:02:20 -07001244 bool frameMissed = !mHadClientComposition &&
1245 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001246 (mPreviousPresentFence->getSignalTime() ==
1247 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001248 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001249 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001250 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001251 signalLayerUpdate();
1252 break;
1253 }
1254
Dan Stoza6b9454d2014-11-07 16:00:59 -08001255 bool refreshNeeded = handleMessageTransaction();
1256 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001257 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001258 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001259 // Signal a refresh if a transaction modified the window state,
1260 // a new buffer was latched, or if HWC has requested a full
1261 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001262 signalRefresh();
1263 }
1264 break;
1265 }
1266 case MessageQueue::REFRESH: {
1267 handleMessageRefresh();
1268 break;
1269 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001270 }
1271}
1272
Dan Stoza6b9454d2014-11-07 16:00:59 -08001273bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001274 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001275 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001276 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001277 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001278 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001279 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001280}
1281
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001283 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001284 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001285}
1286
1287void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001288 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001289
Pablo Ceballos40845df2016-01-25 17:41:15 -08001290 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001291
Brian Andersond6927fb2016-07-23 23:37:30 -07001292 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001293 rebuildLayerStacks();
1294 setUpHWComposer();
1295 doDebugFlashRegions();
1296 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001297 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001298
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001299 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001300
1301 mHadClientComposition = false;
1302 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1303 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1304 mHadClientComposition = mHadClientComposition ||
1305 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1306 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001307
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001309}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001310
Mathias Agopiancd60f992012-08-16 16:28:27 -07001311void SurfaceFlinger::doDebugFlashRegions()
1312{
1313 // is debugging enabled
1314 if (CC_LIKELY(!mDebugRegion))
1315 return;
1316
1317 const bool repaintEverything = mRepaintEverything;
1318 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1319 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001320 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001321 // transform the dirty region into this screen's coordinate space
1322 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1323 if (!dirtyRegion.isEmpty()) {
1324 // redraw the whole screen
1325 doComposeSurfaces(hw, Region(hw->bounds()));
1326
1327 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001328 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001329 RenderEngine& engine(getRenderEngine());
1330 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1331
Mathias Agopianda27af92012-09-13 18:17:13 -07001332 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333 }
1334 }
1335 }
1336
1337 postFramebuffer();
1338
1339 if (mDebugRegion > 1) {
1340 usleep(mDebugRegion * 1000);
1341 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001342
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001344 auto& displayDevice = mDisplays[displayId];
1345 if (!displayDevice->isDisplayOn()) {
1346 continue;
1347 }
1348
1349 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001350 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1351 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001352 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001353}
1354
Brian Andersond6927fb2016-07-23 23:37:30 -07001355void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001356{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001357 ATRACE_CALL();
1358 ALOGV("preComposition");
1359
Mathias Agopiancd60f992012-08-16 16:28:27 -07001360 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001361 mDrawingState.traverseInZOrder([&](Layer* layer) {
1362 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001363 needExtraInvalidate = true;
1364 }
Robert Carr2047fae2016-11-28 14:09:09 -08001365 });
1366
Mathias Agopiancd60f992012-08-16 16:28:27 -07001367 if (needExtraInvalidate) {
1368 signalLayerUpdate();
1369 }
1370}
1371
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001372void SurfaceFlinger::updateCompositorTiming(
1373 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1374 std::shared_ptr<FenceTime>& presentFenceTime) {
1375 // Update queue of past composite+present times and determine the
1376 // most recently known composite to present latency.
1377 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1378 nsecs_t compositeToPresentLatency = -1;
1379 while (!mCompositePresentTimes.empty()) {
1380 CompositePresentTime& cpt = mCompositePresentTimes.front();
1381 // Cached values should have been updated before calling this method,
1382 // which helps avoid duplicate syscalls.
1383 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1384 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1385 break;
1386 }
1387 compositeToPresentLatency = displayTime - cpt.composite;
1388 mCompositePresentTimes.pop();
1389 }
1390
1391 // Don't let mCompositePresentTimes grow unbounded, just in case.
1392 while (mCompositePresentTimes.size() > 16) {
1393 mCompositePresentTimes.pop();
1394 }
1395
Brian Andersond0010582017-03-07 13:20:31 -08001396 setCompositorTimingSnapped(
1397 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1398}
1399
1400void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1401 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001402 // Integer division and modulo round toward 0 not -inf, so we need to
1403 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001404 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1406 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1407
Brian Andersond0010582017-03-07 13:20:31 -08001408 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1409 if (idealLatency <= 0) {
1410 idealLatency = vsyncInterval;
1411 }
1412
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001413 // Snap the latency to a value that removes scheduling jitter from the
1414 // composition and present times, which often have >1ms of jitter.
1415 // Reducing jitter is important if an app attempts to extrapolate
1416 // something (such as user input) to an accurate diasplay time.
1417 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1418 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001419 nsecs_t bias = vsyncInterval / 2;
1420 int64_t extraVsyncs =
1421 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1422 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1423 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424
Brian Andersond0010582017-03-07 13:20:31 -08001425 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001426 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1427 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001428 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429}
1430
1431void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001432{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 ATRACE_CALL();
1434 ALOGV("postComposition");
1435
Brian Anderson3546a3f2016-07-14 11:51:14 -07001436 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001437 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001438 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001439 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001440 }
1441
Brian Andersond6927fb2016-07-23 23:37:30 -07001442 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001443
1444 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1445 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1446 glCompositionDoneFenceTime =
1447 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1448 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1449 } else {
1450 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1451 }
1452 mGlCompositionDoneTimeline.updateSignalTimes();
1453
Brian Anderson4e606e32017-03-16 15:34:57 -07001454 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1455 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1456 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001457 mDisplayTimeline.updateSignalTimes();
1458
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001459 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1460 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1461
1462 // We use the refreshStartTime which might be sampled a little later than
1463 // when we started doing work for this frame, but that should be okay
1464 // since updateCompositorTiming has snapping logic.
1465 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001466 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001467 CompositorTiming compositorTiming;
1468 {
1469 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1470 compositorTiming = mCompositorTiming;
1471 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001472
Robert Carr2047fae2016-11-28 14:09:09 -08001473 mDrawingState.traverseInZOrder([&](Layer* layer) {
1474 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001475 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001476 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001477 recordBufferingStats(layer->getName().string(),
1478 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001479 }
Robert Carr2047fae2016-11-28 14:09:09 -08001480 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001481
Brian Anderson4e606e32017-03-16 15:34:57 -07001482 if (presentFence->isValid()) {
1483 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001484 enableHardwareVsync();
1485 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001486 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001487 }
1488 }
1489
Andy McFadden5167ec62014-05-22 13:08:43 -07001490 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001491 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001492 enableHardwareVsync();
1493 }
1494 }
1495
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001496 if (mAnimCompositionPending) {
1497 mAnimCompositionPending = false;
1498
Brian Anderson4e606e32017-03-16 15:34:57 -07001499 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001500 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001501 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001502 } else {
1503 // The HWC doesn't support present fences, so use the refresh
1504 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001505 nsecs_t presentTime =
1506 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001507 mAnimFrameTracker.setActualPresentTime(presentTime);
1508 }
1509 mAnimFrameTracker.advanceFrame();
1510 }
Dan Stozab90cf072015-03-05 11:05:59 -08001511
1512 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1513 return;
1514 }
1515
1516 nsecs_t currentTime = systemTime();
1517 if (mHasPoweredOff) {
1518 mHasPoweredOff = false;
1519 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001520 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001522 if (numPeriods < NUM_BUCKETS - 1) {
1523 mFrameBuckets[numPeriods] += elapsedTime;
1524 } else {
1525 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1526 }
1527 mTotalTime += elapsedTime;
1528 }
1529 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530}
1531
1532void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 ATRACE_CALL();
1534 ALOGV("rebuildLayerStacks");
1535
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001537 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1538 ATRACE_CALL();
1539 mVisibleRegionsDirty = false;
1540 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001541
Jeff Sharkey76488112017-02-27 14:15:18 -07001542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1543 Region opaqueRegion;
1544 Region dirtyRegion;
1545 Vector<sp<Layer>> layersSortedByZ;
1546 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1547 const Transform& tr(displayDevice->getTransform());
1548 const Rect bounds(displayDevice->getBounds());
1549 if (displayDevice->isDisplayOn()) {
1550 computeVisibleRegions(
1551 displayDevice->getLayerStack(), dirtyRegion,
1552 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001553
Jeff Sharkey76488112017-02-27 14:15:18 -07001554 mDrawingState.traverseInZOrder([&](Layer* layer) {
1555 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1556 Region drawRegion(tr.transform(
1557 layer->visibleNonTransparentRegion));
1558 drawRegion.andSelf(bounds);
1559 if (!drawRegion.isEmpty()) {
1560 layersSortedByZ.add(layer);
1561 } else {
1562 // Clear out the HWC layer if this layer was
1563 // previously visible, but no longer is
1564 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1565 nullptr);
1566 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001567 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001568 // WM changes displayDevice->layerStack upon sleep/awake.
1569 // Here we make sure we delete the HWC layers even if
1570 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001571 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1572 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001573 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001574 });
1575 }
1576 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1577 displayDevice->undefinedRegion.set(bounds);
1578 displayDevice->undefinedRegion.subtractSelf(
1579 tr.transform(opaqueRegion));
1580 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001581 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001582 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001584
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 ATRACE_CALL();
1587 ALOGV("setUpHWComposer");
1588
Jesse Hall028dc8f2013-08-20 16:35:32 -07001589 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001590 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1591 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1592 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1593
1594 // If nothing has changed (!dirty), don't recompose.
1595 // If something changed, but we don't currently have any visible layers,
1596 // and didn't when we last did a composition, then skip it this time.
1597 // The second rule does two things:
1598 // - When all layers are removed from a display, we'll emit one black
1599 // frame, then nothing more until we get new layers.
1600 // - When a display is created with a private layer stack, we won't
1601 // emit any black frames until a layer is added to the layer stack.
1602 bool mustRecompose = dirty && !(empty && wasEmpty);
1603
1604 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1605 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1606 mustRecompose ? "doing" : "skipping",
1607 dirty ? "+" : "-",
1608 empty ? "+" : "-",
1609 wasEmpty ? "+" : "-");
1610
Dan Stoza71433162014-02-04 16:22:36 -08001611 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001612
1613 if (mustRecompose) {
1614 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1615 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001616 }
1617
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 // build the h/w work list
1619 if (CC_UNLIKELY(mGeometryInvalid)) {
1620 mGeometryInvalid = false;
1621 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1622 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1623 const auto hwcId = displayDevice->getHwcDisplayId();
1624 if (hwcId >= 0) {
1625 const Vector<sp<Layer>>& currentLayers(
1626 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001627 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001628 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001629 if (!layer->hasHwcLayer(hwcId)) {
1630 auto hwcLayer = mHwc->createLayer(hwcId);
1631 if (hwcLayer) {
1632 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1633 } else {
1634 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001635 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001636 }
1637 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001638
Robert Carrae060832016-11-28 10:51:00 -08001639 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001640 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001641 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001642 }
1643 }
1644 }
1645 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 }
Riley Andrews03414a12014-07-01 14:22:59 -07001647
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001648
1649 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1650
Dan Stoza9e56aa02015-11-02 13:00:03 -08001651 // Set the per-frame data
1652 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1653 auto& displayDevice = mDisplays[displayId];
1654 const auto hwcId = displayDevice->getHwcDisplayId();
1655 if (hwcId < 0) {
1656 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001657 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001658 if (colorMatrix != mPreviousColorMatrix) {
1659 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1660 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1661 "display %zd: %d", displayId, result);
1662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1664 layer->setPerFrameData(displayDevice);
1665 }
1666 }
1667
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001668 mPreviousColorMatrix = colorMatrix;
1669
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001671 auto& displayDevice = mDisplays[displayId];
1672 if (!displayDevice->isDisplayOn()) {
1673 continue;
1674 }
1675
1676 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1678 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001679 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001681
Mathias Agopiancd60f992012-08-16 16:28:27 -07001682void SurfaceFlinger::doComposition() {
1683 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 ALOGV("doComposition");
1685
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001686 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001687 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001688 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001689 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690 // transform the dirty region into this screen's coordinate space
1691 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001692
1693 // repaint the framebuffer (if needed)
1694 doDisplayComposition(hw, dirtyRegion);
1695
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696 hw->dirtyRegion.clear();
1697 hw->flip(hw->swapRegion);
1698 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001699 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001701 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702}
1703
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001704void SurfaceFlinger::postFramebuffer()
1705{
Mathias Agopian841cde52012-03-01 15:44:37 -08001706 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001708
Mathias Agopiana44b0412011-10-16 18:46:35 -07001709 const nsecs_t now = systemTime();
1710 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001711
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1713 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001714 if (!displayDevice->isDisplayOn()) {
1715 continue;
1716 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001717 const auto hwcId = displayDevice->getHwcDisplayId();
1718 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001719 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001720 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001721 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001722 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1724 sp<Fence> releaseFence = Fence::NO_FENCE;
1725 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1726 releaseFence = displayDevice->getClientTargetAcquireFence();
1727 } else {
1728 auto hwcLayer = layer->getHwcLayer(hwcId);
1729 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001730 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001731 layer->onLayerDisplayed(releaseFence);
1732 }
1733 if (hwcId >= 0) {
1734 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001735 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001736 }
1737
Mathias Agopiana44b0412011-10-16 18:46:35 -07001738 mLastSwapBufferTime = systemTime() - now;
1739 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001740
1741 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1742 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1743 logFrameStats();
1744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001745}
1746
Mathias Agopian87baae12012-07-31 12:38:26 -07001747void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001748{
Mathias Agopian841cde52012-03-01 15:44:37 -08001749 ATRACE_CALL();
1750
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001751 // here we keep a copy of the drawing state (that is the state that's
1752 // going to be overwritten by handleTransactionLocked()) outside of
1753 // mStateLock so that the side-effects of the State assignment
1754 // don't happen with mStateLock held (which can cause deadlocks).
1755 State drawingState(mDrawingState);
1756
Mathias Agopianca4d3602011-05-19 15:38:14 -07001757 Mutex::Autolock _l(mStateLock);
1758 const nsecs_t now = systemTime();
1759 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001760
Mathias Agopianca4d3602011-05-19 15:38:14 -07001761 // Here we're guaranteed that some transaction flags are set
1762 // so we can call handleTransactionLocked() unconditionally.
1763 // We call getTransactionFlags(), which will also clear the flags,
1764 // with mStateLock held to guarantee that mCurrentState won't change
1765 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001766
Mathias Agopiane57f2922012-08-09 16:29:12 -07001767 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001768 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001769
Mathias Agopianca4d3602011-05-19 15:38:14 -07001770 mLastTransactionTime = systemTime() - now;
1771 mDebugInTransaction = 0;
1772 invalidateHwcGeometry();
1773 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001774}
1775
Mathias Agopian87baae12012-07-31 12:38:26 -07001776void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001777{
Dan Stoza7dde5992015-05-22 09:51:44 -07001778 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001779 mCurrentState.traverseInZOrder([](Layer* layer) {
1780 layer->notifyAvailableFrames();
1781 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001782
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001783 /*
1784 * Traversal of the children
1785 * (perform the transaction for each of them if needed)
1786 */
1787
Mathias Agopian3559b072012-08-15 13:46:03 -07001788 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001789 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001791 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001792
1793 const uint32_t flags = layer->doTransaction(0);
1794 if (flags & Layer::eVisibleRegion)
1795 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001796 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797 }
1798
1799 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001800 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801 */
1802
Mathias Agopiane57f2922012-08-09 16:29:12 -07001803 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001804 // here we take advantage of Vector's copy-on-write semantics to
1805 // improve performance by skipping the transaction entirely when
1806 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001807 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1808 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001809 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001811 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001812 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001813
1814 // find the displays that were removed
1815 // (ie: in drawing state but not in current state)
1816 // also handle displays that changed
1817 // (ie: displays that are in both lists)
1818 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001819 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1820 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001821 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001822 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001823 // Call makeCurrent() on the primary display so we can
1824 // be sure that nothing associated with this display
1825 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001826 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001827 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001828 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1829 if (hw != NULL)
1830 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001831 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001832 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001833 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 } else {
1835 ALOGW("trying to remove the main display");
1836 }
1837 } else {
1838 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001839 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001840 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001841 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1842 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001843 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001844 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001845 // recreating the DisplayDevice, so we just remove it
1846 // from the drawing state, so that it get re-added
1847 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001848 sp<DisplayDevice> hw(getDisplayDevice(display));
1849 if (hw != NULL)
1850 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001851 mDisplays.removeItem(display);
1852 mDrawingState.displays.removeItemsAt(i);
1853 dc--; i--;
1854 // at this point we must loop to the next item
1855 continue;
1856 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001857
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001858 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001859 if (disp != NULL) {
1860 if (state.layerStack != draw[i].layerStack) {
1861 disp->setLayerStack(state.layerStack);
1862 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001863 if ((state.orientation != draw[i].orientation)
1864 || (state.viewport != draw[i].viewport)
1865 || (state.frame != draw[i].frame))
1866 {
1867 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001868 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001869 }
Michael Lentine47e45402014-07-18 15:34:25 -07001870 if (state.width != draw[i].width || state.height != draw[i].height) {
1871 disp->setDisplaySize(state.width, state.height);
1872 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001873 }
1874 }
1875 }
1876
1877 // find displays that were added
1878 // (ie: in current state but not in drawing state)
1879 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001880 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001881 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001882
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001883 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001884 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001885 sp<IGraphicBufferProducer> bqProducer;
1886 sp<IGraphicBufferConsumer> bqConsumer;
Chia-I Wu527747d2017-03-13 20:38:48 +00001887 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1888 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001889
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001891 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001892 // Virtual displays without a surface are dormant:
1893 // they have external state (layer stack, projection,
1894 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001895 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001896
Dan Stoza8cf150a2016-08-02 10:27:31 -07001897 if (mUseHwcVirtualDisplays) {
1898 int width = 0;
1899 int status = state.surface->query(
1900 NATIVE_WINDOW_WIDTH, &width);
1901 ALOGE_IF(status != NO_ERROR,
1902 "Unable to query width (%d)", status);
1903 int height = 0;
1904 status = state.surface->query(
1905 NATIVE_WINDOW_HEIGHT, &height);
1906 ALOGE_IF(status != NO_ERROR,
1907 "Unable to query height (%d)", status);
1908 int intFormat = 0;
1909 status = state.surface->query(
1910 NATIVE_WINDOW_FORMAT, &intFormat);
1911 ALOGE_IF(status != NO_ERROR,
1912 "Unable to query format (%d)", status);
1913 auto format = static_cast<android_pixel_format_t>(
1914 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001915
Dan Stoza8cf150a2016-08-02 10:27:31 -07001916 mHwc->allocateVirtualDisplay(width, height, &format,
1917 &hwcId);
1918 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919
Dan Stoza5cf424b2016-05-20 14:02:39 -07001920 // TODO: Plumb requested format back up to consumer
1921
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 sp<VirtualDisplaySurface> vds =
1923 new VirtualDisplaySurface(*mHwc,
1924 hwcId, state.surface, bqProducer,
1925 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001926
1927 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001928 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001929 }
1930 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001931 ALOGE_IF(state.surface!=NULL,
1932 "adding a supported display, but rendering "
1933 "surface is provided (%p), ignoring it",
1934 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001935
1936 hwcId = state.type;
1937 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1938 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001939 }
1940
1941 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001942 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001943 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 state.type, hwcId, state.isSecure, display,
1945 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001946 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001947 hw->setLayerStack(state.layerStack);
1948 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001949 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001950 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001951 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001953 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001954 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001955 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001956 }
1957 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001958 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001959 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960
Mathias Agopian84300952012-11-21 16:02:13 -08001961 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1962 // The transform hint might have changed for some layers
1963 // (either because a display has changed, or because a layer
1964 // as changed).
1965 //
1966 // Walk through all the layers in currentLayers,
1967 // and update their transform hint.
1968 //
1969 // If a layer is visible only on a single display, then that
1970 // display is used to calculate the hint, otherwise we use the
1971 // default display.
1972 //
1973 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1974 // the hint is set before we acquire a buffer from the surface texture.
1975 //
1976 // NOTE: layer transactions have taken place already, so we use their
1977 // drawing state. However, SurfaceFlinger's own transaction has not
1978 // happened yet, so we must use the current state layer list
1979 // (soon to become the drawing state list).
1980 //
1981 sp<const DisplayDevice> disp;
1982 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001983 bool first = true;
1984 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001985 // NOTE: we rely on the fact that layers are sorted by
1986 // layerStack first (so we don't have to traverse the list
1987 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001989 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001990 currentlayerStack = layerStack;
1991 // figure out if this layerstack is mirrored
1992 // (more than one display) if so, pick the default display,
1993 // if not, pick the only display it's on.
1994 disp.clear();
1995 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1996 sp<const DisplayDevice> hw(mDisplays[dpy]);
1997 if (hw->getLayerStack() == currentlayerStack) {
1998 if (disp == NULL) {
1999 disp = hw;
2000 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002001 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002002 break;
2003 }
2004 }
2005 }
2006 }
Chet Haase91d25932013-04-11 15:24:55 -07002007 if (disp == NULL) {
2008 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2009 // redraw after transform hint changes. See bug 8508397.
2010
2011 // could be null when this layer is using a layerStack
2012 // that is not visible on any display. Also can occur at
2013 // screen off/on times.
2014 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002015 }
Chet Haase91d25932013-04-11 15:24:55 -07002016 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002017
2018 first = false;
2019 });
Mathias Agopian84300952012-11-21 16:02:13 -08002020 }
2021
2022
Mathias Agopian3559b072012-08-15 13:46:03 -07002023 /*
2024 * Perform our own transaction if needed
2025 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002026
2027 if (mLayersAdded) {
2028 mLayersAdded = false;
2029 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002030 mVisibleRegionsDirty = true;
2031 }
2032
2033 // some layers might have been removed, so
2034 // we need to update the regions they're exposing.
2035 if (mLayersRemoved) {
2036 mLayersRemoved = false;
2037 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002038 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002039 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002040 // this layer is not visible anymore
2041 // TODO: we could traverse the tree from front to back and
2042 // compute the actual visible region
2043 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002044 Region visibleReg;
2045 visibleReg.set(layer->computeScreenBounds());
2046 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002047 }
Robert Carr2047fae2016-11-28 14:09:09 -08002048 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049 }
2050
2051 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002052
2053 updateCursorAsync();
2054}
2055
2056void SurfaceFlinger::updateCursorAsync()
2057{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2059 auto& displayDevice = mDisplays[displayId];
2060 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002061 continue;
2062 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063
2064 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2065 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002066 }
2067 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002068}
2069
2070void SurfaceFlinger::commitTransaction()
2071{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002072 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002073 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002074 for (const auto& l : mLayersPendingRemoval) {
2075 recordBufferingStats(l->getName().string(),
2076 l->getOccupancyHistory(true));
2077 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002078 }
2079 mLayersPendingRemoval.clear();
2080 }
2081
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082 // If this transaction is part of a window animation then the next frame
2083 // we composite should be considered an animation as well.
2084 mAnimCompositionPending = mAnimTransactionPending;
2085
Mathias Agopian4fec8732012-06-29 14:12:52 -07002086 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002087 mDrawingState.traverseInZOrder([](Layer* layer) {
2088 layer->commitChildList();
2089 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002090 mTransactionPending = false;
2091 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002092 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093}
2094
Robert Carr2047fae2016-11-28 14:09:09 -08002095void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002096 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002097{
Mathias Agopian841cde52012-03-01 15:44:37 -08002098 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101 Region aboveOpaqueLayers;
2102 Region aboveCoveredLayers;
2103 Region dirty;
2104
Mathias Agopian87baae12012-07-31 12:38:26 -07002105 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106
Robert Carr2047fae2016-11-28 14:09:09 -08002107 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002109 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110
Jesse Hall01e29052013-02-19 16:13:35 -08002111 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002112 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002113 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002114
Mathias Agopianab028732010-03-16 16:41:46 -07002115 /*
2116 * opaqueRegion: area of a surface that is fully opaque.
2117 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002119
2120 /*
2121 * visibleRegion: area of a surface that is visible on screen
2122 * and not fully transparent. This is essentially the layer's
2123 * footprint minus the opaque regions above it.
2124 * Areas covered by a translucent surface are considered visible.
2125 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002127
2128 /*
2129 * coveredRegion: area of a surface that is covered by all
2130 * visible regions above it (which includes the translucent areas).
2131 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002133
Jesse Halla8026d22012-09-25 13:25:04 -07002134 /*
2135 * transparentRegion: area of a surface that is hinted to be completely
2136 * transparent. This is only used to tell when the layer has no visible
2137 * non-transparent regions and can be removed from the layer list. It
2138 * does not affect the visibleRegion of this layer or any layers
2139 * beneath it. The hint may not be correct if apps don't respect the
2140 * SurfaceView restrictions (which, sadly, some don't).
2141 */
2142 Region transparentRegion;
2143
Mathias Agopianab028732010-03-16 16:41:46 -07002144
2145 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002146 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002147 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002148 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002150 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002151 if (!visibleRegion.isEmpty()) {
2152 // Remove the transparent area from the visible region
2153 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002154 if (tr.preserveRects()) {
2155 // transform the transparent region
2156 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002157 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002158 // transformation too complex, can't do the
2159 // transparent region optimization.
2160 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002161 }
Mathias Agopianab028732010-03-16 16:41:46 -07002162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163
Mathias Agopianab028732010-03-16 16:41:46 -07002164 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002165 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002167 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2168 // the opaque region is the layer's footprint
2169 opaqueRegion = visibleRegion;
2170 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002171 }
2172 }
2173
Mathias Agopianab028732010-03-16 16:41:46 -07002174 // Clip the covered region to the visible region
2175 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2176
2177 // Update aboveCoveredLayers for next (lower) layer
2178 aboveCoveredLayers.orSelf(visibleRegion);
2179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180 // subtract the opaque region covered by the layers above us
2181 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002182
2183 // compute this layer's dirty region
2184 if (layer->contentDirty) {
2185 // we need to invalidate the whole region
2186 dirty = visibleRegion;
2187 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002188 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002189 layer->contentDirty = false;
2190 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002191 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002192 * the exposed region consists of two components:
2193 * 1) what's VISIBLE now and was COVERED before
2194 * 2) what's EXPOSED now less what was EXPOSED before
2195 *
2196 * note that (1) is conservative, we start with the whole
2197 * visible region but only keep what used to be covered by
2198 * something -- which mean it may have been exposed.
2199 *
2200 * (2) handles areas that were not covered by anything but got
2201 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002202 */
Mathias Agopianab028732010-03-16 16:41:46 -07002203 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002204 const Region oldVisibleRegion = layer->visibleRegion;
2205 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002206 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2207 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002208 }
2209 dirty.subtractSelf(aboveOpaqueLayers);
2210
2211 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002212 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213
Mathias Agopianab028732010-03-16 16:41:46 -07002214 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002215 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002216
Jesse Halla8026d22012-09-25 13:25:04 -07002217 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218 layer->setVisibleRegion(visibleRegion);
2219 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002220 layer->setVisibleNonTransparentRegion(
2221 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002222 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223
Mathias Agopian87baae12012-07-31 12:38:26 -07002224 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225}
2226
Mathias Agopian87baae12012-07-31 12:38:26 -07002227void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2228 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002229 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002230 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2231 if (hw->getLayerStack() == layerStack) {
2232 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002233 }
2234 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002235}
2236
Dan Stoza6b9454d2014-11-07 16:00:59 -08002237bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002239 ALOGV("handlePageFlip");
2240
Brian Andersond6927fb2016-07-23 23:37:30 -07002241 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242
Mathias Agopian4fec8732012-06-29 14:12:52 -07002243 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002244 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002245
2246 // Store the set of layers that need updates. This set must not change as
2247 // buffers are being latched, as this could result in a deadlock.
2248 // Example: Two producers share the same command stream and:
2249 // 1.) Layer 0 is latched
2250 // 2.) Layer 0 gets a new frame
2251 // 2.) Layer 1 gets a new frame
2252 // 3.) Layer 1 is latched.
2253 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2254 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002255 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002256 if (layer->hasQueuedFrame()) {
2257 frameQueued = true;
2258 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002259 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002260 } else {
2261 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002262 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002263 } else {
2264 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002265 }
Robert Carr2047fae2016-11-28 14:09:09 -08002266 });
2267
Dan Stoza9e56aa02015-11-02 13:00:03 -08002268 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002269 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002270 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002271 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002273
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002274 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002275
2276 // If we will need to wake up at some time in the future to deal with a
2277 // queued frame that shouldn't be displayed during this vsync period, wake
2278 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002280 signalLayerUpdate();
2281 }
2282
2283 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002284 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285}
2286
Mathias Agopianad456f92011-01-13 17:53:01 -08002287void SurfaceFlinger::invalidateHwcGeometry()
2288{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002290}
2291
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002292
Fabien Sanglard830b8472016-11-30 16:35:58 -08002293void SurfaceFlinger::doDisplayComposition(
2294 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002295 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296{
Dan Stoza71433162014-02-04 16:22:36 -08002297 // We only need to actually compose the display if:
2298 // 1) It is being handled by hardware composer, which may need this to
2299 // keep its virtual display state machine in sync, or
2300 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002301 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002302 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002303 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002304 return;
2305 }
2306
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 ALOGV("doDisplayComposition");
2308
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 Region dirtyRegion(inDirtyRegion);
2310
Mathias Agopianb8a55602009-06-26 19:06:36 -07002311 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002312 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Fabien Sanglard830b8472016-11-30 16:35:58 -08002314 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002315 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002316 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2317 // takes a rectangle, we must make sure to update that whole
2318 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002319 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002320 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002321 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002322 // We need to redraw the rectangle that will be updated
2323 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002324 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002325 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002326 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002327 } else {
2328 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002329 dirtyRegion.set(displayDevice->bounds());
2330 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331 }
2332 }
2333
Fabien Sanglard830b8472016-11-30 16:35:58 -08002334 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002336 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002338
2339 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341}
2342
Dan Stoza9e56aa02015-11-02 13:00:03 -08002343bool SurfaceFlinger::doComposeSurfaces(
2344 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002345{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002346 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002347
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002349
2350 mat4 oldColorMatrix;
2351 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2352 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2353 if (applyColorMatrix) {
2354 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2355 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2356 }
2357
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2359 if (hasClientComposition) {
2360 ALOGV("hasClientComposition");
2361
2362 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002363 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002365 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2366 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2367 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2368 }
2369 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002370 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002371
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002372 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2374 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002375 // when using overlays, we assume a fully transparent framebuffer
2376 // NOTE: we could reduce how much we need to clear, for instance
2377 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002378 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002379 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002380 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002381 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002382 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002384
2385 // we remove the scissor part
2386 // we're left with the letterbox region
2387 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002389
2390 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002392
2393 // but limit it to the dirty region
2394 region.andSelf(dirty);
2395
Mathias Agopianb9494d52012-04-18 02:28:45 -07002396 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002397 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002398 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002399 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002400 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002401 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002402
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002404 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002405 // scissor on the main display. It should never be needed
2406 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 const Rect& bounds(displayDevice->getBounds());
2408 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002409 if (scissor != bounds) {
2410 // scissor doesn't match the screen's dimensions, so we
2411 // need to clear everything outside of it and enable
2412 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002413
Mathias Agopianf45c5102012-10-24 16:29:17 -07002414 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002415 const uint32_t height = displayDevice->getHeight();
2416 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002417 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002418 }
2419 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002420 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002421
Mathias Agopian85d751c2012-08-29 16:59:24 -07002422 /*
2423 * and then, render the layers targeted at the framebuffer
2424 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002425
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 ALOGV("Rendering client layers");
2427 const Transform& displayTransform = displayDevice->getTransform();
2428 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002429 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002430 bool firstLayer = true;
2431 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2432 const Region clip(dirty.intersect(
2433 displayTransform.transform(layer->visibleRegion)));
2434 ALOGV("Layer: %s", layer->getName().string());
2435 ALOGV(" Composition type: %s",
2436 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002437 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 switch (layer->getCompositionType(hwcId)) {
2439 case HWC2::Composition::Cursor:
2440 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002441 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002442 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002443 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2445 layer->isOpaque(state) && (state.alpha == 1.0f)
2446 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002447 // never clear the very first layer since we're
2448 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002449 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002450 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002451 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002452 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 case HWC2::Composition::Client: {
2454 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002455 break;
2456 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002458 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002459 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 } else {
2461 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002462 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002464 }
2465 } else {
2466 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002468 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002470 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002472 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002473 }
2474 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002475
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002476 if (applyColorMatrix) {
2477 getRenderEngine().setupColorTransform(oldColorMatrix);
2478 }
2479
Mathias Agopianf45c5102012-10-24 16:29:17 -07002480 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002482 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483}
2484
Fabien Sanglard830b8472016-11-30 16:35:58 -08002485void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2486 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002487 RenderEngine& engine(getRenderEngine());
2488 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489}
2490
Dan Stoza7d89d062015-04-30 13:29:25 -07002491status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002492 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002493 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 const sp<Layer>& lbc,
2495 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002496{
Dan Stoza7d89d062015-04-30 13:29:25 -07002497 // add this layer to the current state list
2498 {
2499 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002500 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002501 return NO_MEMORY;
2502 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002503 if (parent == nullptr) {
2504 mCurrentState.layersSortedByZ.add(lbc);
2505 } else {
2506 parent->addChild(lbc);
2507 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002508 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 mLayersAdded = true;
2510 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002511 }
2512
Mathias Agopian96f08192010-06-02 23:28:45 -07002513 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002514 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002515
Dan Stoza7d89d062015-04-30 13:29:25 -07002516 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002517}
2518
Robert Carr9524cb32017-02-13 11:32:32 -08002519status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002520 Mutex::Autolock _l(mStateLock);
2521
Robert Carr1f0a16a2016-10-24 16:27:39 -07002522 const auto& p = layer->getParent();
2523 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2524 mCurrentState.layersSortedByZ.remove(layer);
2525
Robert Carr136e2f62017-02-08 17:54:29 -08002526 // As a matter of normal operation, the LayerCleaner will produce a second
2527 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2528 // so we will succeed in promoting it, but it's already been removed
2529 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2530 // otherwise something has gone wrong and we are leaking the layer.
2531 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2533 layer->getName().string(),
2534 (p != nullptr) ? p->getName().string() : "no-parent");
2535 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002536 } else if (index < 0) {
2537 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002538 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539
2540 mLayersPendingRemoval.add(layer);
2541 mLayersRemoved = true;
2542 mNumLayers--;
2543 setTransactionFlags(eTransactionNeeded);
2544 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545}
2546
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002547uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002548 return android_atomic_release_load(&mTransactionFlags);
2549}
2550
Mathias Agopian3f844832013-08-07 21:24:32 -07002551uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2553}
2554
Mathias Agopian3f844832013-08-07 21:24:32 -07002555uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2557 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002558 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 }
2560 return old;
2561}
2562
Mathias Agopian8b33f032012-07-24 20:43:54 -07002563void SurfaceFlinger::setTransactionState(
2564 const Vector<ComposerState>& state,
2565 const Vector<DisplayState>& displays,
2566 uint32_t flags)
2567{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002568 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002569 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002570 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002571
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002572 if (flags & eAnimation) {
2573 // For window updates that are part of an animation we must wait for
2574 // previous animation "frames" to be handled.
2575 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002576 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002577 if (CC_UNLIKELY(err != NO_ERROR)) {
2578 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002579 // caller after a few seconds.
2580 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2581 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 mAnimTransactionPending = false;
2583 break;
2584 }
2585 }
2586 }
2587
Mathias Agopiane57f2922012-08-09 16:29:12 -07002588 size_t count = displays.size();
2589 for (size_t i=0 ; i<count ; i++) {
2590 const DisplayState& s(displays[i]);
2591 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002592 }
2593
Mathias Agopiane57f2922012-08-09 16:29:12 -07002594 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002595 for (size_t i=0 ; i<count ; i++) {
2596 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002597 // Here we need to check that the interface we're given is indeed
2598 // one of our own. A malicious client could give us a NULL
2599 // IInterface, or one of its own or even one of our own but a
2600 // different type. All these situations would cause us to crash.
2601 //
2602 // NOTE: it would be better to use RTTI as we could directly check
2603 // that we have a Client*. however, RTTI is disabled in Android.
2604 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002605 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002606 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002607 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002608 sp<Client> client( static_cast<Client *>(s.client.get()) );
2609 transactionFlags |= setClientStateLocked(client, s.state);
2610 }
2611 }
2612 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002613 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002614
Robert Carr2a7dbb42016-05-24 11:41:28 -07002615 // If a synchronous transaction is explicitly requested without any changes,
2616 // force a transaction anyway. This can be used as a flush mechanism for
2617 // previous async transactions.
2618 if (transactionFlags == 0 && (flags & eSynchronous)) {
2619 transactionFlags = eTransactionNeeded;
2620 }
2621
Mathias Agopian386aa982011-11-07 21:58:03 -08002622 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002623 if (mInterceptor.isEnabled()) {
2624 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2625 }
Irvel468051e2016-06-13 16:44:44 -07002626
Mathias Agopian386aa982011-11-07 21:58:03 -08002627 // this triggers the transaction
2628 setTransactionFlags(transactionFlags);
2629
2630 // if this is a synchronous transaction, wait for it to take effect
2631 // before returning.
2632 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002633 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002634 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002635 if (flags & eAnimation) {
2636 mAnimTransactionPending = true;
2637 }
2638 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002639 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2640 if (CC_UNLIKELY(err != NO_ERROR)) {
2641 // just in case something goes wrong in SF, return to the
2642 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002643 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2644 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002645 break;
2646 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 }
2649}
2650
Mathias Agopiane57f2922012-08-09 16:29:12 -07002651uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2652{
Jesse Hall9a143922012-10-04 16:29:19 -07002653 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2654 if (dpyIdx < 0)
2655 return 0;
2656
Mathias Agopiane57f2922012-08-09 16:29:12 -07002657 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002658 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002659 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002660 const uint32_t what = s.what;
2661 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002662 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002663 disp.surface = s.surface;
2664 flags |= eDisplayTransactionNeeded;
2665 }
2666 }
2667 if (what & DisplayState::eLayerStackChanged) {
2668 if (disp.layerStack != s.layerStack) {
2669 disp.layerStack = s.layerStack;
2670 flags |= eDisplayTransactionNeeded;
2671 }
2672 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002673 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002674 if (disp.orientation != s.orientation) {
2675 disp.orientation = s.orientation;
2676 flags |= eDisplayTransactionNeeded;
2677 }
2678 if (disp.frame != s.frame) {
2679 disp.frame = s.frame;
2680 flags |= eDisplayTransactionNeeded;
2681 }
2682 if (disp.viewport != s.viewport) {
2683 disp.viewport = s.viewport;
2684 flags |= eDisplayTransactionNeeded;
2685 }
2686 }
Michael Lentine47e45402014-07-18 15:34:25 -07002687 if (what & DisplayState::eDisplaySizeChanged) {
2688 if (disp.width != s.width) {
2689 disp.width = s.width;
2690 flags |= eDisplayTransactionNeeded;
2691 }
2692 if (disp.height != s.height) {
2693 disp.height = s.height;
2694 flags |= eDisplayTransactionNeeded;
2695 }
2696 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002697 }
2698 return flags;
2699}
2700
2701uint32_t SurfaceFlinger::setClientStateLocked(
2702 const sp<Client>& client,
2703 const layer_state_t& s)
2704{
2705 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002706 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002707 if (layer != 0) {
2708 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002709 bool geometryAppliesWithResize =
2710 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002711 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002712 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002714 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 }
2716 if (what & layer_state_t::eLayerChanged) {
2717 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 const auto& p = layer->getParent();
2719 if (p == nullptr) {
2720 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2721 if (layer->setLayer(s.z) && idx >= 0) {
2722 mCurrentState.layersSortedByZ.removeAt(idx);
2723 mCurrentState.layersSortedByZ.add(layer);
2724 // we need traversal (state changed)
2725 // AND transaction (list changed)
2726 flags |= eTransactionNeeded|eTraversalNeeded;
2727 }
2728 } else {
2729 if (p->setChildLayer(layer, s.z)) {
2730 flags |= eTransactionNeeded|eTraversalNeeded;
2731 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002732 }
2733 }
2734 if (what & layer_state_t::eSizeChanged) {
2735 if (layer->setSize(s.w, s.h)) {
2736 flags |= eTraversalNeeded;
2737 }
2738 }
2739 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 flags |= eTraversalNeeded;
2742 }
2743 if (what & layer_state_t::eMatrixChanged) {
2744 if (layer->setMatrix(s.matrix))
2745 flags |= eTraversalNeeded;
2746 }
2747 if (what & layer_state_t::eTransparentRegionChanged) {
2748 if (layer->setTransparentRegionHint(s.transparentRegion))
2749 flags |= eTraversalNeeded;
2750 }
Dan Stoza23116082015-06-18 14:58:39 -07002751 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002752 if (layer->setFlags(s.flags, s.mask))
2753 flags |= eTraversalNeeded;
2754 }
2755 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002756 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 flags |= eTraversalNeeded;
2758 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002759 if (what & layer_state_t::eFinalCropChanged) {
2760 if (layer->setFinalCrop(s.finalCrop))
2761 flags |= eTraversalNeeded;
2762 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002764 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 // We only allow setting layer stacks for top level layers,
2766 // everything else inherits layer stack from its parent.
2767 if (layer->hasParent()) {
2768 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2769 layer->getName().string());
2770 } else if (idx < 0) {
2771 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2772 "that also does not appear in the top level layer list. Something"
2773 " has gone wrong.", layer->getName().string());
2774 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 mCurrentState.layersSortedByZ.removeAt(idx);
2776 mCurrentState.layersSortedByZ.add(layer);
2777 // we need traversal (state changed)
2778 // AND transaction (list changed)
2779 flags |= eTransactionNeeded|eTraversalNeeded;
2780 }
2781 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002782 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002783 if (s.barrierHandle != nullptr) {
2784 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2785 } else if (s.barrierGbp != nullptr) {
2786 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2787 if (authenticateSurfaceTextureLocked(gbp)) {
2788 const auto& otherLayer =
2789 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2790 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2791 } else {
2792 ALOGE("Attempt to defer transaction to to an"
2793 " unrecognized GraphicBufferProducer");
2794 }
2795 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002796 // We don't trigger a traversal here because if no other state is
2797 // changed, we don't want this to cause any more work
2798 }
Robert Carr1db73f62016-12-21 12:58:51 -08002799 if (what & layer_state_t::eReparentChildren) {
2800 if (layer->reparentChildren(s.reparentHandle)) {
2801 flags |= eTransactionNeeded|eTraversalNeeded;
2802 }
2803 }
Robert Carr9524cb32017-02-13 11:32:32 -08002804 if (what & layer_state_t::eDetachChildren) {
2805 layer->detachChildren();
2806 }
Robert Carrc3574f72016-03-24 12:19:32 -07002807 if (what & layer_state_t::eOverrideScalingModeChanged) {
2808 layer->setOverrideScalingMode(s.overrideScalingMode);
2809 // We don't trigger a traversal here because if no other state is
2810 // changed, we don't want this to cause any more work
2811 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002812 }
2813 return flags;
2814}
2815
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002816status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002817 const String8& name,
2818 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002819 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002820 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2821 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002823 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002824 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002825 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002826 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002827 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002828
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002829 status_t result = NO_ERROR;
2830
2831 sp<Layer> layer;
2832
Mathias Agopian3165cc22012-08-08 19:42:09 -07002833 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2834 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002835 result = createNormalLayer(client,
2836 name, w, h, flags, format,
2837 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002839 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002840 result = createDimLayer(client,
2841 name, w, h, flags,
2842 handle, gbp, &layer);
2843 break;
2844 default:
2845 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846 break;
2847 }
2848
Dan Stoza7d89d062015-04-30 13:29:25 -07002849 if (result != NO_ERROR) {
2850 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002852
Albert Chaulk479c60c2017-01-27 14:21:34 -05002853 layer->setInfo(windowType, ownerUid);
2854
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 if (result != NO_ERROR) {
2857 return result;
2858 }
Irvelffc9efc2016-07-27 15:16:37 -07002859 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002860
2861 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002862 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863}
2864
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002865status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2866 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2867 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868{
2869 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002870 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 case PIXEL_FORMAT_TRANSPARENT:
2872 case PIXEL_FORMAT_TRANSLUCENT:
2873 format = PIXEL_FORMAT_RGBA_8888;
2874 break;
2875 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002876 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 break;
2878 }
2879
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002880 *outLayer = new Layer(this, client, name, w, h, flags);
2881 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2882 if (err == NO_ERROR) {
2883 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002884 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002886
2887 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2888 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889}
2890
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002891status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2892 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2893 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002895 *outLayer = new LayerDim(this, client, name, w, h, flags);
2896 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002897 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002898 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002899}
2900
Mathias Agopianac9fa422013-02-11 16:40:36 -08002901status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902{
Robert Carr9524cb32017-02-13 11:32:32 -08002903 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002904 status_t err = NO_ERROR;
2905 sp<Layer> l(client->getLayerUser(handle));
2906 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002907 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002908 err = removeLayer(l);
2909 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2910 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002911 }
2912 return err;
2913}
2914
Mathias Agopian13127d82013-03-05 17:47:11 -08002915status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002916{
Mathias Agopian67106042013-03-14 19:18:13 -07002917 // called by ~LayerCleaner() when all references to the IBinder (handle)
2918 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002919 sp<Layer> l = layer.promote();
2920 if (l == nullptr) {
2921 // The layer has already been removed, carry on
2922 return NO_ERROR;
2923 } if (l->getParent() != nullptr) {
2924 // If we have a parent, then we can continue to live as long as it does.
2925 return NO_ERROR;
2926 }
2927 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928}
2929
Mathias Agopianb60314a2012-04-10 22:09:54 -07002930// ---------------------------------------------------------------------------
2931
Andy McFadden13a082e2012-08-24 10:16:42 -07002932void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002933 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002934 Vector<ComposerState> state;
2935 Vector<DisplayState> displays;
2936 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002937 d.what = DisplayState::eDisplayProjectionChanged |
2938 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002939 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002940 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002941 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002942 d.frame.makeInvalid();
2943 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002944 d.width = 0;
2945 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002946 displays.add(d);
2947 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002948 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002949
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2951 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002952 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002953
Brian Andersond0010582017-03-07 13:20:31 -08002954 // Use phase of 0 since phase is not known.
2955 // Use latency of 0, which will snap to the ideal latency.
2956 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002957}
2958
2959void SurfaceFlinger::initializeDisplays() {
2960 class MessageScreenInitialized : public MessageBase {
2961 SurfaceFlinger* flinger;
2962 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002963 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002964 virtual bool handler() {
2965 flinger->onInitializeDisplays();
2966 return true;
2967 }
2968 };
2969 sp<MessageBase> msg = new MessageScreenInitialized(this);
2970 postMessageAsync(msg); // we may be called from main thread, use async message
2971}
2972
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002973void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2974 int mode) {
2975 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2976 this);
2977 int32_t type = hw->getDisplayType();
2978 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002979
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002980 if (mode == currentMode) {
2981 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002982 return;
2983 }
2984
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002985 hw->setPowerMode(mode);
2986 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2987 ALOGW("Trying to set power mode for virtual display");
2988 return;
2989 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002990
Irvelffc9efc2016-07-27 15:16:37 -07002991 if (mInterceptor.isEnabled()) {
2992 Mutex::Autolock _l(mStateLock);
2993 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2994 if (idx < 0) {
2995 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2996 return;
2997 }
2998 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2999 }
3000
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003001 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003002 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003003 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003004 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3005 // FIXME: eventthread only knows about the main display right now
3006 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003007 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003010 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003011 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003012 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003013
3014 struct sched_param param = {0};
3015 param.sched_priority = 1;
3016 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3017 ALOGW("Couldn't set SCHED_FIFO on display on");
3018 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003019 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003020 // Turn off the display
3021 struct sched_param param = {0};
3022 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3023 ALOGW("Couldn't set SCHED_OTHER on display off");
3024 }
3025
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003026 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003027 disableHardwareVsync(true); // also cancels any in-progress resync
3028
Mathias Agopiancde87a32012-09-13 14:09:01 -07003029 // FIXME: eventthread only knows about the main display right now
3030 mEventThread->onScreenReleased();
3031 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003032
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003033 getHwComposer().setPowerMode(type, mode);
3034 mVisibleRegionsDirty = true;
3035 // from this point on, SF will stop drawing on this display
3036 } else {
3037 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003038 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003039}
3040
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3042 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003043 SurfaceFlinger& mFlinger;
3044 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003045 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003046 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003047 MessageSetPowerMode(SurfaceFlinger& flinger,
3048 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3049 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003050 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003052 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003053 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003054 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003055 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003056 ALOGW("Attempt to set power mode = %d for virtual display",
3057 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003058 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003059 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003060 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003061 return true;
3062 }
3063 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003064 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003065 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003066}
3067
3068// ---------------------------------------------------------------------------
3069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3071{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003073
Mathias Agopianbd115332013-04-18 16:41:04 -07003074 IPCThreadState* ipc = IPCThreadState::self();
3075 const int pid = ipc->getCallingPid();
3076 const int uid = ipc->getCallingUid();
3077 if ((uid != AID_SHELL) &&
3078 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003079 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003080 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003082 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003083 // (this would indicate SF is stuck, but we want to be able to
3084 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003085 status_t err = mStateLock.timedLock(s2ns(1));
3086 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003087 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003088 result.appendFormat(
3089 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3090 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003091 }
3092
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003093 bool dumpAll = true;
3094 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003095 size_t numArgs = args.size();
3096 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003097 if ((index < numArgs) &&
3098 (args[index] == String16("--list"))) {
3099 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003100 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003101 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003102 }
3103
3104 if ((index < numArgs) &&
3105 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003106 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003107 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003108 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003109 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003110
3111 if ((index < numArgs) &&
3112 (args[index] == String16("--latency-clear"))) {
3113 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003114 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003115 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003116 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003117
3118 if ((index < numArgs) &&
3119 (args[index] == String16("--dispsync"))) {
3120 index++;
3121 mPrimaryDispSync.dump(result);
3122 dumpAll = false;
3123 }
Dan Stozab90cf072015-03-05 11:05:59 -08003124
3125 if ((index < numArgs) &&
3126 (args[index] == String16("--static-screen"))) {
3127 index++;
3128 dumpStaticScreenStats(result);
3129 dumpAll = false;
3130 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003131
3132 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003133 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003134 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003135 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003136 dumpAll = false;
3137 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003139
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003140 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003141 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003142 }
3143
Mathias Agopian9795c422009-08-26 16:36:26 -07003144 if (locked) {
3145 mStateLock.unlock();
3146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 }
3148 write(fd, result.string(), result.size());
3149 return NO_ERROR;
3150}
3151
Dan Stozac7014012014-02-14 15:03:43 -08003152void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3153 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003154{
Robert Carr2047fae2016-11-28 14:09:09 -08003155 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003156 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003157 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003158}
3159
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003160void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003161 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003162{
3163 String8 name;
3164 if (index < args.size()) {
3165 name = String8(args[index]);
3166 index++;
3167 }
3168
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3170 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003171 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003172
3173 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003174 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003175 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003176 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003177 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003178 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003179 }
Robert Carr2047fae2016-11-28 14:09:09 -08003180 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003181 }
3182}
3183
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003184void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003185 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003186{
3187 String8 name;
3188 if (index < args.size()) {
3189 name = String8(args[index]);
3190 index++;
3191 }
3192
Robert Carr2047fae2016-11-28 14:09:09 -08003193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003194 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003195 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003196 }
Robert Carr2047fae2016-11-28 14:09:09 -08003197 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003198
Svetoslavd85084b2014-03-20 10:28:31 -07003199 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003200}
3201
Jamie Gennis6547ff42013-07-16 20:12:42 -07003202// This should only be called from the main thread. Otherwise it would need
3203// the lock and should use mCurrentState rather than mDrawingState.
3204void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003206 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003207 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003208
3209 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3210}
3211
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003212void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003213{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003214 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003215 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3216
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217 if (isLayerTripleBufferingDisabled())
3218 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003220}
3221
Dan Stozab90cf072015-03-05 11:05:59 -08003222void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3223{
3224 result.appendFormat("Static screen stats:\n");
3225 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3226 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3227 float percent = 100.0f *
3228 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3229 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3230 b + 1, bucketTimeSec, percent);
3231 }
3232 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3233 float percent = 100.0f *
3234 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3235 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3236 NUM_BUCKETS - 1, bucketTimeSec, percent);
3237}
3238
Dan Stozae77c7662016-05-13 11:37:28 -07003239void SurfaceFlinger::recordBufferingStats(const char* layerName,
3240 std::vector<OccupancyTracker::Segment>&& history) {
3241 Mutex::Autolock lock(mBufferingStatsMutex);
3242 auto& stats = mBufferingStats[layerName];
3243 for (const auto& segment : history) {
3244 if (!segment.usedThirdBuffer) {
3245 stats.twoBufferTime += segment.totalTime;
3246 }
3247 if (segment.occupancyAverage < 1.0f) {
3248 stats.doubleBufferedTime += segment.totalTime;
3249 } else if (segment.occupancyAverage < 2.0f) {
3250 stats.tripleBufferedTime += segment.totalTime;
3251 }
3252 ++stats.numSegments;
3253 stats.totalTime += segment.totalTime;
3254 }
3255}
3256
Brian Andersond6927fb2016-07-23 23:37:30 -07003257void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3258 result.appendFormat("Layer frame timestamps:\n");
3259
3260 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3261 const size_t count = currentLayers.size();
3262 for (size_t i=0 ; i<count ; i++) {
3263 currentLayers[i]->dumpFrameEvents(result);
3264 }
3265}
3266
Dan Stozae77c7662016-05-13 11:37:28 -07003267void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3268 result.append("Buffering stats:\n");
3269 result.append(" [Layer name] <Active time> <Two buffer> "
3270 "<Double buffered> <Triple buffered>\n");
3271 Mutex::Autolock lock(mBufferingStatsMutex);
3272 typedef std::tuple<std::string, float, float, float> BufferTuple;
3273 std::map<float, BufferTuple, std::greater<float>> sorted;
3274 for (const auto& statsPair : mBufferingStats) {
3275 const char* name = statsPair.first.c_str();
3276 const BufferingStats& stats = statsPair.second;
3277 if (stats.numSegments == 0) {
3278 continue;
3279 }
3280 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3281 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3282 stats.totalTime;
3283 float doubleBufferRatio = static_cast<float>(
3284 stats.doubleBufferedTime) / stats.totalTime;
3285 float tripleBufferRatio = static_cast<float>(
3286 stats.tripleBufferedTime) / stats.totalTime;
3287 sorted.insert({activeTime, {name, twoBufferRatio,
3288 doubleBufferRatio, tripleBufferRatio}});
3289 }
3290 for (const auto& sortedPair : sorted) {
3291 float activeTime = sortedPair.first;
3292 const BufferTuple& values = sortedPair.second;
3293 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3294 std::get<0>(values).c_str(), activeTime,
3295 std::get<1>(values), std::get<2>(values),
3296 std::get<3>(values));
3297 }
3298 result.append("\n");
3299}
3300
3301
Mathias Agopian74d211a2013-04-22 16:55:35 +02003302void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3303 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003304{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003305 bool colorize = false;
3306 if (index < args.size()
3307 && (args[index] == String16("--color"))) {
3308 colorize = true;
3309 index++;
3310 }
3311
3312 Colorizer colorizer(colorize);
3313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314 // figure out if we're stuck somewhere
3315 const nsecs_t now = systemTime();
3316 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3317 const nsecs_t inTransaction(mDebugInTransaction);
3318 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3319 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3320
3321 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003322 * Dump library configuration.
3323 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003324
3325 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003326 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003327 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003328 appendSfConfigString(result);
3329 appendUiConfigString(result);
3330 appendGuiConfigString(result);
3331 result.append("\n");
3332
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003333 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003334 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003335 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003336 result.append(SyncFeatures::getInstance().toString());
3337 result.append("\n");
3338
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3340
Andy McFadden41d67d72014-04-25 16:58:34 -07003341 colorizer.bold(result);
3342 result.append("DispSync configuration: ");
3343 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003344 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3345 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3347 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003348 result.append("\n");
3349
Dan Stozab90cf072015-03-05 11:05:59 -08003350 // Dump static screen stats
3351 result.append("\n");
3352 dumpStaticScreenStats(result);
3353 result.append("\n");
3354
Dan Stozae77c7662016-05-13 11:37:28 -07003355 dumpBufferingStats(result);
3356
Andy McFadden4803b742012-09-24 19:07:20 -07003357 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003358 * Dump the visible layer list
3359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003363 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003365 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003366
3367 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003368 * Dump Display state
3369 */
3370
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003371 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003372 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003373 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003374 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3375 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003376 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003377 }
3378
3379 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003380 * Dump SurfaceFlinger global state
3381 */
3382
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003386
Mathias Agopian888c8222012-08-04 21:10:38 -07003387 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003388 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003389
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003390 colorizer.bold(result);
3391 result.appendFormat("EGL implementation : %s\n",
3392 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3393 colorizer.reset(result);
3394 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003395 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003396
Mathias Agopian875d8e12013-06-07 15:35:48 -07003397 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003398
Mathias Agopian42977342012-08-05 00:40:46 -07003399 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3401 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003402 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403 " last eglSwapBuffers() time: %f us\n"
3404 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003405 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003406 " refresh-rate : %f fps\n"
3407 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003408 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003409 " gpu_to_cpu_unsupported : %d\n"
3410 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411 mLastSwapBufferTime/1000.0,
3412 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003413 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 1e9 / activeConfig->getVsyncPeriod(),
3415 activeConfig->getDpiX(),
3416 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003417 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421
Mathias Agopian74d211a2013-04-22 16:55:35 +02003422 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424
3425 /*
3426 * VSYNC state
3427 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003428 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003429 result.append("\n");
3430
3431 /*
3432 * HWC layer minidump
3433 */
3434 for (size_t d = 0; d < mDisplays.size(); d++) {
3435 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3436 int32_t hwcId = displayDevice->getHwcDisplayId();
3437 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3438 continue;
3439 }
3440
3441 result.appendFormat("Display %d HWC layers:\n", hwcId);
3442 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003444 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 });
Dan Stozae22aec72016-08-01 13:20:59 -07003446 result.append("\n");
3447 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448
3449 /*
3450 * Dump HWComposer state
3451 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003452 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003454 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003455 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003456 result.appendFormat(" h/w composer %s\n",
3457 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003458 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459
3460 /*
3461 * Dump gralloc state
3462 */
3463 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3464 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465}
3466
Mathias Agopian13127d82013-03-05 17:47:11 -08003467const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003468SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003469 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003470 wp<IBinder> dpy;
3471 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3472 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3473 dpy = mDisplays.keyAt(i);
3474 break;
3475 }
3476 }
3477 if (dpy == NULL) {
3478 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3479 // Just use the primary display so we have something to return
3480 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3481 }
3482 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003483}
3484
Keun young Park63f165f2012-08-31 10:53:36 -07003485bool SurfaceFlinger::startDdmConnection()
3486{
3487 void* libddmconnection_dso =
3488 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3489 if (!libddmconnection_dso) {
3490 return false;
3491 }
3492 void (*DdmConnection_start)(const char* name);
3493 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003494 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003495 if (!DdmConnection_start) {
3496 dlclose(libddmconnection_dso);
3497 return false;
3498 }
3499 (*DdmConnection_start)(getServiceName());
3500 return true;
3501}
3502
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003503status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 switch (code) {
3505 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003506 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003508 case CLEAR_ANIMATION_FRAME_STATS:
3509 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003511 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 {
3513 // codes that require permission check
3514 IPCThreadState* ipc = IPCThreadState::self();
3515 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003516 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003517 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003518 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003519 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003520 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003522 break;
3523 }
Robert Carr1db73f62016-12-21 12:58:51 -08003524 /*
3525 * Calling setTransactionState is safe, because you need to have been
3526 * granted a reference to Client* and Handle* to do anything with it.
3527 *
3528 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3529 */
3530 case SET_TRANSACTION_STATE:
3531 case CREATE_SCOPED_CONNECTION:
3532 {
3533 return OK;
3534 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003535 case CAPTURE_SCREEN:
3536 {
3537 // codes that require permission check
3538 IPCThreadState* ipc = IPCThreadState::self();
3539 const int pid = ipc->getCallingPid();
3540 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003541 if ((uid != AID_GRAPHICS) &&
3542 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003543 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003544 return PERMISSION_DENIED;
3545 }
3546 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
3548 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003549 return OK;
3550}
3551
3552status_t SurfaceFlinger::onTransact(
3553 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3554{
3555 status_t credentialCheck = CheckTransactCodeCredentials(code);
3556 if (credentialCheck != OK) {
3557 return credentialCheck;
3558 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3561 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003562 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003563 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003564 IPCThreadState* ipc = IPCThreadState::self();
3565 const int pid = ipc->getCallingPid();
3566 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003567 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003568 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569 return PERMISSION_DENIED;
3570 }
3571 int n;
3572 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003573 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003574 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 return NO_ERROR;
3576 case 1002: // SHOW_UPDATES
3577 n = data.readInt32();
3578 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003579 invalidateHwcGeometry();
3580 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003583 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003584 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003586 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 setTransactionFlags(
3588 eTransactionNeeded|
3589 eDisplayTransactionNeeded|
3590 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003591 return NO_ERROR;
3592 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003593 case 1006:{ // send empty update
3594 signalRefresh();
3595 return NO_ERROR;
3596 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003597 case 1008: // toggle use of hw composer
3598 n = data.readInt32();
3599 mDebugDisableHWC = n ? 1 : 0;
3600 invalidateHwcGeometry();
3601 repaintEverything();
3602 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003603 case 1009: // toggle use of transform hint
3604 n = data.readInt32();
3605 mDebugDisableTransformHint = n ? 1 : 0;
3606 invalidateHwcGeometry();
3607 repaintEverything();
3608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003610 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611 reply->writeInt32(0);
3612 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003613 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003614 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 return NO_ERROR;
3616 case 1013: {
3617 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003618 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3619 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003620 return NO_ERROR;
3621 }
3622 case 1014: {
3623 // daltonize
3624 n = data.readInt32();
3625 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003626 case 1:
3627 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3628 break;
3629 case 2:
3630 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3631 break;
3632 case 3:
3633 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3634 break;
3635 default:
3636 mDaltonizer.setType(ColorBlindnessType::None);
3637 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003638 }
3639 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003640 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003641 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003642 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003643 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003644 invalidateHwcGeometry();
3645 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003646 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003648 case 1015: {
3649 // apply a color matrix
3650 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003651 if (n) {
3652 // color matrix is sent as mat3 matrix followed by vec3
3653 // offset, then packed into a mat4 where the last row is
3654 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003655 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003656 for (size_t j = 0; j < 4; j++) {
3657 mColorMatrix[i][j] = data.readFloat();
3658 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003659 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003660 } else {
3661 mColorMatrix = mat4();
3662 }
3663 invalidateHwcGeometry();
3664 repaintEverything();
3665 return NO_ERROR;
3666 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003667 // This is an experimental interface
3668 // Needs to be shifted to proper binder interface when we productize
3669 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003670 n = data.readInt32();
3671 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003672 return NO_ERROR;
3673 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003674 case 1017: {
3675 n = data.readInt32();
3676 mForceFullDamage = static_cast<bool>(n);
3677 return NO_ERROR;
3678 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003679 case 1018: { // Modify Choreographer's phase offset
3680 n = data.readInt32();
3681 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3682 return NO_ERROR;
3683 }
3684 case 1019: { // Modify SurfaceFlinger's phase offset
3685 n = data.readInt32();
3686 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3687 return NO_ERROR;
3688 }
Irvel468051e2016-06-13 16:44:44 -07003689 case 1020: { // Layer updates interceptor
3690 n = data.readInt32();
3691 if (n) {
3692 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003693 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003694 }
3695 else{
3696 ALOGV("Interceptor disabled");
3697 mInterceptor.disable();
3698 }
3699 return NO_ERROR;
3700 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003701 case 1021: { // Disable HWC virtual displays
3702 n = data.readInt32();
3703 mUseHwcVirtualDisplays = !n;
3704 return NO_ERROR;
3705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 }
3707 }
3708 return err;
3709}
3710
Mathias Agopian53331da2011-08-22 21:44:41 -07003711void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003712 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003713 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003714}
3715
Mathias Agopian59119e62010-10-11 12:37:43 -07003716// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003717// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003718// ---------------------------------------------------------------------------
3719
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003720/* The code below is here to handle b/8734824
3721 *
3722 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003723 * from the surfaceflinger thread to the calling binder thread, where they
3724 * are executed. This allows the calling thread in the calling process to be
3725 * reused and not depend on having "enough" binder threads to handle the
3726 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003727 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003728class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003729 /* Parts of GraphicProducerWrapper are run on two different threads,
3730 * communicating by sending messages via Looper but also by shared member
3731 * data. Coherence maintenance is subtle and in places implicit (ugh).
3732 *
3733 * Don't rely on Looper's sendMessage/handleMessage providing
3734 * release/acquire semantics for any data not actually in the Message.
3735 * Data going from surfaceflinger to binder threads needs to be
3736 * synchronized explicitly.
3737 *
3738 * Barrier open/wait do provide release/acquire semantics. This provides
3739 * implicit synchronization for data coming back from binder to
3740 * surfaceflinger threads.
3741 */
3742
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003743 sp<IGraphicBufferProducer> impl;
3744 sp<Looper> looper;
3745 status_t result;
3746 bool exitPending;
3747 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003748 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003749 uint32_t code;
3750 Parcel const* data;
3751 Parcel* reply;
3752
3753 enum {
3754 MSG_API_CALL,
3755 MSG_EXIT
3756 };
3757
3758 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003759 * Called on surfaceflinger thread. This is called by our "fake"
3760 * BpGraphicBufferProducer. We package the data and reply Parcel and
3761 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003762 */
3763 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003764 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003765 this->code = code;
3766 this->data = &data;
3767 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003768 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003769 // if we've exited, we run the message synchronously right here.
3770 // note (JH): as far as I can tell from looking at the code, this
3771 // never actually happens. if it does, i'm not sure if it happens
3772 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003773 handleMessage(Message(MSG_API_CALL));
3774 } else {
3775 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003776 // Prevent stores to this->{code, data, reply} from being
3777 // reordered later than the construction of Message.
3778 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003779 looper->sendMessage(this, Message(MSG_API_CALL));
3780 barrier.wait();
3781 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003782 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 }
3784
3785 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003786 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 * call the real BpGraphicBufferProducer.
3788 */
3789 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003790 int what = message.what;
3791 // Prevent reads below from happening before the read from Message
3792 atomic_thread_fence(memory_order_acquire);
3793 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003794 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003796 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 exitRequested = true;
3798 }
3799 }
3800
3801public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003802 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003803 : impl(impl),
3804 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003805 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003806 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003807 exitRequested(false),
3808 code(0),
3809 data(NULL),
3810 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003811 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812
Jesse Hallb154c422014-07-13 12:47:02 -07003813 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 status_t waitForResponse() {
3815 do {
3816 looper->pollOnce(-1);
3817 } while (!exitRequested);
3818 return result;
3819 }
3820
Jesse Hallb154c422014-07-13 12:47:02 -07003821 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003823 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003825 // Ensure this->result is visible to the binder thread before it
3826 // handles the message.
3827 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 looper->sendMessage(this, Message(MSG_EXIT));
3829 }
3830};
3831
3832
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003833status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3834 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003835 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003836 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003837 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003838
3839 if (CC_UNLIKELY(display == 0))
3840 return BAD_VALUE;
3841
3842 if (CC_UNLIKELY(producer == 0))
3843 return BAD_VALUE;
3844
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003845 // if we have secure windows on this display, never allow the screen capture
3846 // unless the producer interface is local (i.e.: we can take a screenshot for
3847 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003848 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003849
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003850 // Convert to surfaceflinger's internal rotation type.
3851 Transform::orientation_flags rotationFlags;
3852 switch (rotation) {
3853 case ISurfaceComposer::eRotateNone:
3854 rotationFlags = Transform::ROT_0;
3855 break;
3856 case ISurfaceComposer::eRotate90:
3857 rotationFlags = Transform::ROT_90;
3858 break;
3859 case ISurfaceComposer::eRotate180:
3860 rotationFlags = Transform::ROT_180;
3861 break;
3862 case ISurfaceComposer::eRotate270:
3863 rotationFlags = Transform::ROT_270;
3864 break;
3865 default:
3866 rotationFlags = Transform::ROT_0;
3867 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3868 break;
3869 }
3870
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871 class MessageCaptureScreen : public MessageBase {
3872 SurfaceFlinger* flinger;
3873 sp<IBinder> display;
3874 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003875 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003876 uint32_t reqWidth, reqHeight;
3877 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003878 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003879 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003880 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003881 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003882 public:
3883 MessageCaptureScreen(SurfaceFlinger* flinger,
3884 const sp<IBinder>& display,
3885 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003886 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003887 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003888 bool useIdentityTransform,
3889 Transform::orientation_flags rotation,
3890 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003891 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003892 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003893 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003894 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003895 rotation(rotation), result(PERMISSION_DENIED),
3896 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 {
3898 }
3899 status_t getResult() const {
3900 return result;
3901 }
3902 virtual bool handler() {
3903 Mutex::Autolock _l(flinger->mStateLock);
3904 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003905 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003906 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003907 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003908 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 return true;
3910 }
3911 };
3912
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003913 // this creates a "fake" BBinder which will serve as a "fake" remote
3914 // binder to receive the marshaled calls and forward them to the
3915 // real remote (a BpGraphicBufferProducer)
3916 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3917
3918 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3919 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003920 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003921 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003922 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003923 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003924
3925 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 }
3929 return res;
3930}
3931
Mathias Agopian180f10d2013-04-10 22:55:41 -07003932
3933void SurfaceFlinger::renderScreenImplLocked(
3934 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003935 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003936 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003937 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003938{
3939 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003940 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003941
3942 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003943 const int32_t hw_w = hw->getWidth();
3944 const int32_t hw_h = hw->getHeight();
3945 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003946 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003947
Dan Stozac1879002014-05-22 15:59:05 -07003948 // if a default or invalid sourceCrop is passed in, set reasonable values
3949 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3950 !sourceCrop.isValid()) {
3951 sourceCrop.setLeftTop(Point(0, 0));
3952 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3953 }
3954
3955 // ensure that sourceCrop is inside screen
3956 if (sourceCrop.left < 0) {
3957 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3958 }
Dan Stozabe31f442014-06-11 11:20:54 -07003959 if (sourceCrop.right > hw_w) {
3960 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003961 }
3962 if (sourceCrop.top < 0) {
3963 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3964 }
Dan Stozabe31f442014-06-11 11:20:54 -07003965 if (sourceCrop.bottom > hw_h) {
3966 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003967 }
3968
Mathias Agopian180f10d2013-04-10 22:55:41 -07003969 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003970 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003971
3972 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003973 engine.setViewportAndProjection(
3974 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003975 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976
3977 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003978 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979
Robert Carr1f0a16a2016-10-24 16:27:39 -07003980 // We loop through the first level of layers without traversing,
3981 // as we need to interpret min/max layer Z in the top level Z space.
3982 for (const auto& layer : mDrawingState.layersSortedByZ) {
3983 if (layer->getLayerStack() != hw->getLayerStack()) {
3984 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003985 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003986 const Layer::State& state(layer->getDrawingState());
3987 if (state.z < minLayerZ || state.z > maxLayerZ) {
3988 continue;
3989 }
3990 layer->traverseInZOrder([&](Layer* layer) {
3991 if (!layer->isVisible()) {
3992 return;
3993 }
3994 if (filtering) layer->setFiltering(true);
3995 layer->draw(hw, useIdentityTransform);
3996 if (filtering) layer->setFiltering(false);
3997 });
3998 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003999
Mathias Agopian931bda12013-08-28 18:11:46 -07004000 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001}
4002
4003
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004004status_t SurfaceFlinger::captureScreenImplLocked(
4005 const sp<const DisplayDevice>& hw,
4006 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004007 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004008 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004009 bool useIdentityTransform, Transform::orientation_flags rotation,
4010 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004011{
4012 ATRACE_CALL();
4013
Mathias Agopian180f10d2013-04-10 22:55:41 -07004014 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004015 uint32_t hw_w = hw->getWidth();
4016 uint32_t hw_h = hw->getHeight();
4017
4018 if (rotation & Transform::ROT_90) {
4019 std::swap(hw_w, hw_h);
4020 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4023 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4024 reqWidth, reqHeight, hw_w, hw_h);
4025 return BAD_VALUE;
4026 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004027
Mathias Agopian180f10d2013-04-10 22:55:41 -07004028 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4029 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4030
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004031 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004032 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004033 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004034 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4035 (state.z < minLayerZ || state.z > maxLayerZ)) {
4036 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004037 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004038 layer->traverseInZOrder([&](Layer *layer) {
4039 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4040 layer->isSecure());
4041 });
4042 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004043
4044 if (!isLocalScreenshot && secureLayerIsVisible) {
4045 ALOGW("FB is protected: PERMISSION_DENIED");
4046 return PERMISSION_DENIED;
4047 }
4048
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004049 // create a surface (because we're a producer, and we need to
4050 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004051 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004052
4053 // Put the screenshot Surface into async mode so that
4054 // Layer::headFenceHasSignaled will always return true and we'll latch the
4055 // first buffer regardless of whether or not its acquire fence has
4056 // signaled. This is needed to avoid a race condition in the rotation
4057 // animation. See b/30209608
4058 sur->setAsyncMode(true);
4059
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004060 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004061
Michael Lentine5a16a622015-05-21 13:48:24 -07004062 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4063 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004064 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4065 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004066
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004067 int err = 0;
4068 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004069 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4071 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004072
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004073 if (err == NO_ERROR) {
4074 ANativeWindowBuffer* buffer;
4075 /* TODO: Once we have the sync framework everywhere this can use
4076 * server-side waits on the fence that dequeueBuffer returns.
4077 */
4078 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4079 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004080 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 // create an EGLImage from the buffer so we can later
4082 // turn it into a texture
4083 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4084 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4085 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004086 // this binds the given EGLImage as a framebuffer for the
4087 // duration of this scope.
4088 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4089 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004090 // this will in fact render into our dequeued buffer
4091 // via an FBO, which means we didn't have to create
4092 // an EGLSurface and therefore we're not
4093 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004094 renderScreenImplLocked(
4095 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4096 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004097
Riley Andrews86639902014-08-15 12:27:24 -07004098 // Attempt to create a sync khr object that can produce a sync point. If that
4099 // isn't available, create a non-dupable sync object in the fallback path and
4100 // wait on it directly.
4101 EGLSyncKHR sync;
4102 if (!DEBUG_SCREENSHOTS) {
4103 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004104 // native fence fd will not be populated until flush() is done.
4105 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004106 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004107 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004108 }
Riley Andrews86639902014-08-15 12:27:24 -07004109 if (sync != EGL_NO_SYNC_KHR) {
4110 // get the sync fd
4111 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4112 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4113 ALOGW("captureScreen: failed to dup sync khr object");
4114 syncFd = -1;
4115 }
4116 eglDestroySyncKHR(mEGLDisplay, sync);
4117 } else {
4118 // fallback path
4119 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4120 if (sync != EGL_NO_SYNC_KHR) {
4121 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4122 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4123 EGLint eglErr = eglGetError();
4124 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4125 ALOGW("captureScreen: fence wait timed out");
4126 } else {
4127 ALOGW_IF(eglErr != EGL_SUCCESS,
4128 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4129 }
4130 eglDestroySyncKHR(mEGLDisplay, sync);
4131 } else {
4132 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4133 }
4134 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004135 if (DEBUG_SCREENSHOTS) {
4136 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4137 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4138 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4139 hw, minLayerZ, maxLayerZ);
4140 delete [] pixels;
4141 }
4142
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004143 } else {
4144 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4145 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004146 window->cancelBuffer(window, buffer, syncFd);
4147 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004148 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004149 // destroy our image
4150 eglDestroyImageKHR(mEGLDisplay, image);
4151 } else {
4152 result = BAD_VALUE;
4153 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004154 if (buffer) {
4155 // queueBuffer takes ownership of syncFd
4156 result = window->queueBuffer(window, buffer, syncFd);
4157 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004158 }
4159 } else {
4160 result = BAD_VALUE;
4161 }
4162 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4163 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004164
Mathias Agopian74c40c02010-09-29 13:02:36 -07004165 return result;
4166}
4167
Mathias Agopiand5556842013-09-19 17:08:37 -07004168void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004169 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004170 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004171 for (size_t y=0 ; y<h ; y++) {
4172 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4173 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004174 if (p[x] != 0xFF000000) return;
4175 }
4176 }
4177 ALOGE("*** we just took a black screenshot ***\n"
4178 "requested minz=%d, maxz=%d, layerStack=%d",
4179 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004180
Robert Carr2047fae2016-11-28 14:09:09 -08004181 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004182 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004183 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004184 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4185 state.z <= maxLayerZ) {
4186 layer->traverseInZOrder([&](Layer* layer) {
4187 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4188 layer->isVisible() ? '+' : '-',
4189 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004190 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 i++;
4192 });
4193 }
4194 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 }
4196}
4197
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004198// ---------------------------------------------------------------------------
4199
Robert Carr2047fae2016-11-28 14:09:09 -08004200void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4201 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004202}
4203
Robert Carr2047fae2016-11-28 14:09:09 -08004204void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4205 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004206}
4207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004209
4210
4211#if defined(__gl_h_)
4212#error "don't include gl/gl.h in this file"
4213#endif
4214
4215#if defined(__gl2_h_)
4216#error "don't include gl2/gl2.h in this file"
4217#endif