blob: bff8f5fd3a80b6846fdcab36f5ced874641b0a3e [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 Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
40
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Mathias Agopian921e6ac2012-07-23 23:11:29 -070044#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080049#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080078#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Mathias Agopianca088332013-03-28 17:44:13 -0700100EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107// This is the phase offset in nanoseconds of the software vsync event
108// relative to the vsync event reported by HWComposer. The software vsync
109// event is when SurfaceFlinger and Choreographer-based applications run each
110// frame.
111//
112// This phase offset allows adjustment of the minimum latency from application
113// wake-up (by Choregographer) time to the time at which the resulting window
114// image is displayed. This value may be either positive (after the HW vsync)
115// or negative (before the HW vsync). Setting it to 0 will result in a
116// minimum latency of two vsync periods because the app and SurfaceFlinger
117// will run just after the HW vsync. Setting it to a positive number will
118// result in the minimum latency being:
119//
120// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
121//
122// Note that reducing this latency makes it more likely for the applications
123// to not have their window content image ready in time. When this happens
124// the latency will end up being an additional vsync period, and animations
125// will hiccup. Therefore, this latency should be tuned somewhat
126// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900127static int64_t vsyncPhaseOffsetNs = getInt64<
128 ISurfaceFlingerConfigs,
129 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800132static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700149 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700150 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800151 mHwc(nullptr),
152 mRealHwc(nullptr),
153 mVrHwc(nullptr),
154 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800158 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800159 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700161 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700162 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700163 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700164 mDebugInSwapBuffers(0),
165 mLastSwapBufferTime(0),
166 mDebugInTransaction(0),
167 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700168 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700169 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700170 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000171 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700172 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700173 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800174 mHasColorMatrix(false),
175 mHasPoweredOff(false),
176 mFrameBuckets(),
177 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700178 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800179 mNumLayers(0)
180#ifdef USE_HWC2
181 ,mEnterVrMode(false)
182#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183{
Steve Blocka19954a2012-01-04 20:05:49 +0000184 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185
186 // debugging stuff...
187 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700188
Mathias Agopianb4b17302013-03-20 18:36:41 -0700189 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700190 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 property_get("debug.sf.showupdates", value, "0");
193 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700195 property_get("debug.sf.ddms", value, "0");
196 mDebugDDMS = atoi(value);
197 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700198 if (!startDdmConnection()) {
199 // start failed, and DDMS debugging not enabled
200 mDebugDDMS = 0;
201 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700203 ALOGI_IF(mDebugRegion, "showupdates enabled");
204 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700205
206 property_get("debug.sf.disable_backpressure", value, "0");
207 mPropagateBackpressure = !atoi(value);
208 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700209
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800210 property_get("debug.sf.enable_hwc_vds", value, "0");
211 mUseHwcVirtualDisplays = atoi(value);
212 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800213
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800214 property_get("ro.sf.disable_triple_buffer", value, "1");
215 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800216 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217}
218
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219void SurfaceFlinger::onFirstRef()
220{
221 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800222}
223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224SurfaceFlinger::~SurfaceFlinger()
225{
Mathias Agopiana4912602012-07-12 14:25:33 -0700226 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
227 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
228 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800229
230 if (mVrStateCallbacks.get()) {
231 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
232 defaultServiceManager()->checkService(String16("vrmanager")));
233 if (vrManagerService.get()) {
234 vrManagerService->unregisterListener(mVrStateCallbacks);
235 }
236 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237}
238
Dan Stozac7014012014-02-14 15:03:43 -0800239void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800240{
241 // the window manager died on us. prepare its eulogy.
242
Andy McFadden13a082e2012-08-24 10:16:42 -0700243 // restore initial conditions (default device unblank, etc)
244 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245
246 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700247 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248}
249
Robert Carr1db73f62016-12-21 12:58:51 -0800250static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700251 status_t err = client->initCheck();
252 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800253 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 }
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return nullptr;
256}
257
258sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
259 return initClient(new Client(this));
260}
261
262sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
263 const sp<IGraphicBufferProducer>& gbp) {
264 if (authenticateSurfaceTexture(gbp) == false) {
265 return nullptr;
266 }
267 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
268 if (layer == nullptr) {
269 return nullptr;
270 }
271
272 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273}
274
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700275sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
276 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277{
278 class DisplayToken : public BBinder {
279 sp<SurfaceFlinger> flinger;
280 virtual ~DisplayToken() {
281 // no more references, this display must be terminated
282 Mutex::Autolock _l(flinger->mStateLock);
283 flinger->mCurrentState.displays.removeItem(this);
284 flinger->setTransactionFlags(eDisplayTransactionNeeded);
285 }
286 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700287 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288 : flinger(flinger) {
289 }
290 };
291
292 sp<BBinder> token = new DisplayToken(this);
293
294 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700295 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700296 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700298 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 return token;
300}
301
Jesse Hall6c913be2013-08-08 12:15:49 -0700302void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
303 Mutex::Autolock _l(mStateLock);
304
305 ssize_t idx = mCurrentState.displays.indexOfKey(display);
306 if (idx < 0) {
307 ALOGW("destroyDisplay: invalid display token");
308 return;
309 }
310
311 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
312 if (!info.isVirtualDisplay()) {
313 ALOGE("destroyDisplay called for non-virtual display");
314 return;
315 }
Irvelffc9efc2016-07-27 15:16:37 -0700316 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700317 mCurrentState.displays.removeItemsAt(idx);
318 setTransactionFlags(eDisplayTransactionNeeded);
319}
320
Jesse Hall692c7232012-11-08 15:41:56 -0800321void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800322 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800323 ALOGW_IF(mBuiltinDisplays[type],
324 "Overwriting display token for display type %d", type);
325 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800326 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700327 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800328 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700329 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800330}
331
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700333 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
335 return NULL;
336 }
Jesse Hall692c7232012-11-08 15:41:56 -0800337 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338}
339
Jamie Gennis9a78c902011-01-12 18:30:40 -0800340sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
341{
342 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
343 return gba;
344}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346void SurfaceFlinger::bootFinished()
347{
Wei Wangb254fa32017-01-31 17:43:23 -0800348 if (mStartBootAnimThread->join() != NO_ERROR) {
349 ALOGE("Join StartBootAnimThread failed!");
350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 const nsecs_t now = systemTime();
352 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000353 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700354 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700355
356 // wait patiently for the window manager death
357 const String16 name("window");
358 sp<IBinder> window(defaultServiceManager()->getService(name));
359 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700360 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700361 }
362
363 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 // formerly we would just kill the process, but we now ask it to exit so it
365 // can choose where to stop the animation.
366 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700367
368 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
369 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
370 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800371
372 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
373 defaultServiceManager()->checkService(String16("vrmanager")));
374 if (vrManagerService.get()) {
375 mVrStateCallbacks = new VrStateCallbacks(*this);
376 vrManagerService->registerListener(mVrStateCallbacks);
377 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800573 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800574 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800575 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
577
Jesse Hall692c7232012-11-08 15:41:56 -0800578 Mutex::Autolock _l(mStateLock);
579
Mathias Agopian875d8e12013-06-07 15:35:48 -0700580 // retrieve the EGL context that was selected/created
581 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700582
Mathias Agopianda27af92012-09-13 18:17:13 -0700583 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
584 "couldn't create EGLContext");
585
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 // make the GLContext current so that we can create textures when creating
587 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700588 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
589
Jamie Gennisd1700752013-10-14 12:22:52 -0700590 mEventControlThread = new EventControlThread(this);
591 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
592
Mathias Agopian92a979a2012-08-02 18:32:23 -0700593 // initialize our drawing state
594 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700595
Andy McFadden13a082e2012-08-24 10:16:42 -0700596 // set initial conditions (e.g. unblank default device)
597 initializeDisplays();
598
Dan Stoza4e637772016-07-28 13:31:51 -0700599 mRenderEngine->primeCache();
600
Wei Wangb254fa32017-01-31 17:43:23 -0800601 mStartBootAnimThread = new StartBootAnimThread();
602 if (mStartBootAnimThread->Start() != NO_ERROR) {
603 ALOGE("Run StartBootAnimThread failed!");
604 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800605
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700607}
608
Mathias Agopiana67e4182012-06-19 17:26:12 -0700609void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800610 // Start boot animation service by setting a property mailbox
611 // if property setting thread is already running, Start() will be just a NOP
612 mStartBootAnimThread->Start();
613 // Wait until property was set
614 if (mStartBootAnimThread->join() != NO_ERROR) {
615 ALOGE("Join StartBootAnimThread failed!");
616 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700617}
618
Mathias Agopian875d8e12013-06-07 15:35:48 -0700619size_t SurfaceFlinger::getMaxTextureSize() const {
620 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700621}
622
Mathias Agopian875d8e12013-06-07 15:35:48 -0700623size_t SurfaceFlinger::getMaxViewportDims() const {
624 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700625}
626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800628
Jamie Gennis582270d2011-08-17 18:19:00 -0700629bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800630 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800631 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800632 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700633 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800634}
635
Brian Anderson069b3652016-07-22 10:32:47 -0700636status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700637 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700638 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700639 FrameEvent::REQUESTED_PRESENT,
640 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700641 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700642 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700643 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700644 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700645 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700647 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700648 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700649 };
650 return NO_ERROR;
651}
652
Dan Stoza7f7da322014-05-02 15:26:25 -0700653status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
654 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700655 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700656 return BAD_VALUE;
657 }
658
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500659 if (!display.get())
660 return NAME_NOT_FOUND;
661
Jesse Hall692c7232012-11-08 15:41:56 -0800662 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700663 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800664 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700665 type = i;
666 break;
667 }
668 }
669
670 if (type < 0) {
671 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700672 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700673
Mathias Agopian8b736f12012-08-13 17:54:26 -0700674 // TODO: Not sure if display density should handled by SF any longer
675 class Density {
676 static int getDensityFromProperty(char const* propName) {
677 char property[PROPERTY_VALUE_MAX];
678 int density = 0;
679 if (property_get(propName, property, NULL) > 0) {
680 density = atoi(property);
681 }
682 return density;
683 }
684 public:
685 static int getEmuDensity() {
686 return getDensityFromProperty("qemu.sf.lcd_density"); }
687 static int getBuildDensity() {
688 return getDensityFromProperty("ro.sf.lcd_density"); }
689 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700690
Dan Stoza7f7da322014-05-02 15:26:25 -0700691 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700694 DisplayInfo info = DisplayInfo();
695
Dan Stoza9e56aa02015-11-02 13:00:03 -0800696 float xdpi = hwConfig->getDpiX();
697 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700698
699 if (type == DisplayDevice::DISPLAY_PRIMARY) {
700 // The density of the device is provided by a build property
701 float density = Density::getBuildDensity() / 160.0f;
702 if (density == 0) {
703 // the build doesn't provide a density -- this is wrong!
704 // use xdpi instead
705 ALOGE("ro.sf.lcd_density must be defined as a build property");
706 density = xdpi / 160.0f;
707 }
708 if (Density::getEmuDensity()) {
709 // if "qemu.sf.lcd_density" is specified, it overrides everything
710 xdpi = ydpi = density = Density::getEmuDensity();
711 density /= 160.0f;
712 }
713 info.density = density;
714
715 // TODO: this needs to go away (currently needed only by webkit)
716 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
717 info.orientation = hw->getOrientation();
718 } else {
719 // TODO: where should this value come from?
720 static const int TV_DENSITY = 213;
721 info.density = TV_DENSITY / 160.0f;
722 info.orientation = 0;
723 }
724
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725 info.w = hwConfig->getWidth();
726 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700727 info.xdpi = xdpi;
728 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900730 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731
Andy McFadden91b2ca82014-06-13 14:04:23 -0700732 // This is how far in advance a buffer must be queued for
733 // presentation at a given time. If you want a buffer to appear
734 // on the screen at time N, you must submit the buffer before
735 // (N - presentationDeadline).
736 //
737 // Normally it's one full refresh period (to give SF a chance to
738 // latch the buffer), but this can be reduced by configuring a
739 // DispSync offset. Any additional delays introduced by the hardware
740 // composer or panel must be accounted for here.
741 //
742 // We add an additional 1ms to allow for processing time and
743 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 info.presentationDeadline = hwConfig->getVsyncPeriod() -
745 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700746
747 // All non-virtual displays are currently considered secure.
748 info.secure = true;
749
Michael Wright28f24d02016-07-12 13:30:53 -0700750 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 }
752
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 return NO_ERROR;
754}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700755
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800756status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700757 DisplayStatInfo* stats) {
758 if (stats == NULL) {
759 return BAD_VALUE;
760 }
761
762 // FIXME for now we always return stats for the primary display
763 memset(stats, 0, sizeof(*stats));
764 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
765 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
766 return NO_ERROR;
767}
768
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700769int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800770 if (display == NULL) {
771 ALOGE("%s : display is NULL", __func__);
772 return BAD_VALUE;
773 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700774 sp<DisplayDevice> device(getDisplayDevice(display));
775 if (device != NULL) {
776 return device->getActiveConfig();
777 }
778 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700779}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700780
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700781void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
782 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
783 this);
784 int32_t type = hw->getDisplayType();
785 int currentMode = hw->getActiveConfig();
786
787 if (mode == currentMode) {
788 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
789 return;
790 }
791
792 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
793 ALOGW("Trying to set config for virtual display");
794 return;
795 }
796
797 hw->setActiveConfig(mode);
798 getHwComposer().setActiveConfig(type, mode);
799}
800
801status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
802 class MessageSetActiveConfig: public MessageBase {
803 SurfaceFlinger& mFlinger;
804 sp<IBinder> mDisplay;
805 int mMode;
806 public:
807 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
808 int mode) :
809 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
810 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700811 Vector<DisplayInfo> configs;
812 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700813 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700814 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700815 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700816 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700817 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700818 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
819 if (hw == NULL) {
820 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700821 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700822 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
823 ALOGW("Attempt to set active config = %d for virtual display",
824 mMode);
825 } else {
826 mFlinger.setActiveConfigInternal(hw, mMode);
827 }
828 return true;
829 }
830 };
831 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
832 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700833 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700834}
Michael Wright28f24d02016-07-12 13:30:53 -0700835status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
836 Vector<android_color_mode_t>* outColorModes) {
837 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
838 return BAD_VALUE;
839 }
840
841 if (!display.get()) {
842 return NAME_NOT_FOUND;
843 }
844
845 int32_t type = NAME_NOT_FOUND;
846 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
847 if (display == mBuiltinDisplays[i]) {
848 type = i;
849 break;
850 }
851 }
852
853 if (type < 0) {
854 return type;
855 }
856
857 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
858 outColorModes->clear();
859 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
860
861 return NO_ERROR;
862}
863
864android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
865 sp<DisplayDevice> device(getDisplayDevice(display));
866 if (device != nullptr) {
867 return device->getActiveColorMode();
868 }
869 return static_cast<android_color_mode_t>(BAD_VALUE);
870}
871
872void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
873 android_color_mode_t mode) {
874 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
875 this);
876 int32_t type = hw->getDisplayType();
877 android_color_mode_t currentMode = hw->getActiveColorMode();
878
879 if (mode == currentMode) {
880 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
881 return;
882 }
883
884 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
885 ALOGW("Trying to set config for virtual display");
886 return;
887 }
888
889 hw->setActiveColorMode(mode);
890 getHwComposer().setActiveColorMode(type, mode);
891}
892
893
894status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
895 android_color_mode_t colorMode) {
896 class MessageSetActiveColorMode: public MessageBase {
897 SurfaceFlinger& mFlinger;
898 sp<IBinder> mDisplay;
899 android_color_mode_t mMode;
900 public:
901 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
902 android_color_mode_t mode) :
903 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
904 virtual bool handler() {
905 Vector<android_color_mode_t> modes;
906 mFlinger.getDisplayColorModes(mDisplay, &modes);
907 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
908 if (mMode < 0 || !exists) {
909 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
910 mDisplay.get());
911 return true;
912 }
913 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
914 if (hw == nullptr) {
915 ALOGE("Attempt to set active color mode = %d for null display %p",
916 mMode, mDisplay.get());
917 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
918 ALOGW("Attempt to set active color mode= %d for virtual display",
919 mMode);
920 } else {
921 mFlinger.setActiveColorModeInternal(hw, mMode);
922 }
923 return true;
924 }
925 };
926 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
927 postMessageSync(msg);
928 return NO_ERROR;
929}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700930
Svetoslavd85084b2014-03-20 10:28:31 -0700931status_t SurfaceFlinger::clearAnimationFrameStats() {
932 Mutex::Autolock _l(mStateLock);
933 mAnimFrameTracker.clearStats();
934 return NO_ERROR;
935}
936
937status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
938 Mutex::Autolock _l(mStateLock);
939 mAnimFrameTracker.getStats(outStats);
940 return NO_ERROR;
941}
942
Dan Stozac4f471e2016-03-24 09:31:08 -0700943status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
944 HdrCapabilities* outCapabilities) const {
945 Mutex::Autolock _l(mStateLock);
946
947 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
948 if (displayDevice == nullptr) {
949 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
950 return BAD_VALUE;
951 }
952
953 std::unique_ptr<HdrCapabilities> capabilities =
954 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
955 if (capabilities) {
956 std::swap(*outCapabilities, *capabilities);
957 } else {
958 return BAD_VALUE;
959 }
960
961 return NO_ERROR;
962}
963
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700964status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
965 if (enable == mInjectVSyncs) {
966 return NO_ERROR;
967 }
968
969 if (enable) {
970 mInjectVSyncs = enable;
971 ALOGV("VSync Injections enabled");
972 if (mVSyncInjector.get() == nullptr) {
973 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700974 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700975 }
976 mEventQueue.setEventThread(mInjectorEventThread);
977 } else {
978 mInjectVSyncs = enable;
979 ALOGV("VSync Injections disabled");
980 mEventQueue.setEventThread(mSFEventThread);
981 mVSyncInjector.clear();
982 }
983 return NO_ERROR;
984}
985
986status_t SurfaceFlinger::injectVSync(nsecs_t when) {
987 if (!mInjectVSyncs) {
988 ALOGE("VSync Injections not enabled");
989 return BAD_VALUE;
990 }
991 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
992 ALOGV("Injecting VSync inside SurfaceFlinger");
993 mVSyncInjector->onInjectSyncEvent(when);
994 }
995 return NO_ERROR;
996}
997
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800998// ----------------------------------------------------------------------------
999
1000sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001001 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001002}
1003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001004// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001005
1006void SurfaceFlinger::waitForEvent() {
1007 mEventQueue.waitMessage();
1008}
1009
1010void SurfaceFlinger::signalTransaction() {
1011 mEventQueue.invalidate();
1012}
1013
1014void SurfaceFlinger::signalLayerUpdate() {
1015 mEventQueue.invalidate();
1016}
1017
1018void SurfaceFlinger::signalRefresh() {
1019 mEventQueue.refresh();
1020}
1021
1022status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001023 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001024 return mEventQueue.postMessage(msg, reltime);
1025}
1026
1027status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001028 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001029 status_t res = mEventQueue.postMessage(msg, reltime);
1030 if (res == NO_ERROR) {
1031 msg->wait();
1032 }
1033 return res;
1034}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001036void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001037 do {
1038 waitForEvent();
1039 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040}
1041
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001042void SurfaceFlinger::enableHardwareVsync() {
1043 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001044 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001045 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001046 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1047 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001048 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001049 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050}
1051
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 Mutex::Autolock _l(mHWVsyncLock);
1054
Jesse Hall948fe0c2013-10-14 12:56:09 -07001055 if (makeAvailable) {
1056 mHWVsyncAvailable = true;
1057 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001058 // Hardware vsync is not currently available, so abort the resync
1059 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060 return;
1061 }
1062
Dan Stoza9e56aa02015-11-02 13:00:03 -08001063 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1064 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065
1066 mPrimaryDispSync.reset();
1067 mPrimaryDispSync.setPeriod(period);
1068
1069 if (!mPrimaryHWVsyncEnabled) {
1070 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001071 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1072 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 mPrimaryHWVsyncEnabled = true;
1074 }
1075}
1076
Jesse Hall948fe0c2013-10-14 12:56:09 -07001077void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078 Mutex::Autolock _l(mHWVsyncLock);
1079 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001080 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1081 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 mPrimaryDispSync.endResync();
1083 mPrimaryHWVsyncEnabled = false;
1084 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001085 if (makeUnavailable) {
1086 mHWVsyncAvailable = false;
1087 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088}
1089
Tim Murray4a4e4a22016-04-19 16:29:23 +00001090void SurfaceFlinger::resyncWithRateLimit() {
1091 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1092 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001093 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001094 }
1095}
1096
Steven Thomas3cfac282017-02-06 12:29:30 -08001097void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1098 nsecs_t timestamp) {
1099 Mutex::Autolock lock(mStateLock);
1100 // Ignore any vsyncs from the non-active hardware composer.
1101 if (composer != mHwc) {
1102 return;
1103 }
1104
Jamie Gennisd1700752013-10-14 12:22:52 -07001105 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 { // Scope for the lock
1108 Mutex::Autolock _l(mHWVsyncLock);
1109 if (type == 0 && mPrimaryHWVsyncEnabled) {
1110 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001112 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001113
1114 if (needsHwVsync) {
1115 enableHardwareVsync();
1116 } else {
1117 disableHardwareVsync(false);
1118 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001119}
1120
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001121void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1122 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1123 *compositorTiming = mCompositorTiming;
1124}
1125
Dan Stoza9e56aa02015-11-02 13:00:03 -08001126void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1127 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1128 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1129 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001130
Dan Stoza9e56aa02015-11-02 13:00:03 -08001131 // All non-virtual displays are currently considered secure.
1132 bool isSecure = true;
1133
1134 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001135
1136 // When we're using the vr composer, the assumption is that we've
1137 // already created the IBinder object for the primary display.
1138 if (!mHwc->isUsingVrComposer()) {
1139 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1140 }
1141
Dan Stoza9e56aa02015-11-02 13:00:03 -08001142 wp<IBinder> token = mBuiltinDisplays[type];
1143
1144 sp<IGraphicBufferProducer> producer;
1145 sp<IGraphicBufferConsumer> consumer;
1146 BufferQueue::createBufferQueue(&producer, &consumer,
1147 new GraphicBufferAlloc());
1148
1149 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1150 DisplayDevice::DISPLAY_PRIMARY, consumer);
1151 sp<DisplayDevice> hw = new DisplayDevice(this,
1152 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1153 producer, mRenderEngine->getEGLConfig());
1154 mDisplays.add(token, hw);
1155 } else {
1156 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001157 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001158 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001160 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001161 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1162 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001163 }
1164 setTransactionFlags(eDisplayTransactionNeeded);
1165
Andy McFadden9e9689c2012-10-10 18:17:51 -07001166 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001167 }
Mathias Agopian86303202012-07-24 22:46:10 -07001168}
1169
Steven Thomas3cfac282017-02-06 12:29:30 -08001170void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1171 Mutex::Autolock lock(mStateLock);
1172 if (composer == mHwc) {
1173 repaintEverything();
1174 } else {
1175 // This isn't from our current hardware composer. If it's a callback
1176 // from the real composer, forward the refresh request to vr
1177 // flinger. Otherwise ignore it.
1178 if (!composer->isUsingVrComposer()) {
1179 mVrFlinger->OnHardwareComposerRefresh();
1180 }
1181 }
1182}
1183
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 getHwComposer().setVsyncEnabled(disp,
1187 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001188}
1189
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001190void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1191 for (size_t i = 0; i < layers.size(); ++i) {
1192 layers[i]->clearHwcLayers();
1193 }
1194}
1195
1196void SurfaceFlinger::resetHwc() {
1197 disableHardwareVsync(true);
1198 clearHwcLayers(mDrawingState.layersSortedByZ);
1199 clearHwcLayers(mCurrentState.layersSortedByZ);
1200 // Clear the drawing state so that the logic inside of
1201 // handleTransactionLocked will fire. It will determine the delta between
1202 // mCurrentState and mDrawingState and re-apply all changes when we make the
1203 // transition.
1204 mDrawingState.displays.clear();
1205 mDisplays.clear();
1206}
1207
1208void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001209 bool enteringVrMode = mEnterVrMode;
1210 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1211 return;
1212 }
1213 if (enteringVrMode && !mVrHwc) {
1214 // Construct new HWComposer without holding any locks.
1215 mVrHwc = new HWComposer(true);
1216 ALOGV("Vr HWC created");
1217 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001218 {
1219 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001220
1221 if (enteringVrMode) {
1222 // Start vrflinger thread, if it hasn't been started already.
1223 if (!mVrFlinger) {
1224 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1225 int err = mVrFlinger->Run(mHwc->getComposer());
1226 if (err != NO_ERROR) {
1227 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1228 mVrFlinger.reset();
1229 mEnterVrMode = false;
1230 return;
1231 }
1232 }
1233
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001234 resetHwc();
1235
1236 mHwc = mVrHwc;
1237 mVrFlinger->EnterVrMode();
1238 } else {
1239 mVrFlinger->ExitVrMode();
1240
1241 resetHwc();
1242
1243 mHwc = mRealHwc;
1244 enableHardwareVsync();
1245 }
1246
1247 mVisibleRegionsDirty = true;
1248 invalidateHwcGeometry();
1249 android_atomic_or(1, &mRepaintEverything);
1250 setTransactionFlags(eDisplayTransactionNeeded);
1251 }
1252 if (mVrHwc) {
1253 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1254 }
1255}
1256
Mathias Agopian4fec8732012-06-29 14:12:52 -07001257void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001258 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 case MessageQueue::INVALIDATE: {
Corey Tabakace2c1982017-02-15 17:07:20 -08001261 // TODO(eieio): Disabled until SELinux issues are resolved.
1262 //updateVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001263
Dan Stoza50182882016-07-08 12:02:20 -07001264 bool frameMissed = !mHadClientComposition &&
1265 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001266 (mPreviousPresentFence->getSignalTime() ==
1267 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001268 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001269 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001270 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001271 signalLayerUpdate();
1272 break;
1273 }
1274
Dan Stoza6b9454d2014-11-07 16:00:59 -08001275 bool refreshNeeded = handleMessageTransaction();
1276 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001277 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001278 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001279 // Signal a refresh if a transaction modified the window state,
1280 // a new buffer was latched, or if HWC has requested a full
1281 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282 signalRefresh();
1283 }
1284 break;
1285 }
1286 case MessageQueue::REFRESH: {
1287 handleMessageRefresh();
1288 break;
1289 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001290 }
1291}
1292
Dan Stoza6b9454d2014-11-07 16:00:59 -08001293bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001294 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001295 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001296 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001297 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001298 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001300}
1301
Dan Stoza6b9454d2014-11-07 16:00:59 -08001302bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001303 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001304 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001305}
1306
1307void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001308 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001309
Pablo Ceballos40845df2016-01-25 17:41:15 -08001310 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001311
Brian Andersond6927fb2016-07-23 23:37:30 -07001312 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001313 rebuildLayerStacks();
1314 setUpHWComposer();
1315 doDebugFlashRegions();
1316 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001317 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001318
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001319 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001320
1321 mHadClientComposition = false;
1322 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1323 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1324 mHadClientComposition = mHadClientComposition ||
1325 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1326 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001327
Dan Stoza9e56aa02015-11-02 13:00:03 -08001328 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001329}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001330
Mathias Agopiancd60f992012-08-16 16:28:27 -07001331void SurfaceFlinger::doDebugFlashRegions()
1332{
1333 // is debugging enabled
1334 if (CC_LIKELY(!mDebugRegion))
1335 return;
1336
1337 const bool repaintEverything = mRepaintEverything;
1338 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1339 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001340 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001341 // transform the dirty region into this screen's coordinate space
1342 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1343 if (!dirtyRegion.isEmpty()) {
1344 // redraw the whole screen
1345 doComposeSurfaces(hw, Region(hw->bounds()));
1346
1347 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001348 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001349 RenderEngine& engine(getRenderEngine());
1350 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1351
Mathias Agopianda27af92012-09-13 18:17:13 -07001352 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001353 }
1354 }
1355 }
1356
1357 postFramebuffer();
1358
1359 if (mDebugRegion > 1) {
1360 usleep(mDebugRegion * 1000);
1361 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001362
Dan Stoza9e56aa02015-11-02 13:00:03 -08001363 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001364 auto& displayDevice = mDisplays[displayId];
1365 if (!displayDevice->isDisplayOn()) {
1366 continue;
1367 }
1368
1369 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1371 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001372 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373}
1374
Brian Andersond6927fb2016-07-23 23:37:30 -07001375void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 ATRACE_CALL();
1378 ALOGV("preComposition");
1379
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001381 mDrawingState.traverseInZOrder([&](Layer* layer) {
1382 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383 needExtraInvalidate = true;
1384 }
Robert Carr2047fae2016-11-28 14:09:09 -08001385 });
1386
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387 if (needExtraInvalidate) {
1388 signalLayerUpdate();
1389 }
1390}
1391
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392void SurfaceFlinger::updateCompositorTiming(
1393 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1394 std::shared_ptr<FenceTime>& presentFenceTime) {
1395 // Update queue of past composite+present times and determine the
1396 // most recently known composite to present latency.
1397 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1398 nsecs_t compositeToPresentLatency = -1;
1399 while (!mCompositePresentTimes.empty()) {
1400 CompositePresentTime& cpt = mCompositePresentTimes.front();
1401 // Cached values should have been updated before calling this method,
1402 // which helps avoid duplicate syscalls.
1403 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1404 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1405 break;
1406 }
1407 compositeToPresentLatency = displayTime - cpt.composite;
1408 mCompositePresentTimes.pop();
1409 }
1410
1411 // Don't let mCompositePresentTimes grow unbounded, just in case.
1412 while (mCompositePresentTimes.size() > 16) {
1413 mCompositePresentTimes.pop();
1414 }
1415
1416 // Integer division and modulo round toward 0 not -inf, so we need to
1417 // treat negative and positive offsets differently.
1418 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1419 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1420 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1421
1422 // Snap the latency to a value that removes scheduling jitter from the
1423 // composition and present times, which often have >1ms of jitter.
1424 // Reducing jitter is important if an app attempts to extrapolate
1425 // something (such as user input) to an accurate diasplay time.
1426 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1427 // with (presentLatency % interval).
1428 nsecs_t snappedCompositeToPresentLatency = -1;
1429 if (compositeToPresentLatency >= 0) {
1430 nsecs_t bias = vsyncInterval / 2;
1431 int64_t extraVsyncs =
1432 (compositeToPresentLatency - idealLatency + bias) /
1433 vsyncInterval;
1434 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1435 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1436 }
1437
1438 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1439 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1440 mCompositorTiming.interval = vsyncInterval;
1441 if (snappedCompositeToPresentLatency >= 0) {
1442 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1443 }
1444}
1445
1446void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001448 ATRACE_CALL();
1449 ALOGV("postComposition");
1450
Brian Anderson3546a3f2016-07-14 11:51:14 -07001451 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001452 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001453 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001454 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001455 }
1456
Brian Andersond6927fb2016-07-23 23:37:30 -07001457 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001458
1459 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1460 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1461 glCompositionDoneFenceTime =
1462 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1463 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1464 } else {
1465 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1466 }
1467 mGlCompositionDoneTimeline.updateSignalTimes();
1468
1469 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1470 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1471 mDisplayTimeline.push(displayFenceTime);
1472 mDisplayTimeline.updateSignalTimes();
1473
1474 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1475 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1476 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1477 presentFenceTime = &displayFenceTime;
1478 } else {
1479 retireFenceTime = &displayFenceTime;
1480 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481
1482 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1483 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1484
1485 // We use the refreshStartTime which might be sampled a little later than
1486 // when we started doing work for this frame, but that should be okay
1487 // since updateCompositorTiming has snapping logic.
1488 updateCompositorTiming(
1489 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1490
Robert Carr2047fae2016-11-28 14:09:09 -08001491 mDrawingState.traverseInZOrder([&](Layer* layer) {
1492 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001494 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001495 recordBufferingStats(layer->getName().string(),
1496 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001497 }
Robert Carr2047fae2016-11-28 14:09:09 -08001498 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001499
Brian Anderson3d4039d2016-09-23 16:31:30 -07001500 if (displayFence->isValid()) {
1501 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001502 enableHardwareVsync();
1503 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001504 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001505 }
1506 }
1507
Andy McFadden5167ec62014-05-22 13:08:43 -07001508 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001509 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001510 enableHardwareVsync();
1511 }
1512 }
1513
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001514 if (mAnimCompositionPending) {
1515 mAnimCompositionPending = false;
1516
Brian Anderson3d4039d2016-09-23 16:31:30 -07001517 if (displayFenceTime->isValid()) {
1518 mAnimFrameTracker.setActualPresentFence(
1519 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001520 } else {
1521 // The HWC doesn't support present fences, so use the refresh
1522 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001523 nsecs_t presentTime =
1524 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001525 mAnimFrameTracker.setActualPresentTime(presentTime);
1526 }
1527 mAnimFrameTracker.advanceFrame();
1528 }
Dan Stozab90cf072015-03-05 11:05:59 -08001529
1530 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1531 return;
1532 }
1533
1534 nsecs_t currentTime = systemTime();
1535 if (mHasPoweredOff) {
1536 mHasPoweredOff = false;
1537 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001538 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001540 if (numPeriods < NUM_BUCKETS - 1) {
1541 mFrameBuckets[numPeriods] += elapsedTime;
1542 } else {
1543 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1544 }
1545 mTotalTime += elapsedTime;
1546 }
1547 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548}
1549
1550void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001551 ATRACE_CALL();
1552 ALOGV("rebuildLayerStacks");
1553
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001555 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1556 ATRACE_CALL();
1557 mVisibleRegionsDirty = false;
1558 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001559
Jeff Sharkey76488112017-02-27 14:15:18 -07001560 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1561 Region opaqueRegion;
1562 Region dirtyRegion;
1563 Vector<sp<Layer>> layersSortedByZ;
1564 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1565 const Transform& tr(displayDevice->getTransform());
1566 const Rect bounds(displayDevice->getBounds());
1567 if (displayDevice->isDisplayOn()) {
1568 computeVisibleRegions(
1569 displayDevice->getLayerStack(), dirtyRegion,
1570 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001571
Jeff Sharkey76488112017-02-27 14:15:18 -07001572 mDrawingState.traverseInZOrder([&](Layer* layer) {
1573 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1574 Region drawRegion(tr.transform(
1575 layer->visibleNonTransparentRegion));
1576 drawRegion.andSelf(bounds);
1577 if (!drawRegion.isEmpty()) {
1578 layersSortedByZ.add(layer);
1579 } else {
1580 // Clear out the HWC layer if this layer was
1581 // previously visible, but no longer is
1582 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1583 nullptr);
1584 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001585 } else {
1586 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1587 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001588 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001589 });
1590 }
1591 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1592 displayDevice->undefinedRegion.set(bounds);
1593 displayDevice->undefinedRegion.subtractSelf(
1594 tr.transform(opaqueRegion));
1595 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001596 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001597 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001599
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001601 ATRACE_CALL();
1602 ALOGV("setUpHWComposer");
1603
Jesse Hall028dc8f2013-08-20 16:35:32 -07001604 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001605 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1606 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1607 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1608
1609 // If nothing has changed (!dirty), don't recompose.
1610 // If something changed, but we don't currently have any visible layers,
1611 // and didn't when we last did a composition, then skip it this time.
1612 // The second rule does two things:
1613 // - When all layers are removed from a display, we'll emit one black
1614 // frame, then nothing more until we get new layers.
1615 // - When a display is created with a private layer stack, we won't
1616 // emit any black frames until a layer is added to the layer stack.
1617 bool mustRecompose = dirty && !(empty && wasEmpty);
1618
1619 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1620 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1621 mustRecompose ? "doing" : "skipping",
1622 dirty ? "+" : "-",
1623 empty ? "+" : "-",
1624 wasEmpty ? "+" : "-");
1625
Dan Stoza71433162014-02-04 16:22:36 -08001626 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001627
1628 if (mustRecompose) {
1629 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1630 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001631 }
1632
Dan Stoza9e56aa02015-11-02 13:00:03 -08001633 // build the h/w work list
1634 if (CC_UNLIKELY(mGeometryInvalid)) {
1635 mGeometryInvalid = false;
1636 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1637 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1638 const auto hwcId = displayDevice->getHwcDisplayId();
1639 if (hwcId >= 0) {
1640 const Vector<sp<Layer>>& currentLayers(
1641 displayDevice->getVisibleLayersSortedByZ());
1642 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001643 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001644 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001645 if (!layer->hasHwcLayer(hwcId)) {
1646 auto hwcLayer = mHwc->createLayer(hwcId);
1647 if (hwcLayer) {
1648 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1649 } else {
1650 layer->forceClientComposition(hwcId);
1651 foundLayerWithoutHwc = true;
1652 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001653 }
1654 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001655
Robert Carrae060832016-11-28 10:51:00 -08001656 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001657 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001659 }
1660 }
1661 }
1662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 }
Riley Andrews03414a12014-07-01 14:22:59 -07001664
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001665
1666 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1667
Dan Stoza9e56aa02015-11-02 13:00:03 -08001668 // Set the per-frame data
1669 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1670 auto& displayDevice = mDisplays[displayId];
1671 const auto hwcId = displayDevice->getHwcDisplayId();
1672 if (hwcId < 0) {
1673 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001674 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001675 if (colorMatrix != mPreviousColorMatrix) {
1676 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1677 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1678 "display %zd: %d", displayId, result);
1679 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001680 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1681 layer->setPerFrameData(displayDevice);
1682 }
1683 }
1684
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001685 mPreviousColorMatrix = colorMatrix;
1686
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001688 auto& displayDevice = mDisplays[displayId];
1689 if (!displayDevice->isDisplayOn()) {
1690 continue;
1691 }
1692
1693 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1695 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001696 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001698
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699void SurfaceFlinger::doComposition() {
1700 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001701 ALOGV("doComposition");
1702
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001703 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001704 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001705 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001706 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707 // transform the dirty region into this screen's coordinate space
1708 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001709
1710 // repaint the framebuffer (if needed)
1711 doDisplayComposition(hw, dirtyRegion);
1712
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 hw->dirtyRegion.clear();
1714 hw->flip(hw->swapRegion);
1715 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001716 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001717 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001718 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001719}
1720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001721void SurfaceFlinger::postFramebuffer()
1722{
Mathias Agopian841cde52012-03-01 15:44:37 -08001723 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001724 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001725
Mathias Agopiana44b0412011-10-16 18:46:35 -07001726 const nsecs_t now = systemTime();
1727 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001728
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1730 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001731 if (!displayDevice->isDisplayOn()) {
1732 continue;
1733 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001734 const auto hwcId = displayDevice->getHwcDisplayId();
1735 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001736 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001737 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001738 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001739 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1741 sp<Fence> releaseFence = Fence::NO_FENCE;
1742 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1743 releaseFence = displayDevice->getClientTargetAcquireFence();
1744 } else {
1745 auto hwcLayer = layer->getHwcLayer(hwcId);
1746 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001747 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001748 layer->onLayerDisplayed(releaseFence);
1749 }
1750 if (hwcId >= 0) {
1751 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001752 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001753 }
1754
Mathias Agopiana44b0412011-10-16 18:46:35 -07001755 mLastSwapBufferTime = systemTime() - now;
1756 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001757
1758 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1759 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1760 logFrameStats();
1761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001762}
1763
Mathias Agopian87baae12012-07-31 12:38:26 -07001764void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765{
Mathias Agopian841cde52012-03-01 15:44:37 -08001766 ATRACE_CALL();
1767
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001768 // here we keep a copy of the drawing state (that is the state that's
1769 // going to be overwritten by handleTransactionLocked()) outside of
1770 // mStateLock so that the side-effects of the State assignment
1771 // don't happen with mStateLock held (which can cause deadlocks).
1772 State drawingState(mDrawingState);
1773
Mathias Agopianca4d3602011-05-19 15:38:14 -07001774 Mutex::Autolock _l(mStateLock);
1775 const nsecs_t now = systemTime();
1776 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777
Mathias Agopianca4d3602011-05-19 15:38:14 -07001778 // Here we're guaranteed that some transaction flags are set
1779 // so we can call handleTransactionLocked() unconditionally.
1780 // We call getTransactionFlags(), which will also clear the flags,
1781 // with mStateLock held to guarantee that mCurrentState won't change
1782 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001783
Mathias Agopiane57f2922012-08-09 16:29:12 -07001784 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001785 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001786
Mathias Agopianca4d3602011-05-19 15:38:14 -07001787 mLastTransactionTime = systemTime() - now;
1788 mDebugInTransaction = 0;
1789 invalidateHwcGeometry();
1790 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001791}
1792
Mathias Agopian87baae12012-07-31 12:38:26 -07001793void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001794{
Dan Stoza7dde5992015-05-22 09:51:44 -07001795 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001796 mCurrentState.traverseInZOrder([](Layer* layer) {
1797 layer->notifyAvailableFrames();
1798 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001799
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001800 /*
1801 * Traversal of the children
1802 * (perform the transaction for each of them if needed)
1803 */
1804
Mathias Agopian3559b072012-08-15 13:46:03 -07001805 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001806 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001808 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001809
1810 const uint32_t flags = layer->doTransaction(0);
1811 if (flags & Layer::eVisibleRegion)
1812 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001813 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 }
1815
1816 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001817 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001818 */
1819
Mathias Agopiane57f2922012-08-09 16:29:12 -07001820 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001821 // here we take advantage of Vector's copy-on-write semantics to
1822 // improve performance by skipping the transaction entirely when
1823 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001824 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1825 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001826 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001827 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001828 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001829 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001830
1831 // find the displays that were removed
1832 // (ie: in drawing state but not in current state)
1833 // also handle displays that changed
1834 // (ie: displays that are in both lists)
1835 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001836 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1837 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001838 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001839 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001840 // Call makeCurrent() on the primary display so we can
1841 // be sure that nothing associated with this display
1842 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001843 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001844 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001845 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1846 if (hw != NULL)
1847 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001848 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001849 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001850 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001851 } else {
1852 ALOGW("trying to remove the main display");
1853 }
1854 } else {
1855 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001856 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001857 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001858 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1859 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001860 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001861 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001862 // recreating the DisplayDevice, so we just remove it
1863 // from the drawing state, so that it get re-added
1864 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001865 sp<DisplayDevice> hw(getDisplayDevice(display));
1866 if (hw != NULL)
1867 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001868 mDisplays.removeItem(display);
1869 mDrawingState.displays.removeItemsAt(i);
1870 dc--; i--;
1871 // at this point we must loop to the next item
1872 continue;
1873 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001874
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001875 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001876 if (disp != NULL) {
1877 if (state.layerStack != draw[i].layerStack) {
1878 disp->setLayerStack(state.layerStack);
1879 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001880 if ((state.orientation != draw[i].orientation)
1881 || (state.viewport != draw[i].viewport)
1882 || (state.frame != draw[i].frame))
1883 {
1884 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001885 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001886 }
Michael Lentine47e45402014-07-18 15:34:25 -07001887 if (state.width != draw[i].width || state.height != draw[i].height) {
1888 disp->setDisplaySize(state.width, state.height);
1889 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001890 }
1891 }
1892 }
1893
1894 // find displays that were added
1895 // (ie: in current state but not in drawing state)
1896 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001897 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001898 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001899
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001900 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001901 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001902 sp<IGraphicBufferProducer> bqProducer;
1903 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001904 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1905 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001908 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001909 // Virtual displays without a surface are dormant:
1910 // they have external state (layer stack, projection,
1911 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001912 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001913
Dan Stoza8cf150a2016-08-02 10:27:31 -07001914 if (mUseHwcVirtualDisplays) {
1915 int width = 0;
1916 int status = state.surface->query(
1917 NATIVE_WINDOW_WIDTH, &width);
1918 ALOGE_IF(status != NO_ERROR,
1919 "Unable to query width (%d)", status);
1920 int height = 0;
1921 status = state.surface->query(
1922 NATIVE_WINDOW_HEIGHT, &height);
1923 ALOGE_IF(status != NO_ERROR,
1924 "Unable to query height (%d)", status);
1925 int intFormat = 0;
1926 status = state.surface->query(
1927 NATIVE_WINDOW_FORMAT, &intFormat);
1928 ALOGE_IF(status != NO_ERROR,
1929 "Unable to query format (%d)", status);
1930 auto format = static_cast<android_pixel_format_t>(
1931 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001932
Dan Stoza8cf150a2016-08-02 10:27:31 -07001933 mHwc->allocateVirtualDisplay(width, height, &format,
1934 &hwcId);
1935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936
Dan Stoza5cf424b2016-05-20 14:02:39 -07001937 // TODO: Plumb requested format back up to consumer
1938
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 sp<VirtualDisplaySurface> vds =
1940 new VirtualDisplaySurface(*mHwc,
1941 hwcId, state.surface, bqProducer,
1942 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001943
1944 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001945 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001946 }
1947 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001948 ALOGE_IF(state.surface!=NULL,
1949 "adding a supported display, but rendering "
1950 "surface is provided (%p), ignoring it",
1951 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001952
1953 hwcId = state.type;
1954 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1955 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001956 }
1957
1958 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001959 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001960 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 state.type, hwcId, state.isSecure, display,
1962 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001963 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001964 hw->setLayerStack(state.layerStack);
1965 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001966 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001967 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001968 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001970 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001971 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001972 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001973 }
1974 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001976 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977
Mathias Agopian84300952012-11-21 16:02:13 -08001978 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1979 // The transform hint might have changed for some layers
1980 // (either because a display has changed, or because a layer
1981 // as changed).
1982 //
1983 // Walk through all the layers in currentLayers,
1984 // and update their transform hint.
1985 //
1986 // If a layer is visible only on a single display, then that
1987 // display is used to calculate the hint, otherwise we use the
1988 // default display.
1989 //
1990 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1991 // the hint is set before we acquire a buffer from the surface texture.
1992 //
1993 // NOTE: layer transactions have taken place already, so we use their
1994 // drawing state. However, SurfaceFlinger's own transaction has not
1995 // happened yet, so we must use the current state layer list
1996 // (soon to become the drawing state list).
1997 //
1998 sp<const DisplayDevice> disp;
1999 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002000 bool first = true;
2001 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002002 // NOTE: we rely on the fact that layers are sorted by
2003 // layerStack first (so we don't have to traverse the list
2004 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002005 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002006 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002007 currentlayerStack = layerStack;
2008 // figure out if this layerstack is mirrored
2009 // (more than one display) if so, pick the default display,
2010 // if not, pick the only display it's on.
2011 disp.clear();
2012 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2013 sp<const DisplayDevice> hw(mDisplays[dpy]);
2014 if (hw->getLayerStack() == currentlayerStack) {
2015 if (disp == NULL) {
2016 disp = hw;
2017 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002018 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002019 break;
2020 }
2021 }
2022 }
2023 }
Chet Haase91d25932013-04-11 15:24:55 -07002024 if (disp == NULL) {
2025 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2026 // redraw after transform hint changes. See bug 8508397.
2027
2028 // could be null when this layer is using a layerStack
2029 // that is not visible on any display. Also can occur at
2030 // screen off/on times.
2031 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002032 }
Chet Haase91d25932013-04-11 15:24:55 -07002033 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002034
2035 first = false;
2036 });
Mathias Agopian84300952012-11-21 16:02:13 -08002037 }
2038
2039
Mathias Agopian3559b072012-08-15 13:46:03 -07002040 /*
2041 * Perform our own transaction if needed
2042 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002043
2044 if (mLayersAdded) {
2045 mLayersAdded = false;
2046 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002047 mVisibleRegionsDirty = true;
2048 }
2049
2050 // some layers might have been removed, so
2051 // we need to update the regions they're exposing.
2052 if (mLayersRemoved) {
2053 mLayersRemoved = false;
2054 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002055 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002056 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002057 // this layer is not visible anymore
2058 // TODO: we could traverse the tree from front to back and
2059 // compute the actual visible region
2060 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002061 Region visibleReg;
2062 visibleReg.set(layer->computeScreenBounds());
2063 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002064 }
Robert Carr2047fae2016-11-28 14:09:09 -08002065 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066 }
2067
2068 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002069
2070 updateCursorAsync();
2071}
2072
2073void SurfaceFlinger::updateCursorAsync()
2074{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2076 auto& displayDevice = mDisplays[displayId];
2077 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002078 continue;
2079 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080
2081 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2082 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002083 }
2084 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002085}
2086
2087void SurfaceFlinger::commitTransaction()
2088{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002089 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002090 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002091 for (const auto& l : mLayersPendingRemoval) {
2092 recordBufferingStats(l->getName().string(),
2093 l->getOccupancyHistory(true));
2094 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002095 }
2096 mLayersPendingRemoval.clear();
2097 }
2098
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002099 // If this transaction is part of a window animation then the next frame
2100 // we composite should be considered an animation as well.
2101 mAnimCompositionPending = mAnimTransactionPending;
2102
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002104 mDrawingState.traverseInZOrder([](Layer* layer) {
2105 layer->commitChildList();
2106 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002107 mTransactionPending = false;
2108 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002109 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110}
2111
Robert Carr2047fae2016-11-28 14:09:09 -08002112void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002113 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114{
Mathias Agopian841cde52012-03-01 15:44:37 -08002115 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118 Region aboveOpaqueLayers;
2119 Region aboveCoveredLayers;
2120 Region dirty;
2121
Mathias Agopian87baae12012-07-31 12:38:26 -07002122 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123
Robert Carr2047fae2016-11-28 14:09:09 -08002124 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002125 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002126 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002127
Jesse Hall01e29052013-02-19 16:13:35 -08002128 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002129 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002130 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002131
Mathias Agopianab028732010-03-16 16:41:46 -07002132 /*
2133 * opaqueRegion: area of a surface that is fully opaque.
2134 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002136
2137 /*
2138 * visibleRegion: area of a surface that is visible on screen
2139 * and not fully transparent. This is essentially the layer's
2140 * footprint minus the opaque regions above it.
2141 * Areas covered by a translucent surface are considered visible.
2142 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002144
2145 /*
2146 * coveredRegion: area of a surface that is covered by all
2147 * visible regions above it (which includes the translucent areas).
2148 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002150
Jesse Halla8026d22012-09-25 13:25:04 -07002151 /*
2152 * transparentRegion: area of a surface that is hinted to be completely
2153 * transparent. This is only used to tell when the layer has no visible
2154 * non-transparent regions and can be removed from the layer list. It
2155 * does not affect the visibleRegion of this layer or any layers
2156 * beneath it. The hint may not be correct if apps don't respect the
2157 * SurfaceView restrictions (which, sadly, some don't).
2158 */
2159 Region transparentRegion;
2160
Mathias Agopianab028732010-03-16 16:41:46 -07002161
2162 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002163 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002164 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002165 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002167 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002168 if (!visibleRegion.isEmpty()) {
2169 // Remove the transparent area from the visible region
2170 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002171 if (tr.preserveRects()) {
2172 // transform the transparent region
2173 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002174 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002175 // transformation too complex, can't do the
2176 // transparent region optimization.
2177 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002178 }
Mathias Agopianab028732010-03-16 16:41:46 -07002179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180
Mathias Agopianab028732010-03-16 16:41:46 -07002181 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002182 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002183 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002184 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2185 // the opaque region is the layer's footprint
2186 opaqueRegion = visibleRegion;
2187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188 }
2189 }
2190
Mathias Agopianab028732010-03-16 16:41:46 -07002191 // Clip the covered region to the visible region
2192 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2193
2194 // Update aboveCoveredLayers for next (lower) layer
2195 aboveCoveredLayers.orSelf(visibleRegion);
2196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002197 // subtract the opaque region covered by the layers above us
2198 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002199
2200 // compute this layer's dirty region
2201 if (layer->contentDirty) {
2202 // we need to invalidate the whole region
2203 dirty = visibleRegion;
2204 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002205 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002206 layer->contentDirty = false;
2207 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002208 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002209 * the exposed region consists of two components:
2210 * 1) what's VISIBLE now and was COVERED before
2211 * 2) what's EXPOSED now less what was EXPOSED before
2212 *
2213 * note that (1) is conservative, we start with the whole
2214 * visible region but only keep what used to be covered by
2215 * something -- which mean it may have been exposed.
2216 *
2217 * (2) handles areas that were not covered by anything but got
2218 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002219 */
Mathias Agopianab028732010-03-16 16:41:46 -07002220 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002221 const Region oldVisibleRegion = layer->visibleRegion;
2222 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002223 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2224 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225 }
2226 dirty.subtractSelf(aboveOpaqueLayers);
2227
2228 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002229 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230
Mathias Agopianab028732010-03-16 16:41:46 -07002231 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002232 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002233
Jesse Halla8026d22012-09-25 13:25:04 -07002234 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235 layer->setVisibleRegion(visibleRegion);
2236 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002237 layer->setVisibleNonTransparentRegion(
2238 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002239 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240
Mathias Agopian87baae12012-07-31 12:38:26 -07002241 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242}
2243
Mathias Agopian87baae12012-07-31 12:38:26 -07002244void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2245 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002246 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002247 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2248 if (hw->getLayerStack() == layerStack) {
2249 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002250 }
2251 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002252}
2253
Dan Stoza6b9454d2014-11-07 16:00:59 -08002254bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002256 ALOGV("handlePageFlip");
2257
Brian Andersond6927fb2016-07-23 23:37:30 -07002258 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259
Mathias Agopian4fec8732012-06-29 14:12:52 -07002260 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002261 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002262
2263 // Store the set of layers that need updates. This set must not change as
2264 // buffers are being latched, as this could result in a deadlock.
2265 // Example: Two producers share the same command stream and:
2266 // 1.) Layer 0 is latched
2267 // 2.) Layer 0 gets a new frame
2268 // 2.) Layer 1 gets a new frame
2269 // 3.) Layer 1 is latched.
2270 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2271 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002272 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002273 if (layer->hasQueuedFrame()) {
2274 frameQueued = true;
2275 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002276 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002277 } else {
2278 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002279 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002280 } else {
2281 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002282 }
Robert Carr2047fae2016-11-28 14:09:09 -08002283 });
2284
Dan Stoza9e56aa02015-11-02 13:00:03 -08002285 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002286 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002287 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002288 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002290
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002291 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002292
2293 // If we will need to wake up at some time in the future to deal with a
2294 // queued frame that shouldn't be displayed during this vsync period, wake
2295 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002297 signalLayerUpdate();
2298 }
2299
2300 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302}
2303
Mathias Agopianad456f92011-01-13 17:53:01 -08002304void SurfaceFlinger::invalidateHwcGeometry()
2305{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002306 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002307}
2308
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002309
Fabien Sanglard830b8472016-11-30 16:35:58 -08002310void SurfaceFlinger::doDisplayComposition(
2311 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002312 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313{
Dan Stoza71433162014-02-04 16:22:36 -08002314 // We only need to actually compose the display if:
2315 // 1) It is being handled by hardware composer, which may need this to
2316 // keep its virtual display state machine in sync, or
2317 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002318 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002319 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002320 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002321 return;
2322 }
2323
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 ALOGV("doDisplayComposition");
2325
Mathias Agopian87baae12012-07-31 12:38:26 -07002326 Region dirtyRegion(inDirtyRegion);
2327
Mathias Agopianb8a55602009-06-26 19:06:36 -07002328 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002329 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002332 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002333 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2334 // takes a rectangle, we must make sure to update that whole
2335 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002336 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002337 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002338 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002339 // We need to redraw the rectangle that will be updated
2340 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002341 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002342 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002343 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002344 } else {
2345 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002346 dirtyRegion.set(displayDevice->bounds());
2347 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348 }
2349 }
2350
Fabien Sanglard830b8472016-11-30 16:35:58 -08002351 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002353 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002354 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002355
2356 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358}
2359
Dan Stoza9e56aa02015-11-02 13:00:03 -08002360bool SurfaceFlinger::doComposeSurfaces(
2361 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002362{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002363 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002364
Dan Stoza9e56aa02015-11-02 13:00:03 -08002365 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002366
2367 mat4 oldColorMatrix;
2368 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2369 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2370 if (applyColorMatrix) {
2371 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2372 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2373 }
2374
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2376 if (hasClientComposition) {
2377 ALOGV("hasClientComposition");
2378
2379 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002380 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002381 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002382 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2383 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2384 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2385 }
2386 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002387 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002388
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002389 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002390 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2391 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002392 // when using overlays, we assume a fully transparent framebuffer
2393 // NOTE: we could reduce how much we need to clear, for instance
2394 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002395 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002396 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002397 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002398 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002399 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002400 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002401
2402 // we remove the scissor part
2403 // we're left with the letterbox region
2404 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002406
2407 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002409
2410 // but limit it to the dirty region
2411 region.andSelf(dirty);
2412
Mathias Agopianb9494d52012-04-18 02:28:45 -07002413 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002414 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002415 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002417 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002418 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002419
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002421 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002422 // scissor on the main display. It should never be needed
2423 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002424 const Rect& bounds(displayDevice->getBounds());
2425 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002426 if (scissor != bounds) {
2427 // scissor doesn't match the screen's dimensions, so we
2428 // need to clear everything outside of it and enable
2429 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002430
Mathias Agopianf45c5102012-10-24 16:29:17 -07002431 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 const uint32_t height = displayDevice->getHeight();
2433 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002434 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002435 }
2436 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002437 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002438
Mathias Agopian85d751c2012-08-29 16:59:24 -07002439 /*
2440 * and then, render the layers targeted at the framebuffer
2441 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002442
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ALOGV("Rendering client layers");
2444 const Transform& displayTransform = displayDevice->getTransform();
2445 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002446 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 bool firstLayer = true;
2448 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2449 const Region clip(dirty.intersect(
2450 displayTransform.transform(layer->visibleRegion)));
2451 ALOGV("Layer: %s", layer->getName().string());
2452 ALOGV(" Composition type: %s",
2453 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002454 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 switch (layer->getCompositionType(hwcId)) {
2456 case HWC2::Composition::Cursor:
2457 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002458 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002460 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2462 layer->isOpaque(state) && (state.alpha == 1.0f)
2463 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002464 // never clear the very first layer since we're
2465 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002466 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002467 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002468 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002469 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 case HWC2::Composition::Client: {
2471 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002472 break;
2473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002475 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002476 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 } else {
2478 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002479 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 }
2482 } else {
2483 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002485 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002487 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002489 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002490 }
2491 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002492
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002493 if (applyColorMatrix) {
2494 getRenderEngine().setupColorTransform(oldColorMatrix);
2495 }
2496
Mathias Agopianf45c5102012-10-24 16:29:17 -07002497 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002499 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500}
2501
Fabien Sanglard830b8472016-11-30 16:35:58 -08002502void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2503 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002504 RenderEngine& engine(getRenderEngine());
2505 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506}
2507
Dan Stoza7d89d062015-04-30 13:29:25 -07002508status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002509 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002510 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 const sp<Layer>& lbc,
2512 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002513{
Dan Stoza7d89d062015-04-30 13:29:25 -07002514 // add this layer to the current state list
2515 {
2516 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002517 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002518 return NO_MEMORY;
2519 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 if (parent == nullptr) {
2521 mCurrentState.layersSortedByZ.add(lbc);
2522 } else {
2523 parent->addChild(lbc);
2524 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002525 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526 mLayersAdded = true;
2527 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002528 }
2529
Mathias Agopian96f08192010-06-02 23:28:45 -07002530 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002531 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002532
Dan Stoza7d89d062015-04-30 13:29:25 -07002533 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002534}
2535
Dan Stoza22851c32016-08-09 13:21:03 -07002536status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002538 sp<Layer> layer = weakLayer.promote();
2539 if (layer == nullptr) {
2540 // The layer has already been removed, carry on
2541 return NO_ERROR;
2542 }
2543
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 const auto& p = layer->getParent();
2545 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2546 mCurrentState.layersSortedByZ.remove(layer);
2547
Robert Carr136e2f62017-02-08 17:54:29 -08002548 // As a matter of normal operation, the LayerCleaner will produce a second
2549 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2550 // so we will succeed in promoting it, but it's already been removed
2551 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2552 // otherwise something has gone wrong and we are leaking the layer.
2553 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2555 layer->getName().string(),
2556 (p != nullptr) ? p->getName().string() : "no-parent");
2557 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002558 } else if (index < 0) {
2559 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002560 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002561
2562 mLayersPendingRemoval.add(layer);
2563 mLayersRemoved = true;
2564 mNumLayers--;
2565 setTransactionFlags(eTransactionNeeded);
2566 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567}
2568
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002569uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002570 return android_atomic_release_load(&mTransactionFlags);
2571}
2572
Mathias Agopian3f844832013-08-07 21:24:32 -07002573uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2575}
2576
Mathias Agopian3f844832013-08-07 21:24:32 -07002577uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2579 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002580 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 }
2582 return old;
2583}
2584
Mathias Agopian8b33f032012-07-24 20:43:54 -07002585void SurfaceFlinger::setTransactionState(
2586 const Vector<ComposerState>& state,
2587 const Vector<DisplayState>& displays,
2588 uint32_t flags)
2589{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002590 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002591 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002592 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002593
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002594 if (flags & eAnimation) {
2595 // For window updates that are part of an animation we must wait for
2596 // previous animation "frames" to be handled.
2597 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002598 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002599 if (CC_UNLIKELY(err != NO_ERROR)) {
2600 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002601 // caller after a few seconds.
2602 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2603 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002604 mAnimTransactionPending = false;
2605 break;
2606 }
2607 }
2608 }
2609
Mathias Agopiane57f2922012-08-09 16:29:12 -07002610 size_t count = displays.size();
2611 for (size_t i=0 ; i<count ; i++) {
2612 const DisplayState& s(displays[i]);
2613 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002614 }
2615
Mathias Agopiane57f2922012-08-09 16:29:12 -07002616 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002617 for (size_t i=0 ; i<count ; i++) {
2618 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002619 // Here we need to check that the interface we're given is indeed
2620 // one of our own. A malicious client could give us a NULL
2621 // IInterface, or one of its own or even one of our own but a
2622 // different type. All these situations would cause us to crash.
2623 //
2624 // NOTE: it would be better to use RTTI as we could directly check
2625 // that we have a Client*. however, RTTI is disabled in Android.
2626 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002627 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002628 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002629 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002630 sp<Client> client( static_cast<Client *>(s.client.get()) );
2631 transactionFlags |= setClientStateLocked(client, s.state);
2632 }
2633 }
2634 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002635 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002636
Robert Carr2a7dbb42016-05-24 11:41:28 -07002637 // If a synchronous transaction is explicitly requested without any changes,
2638 // force a transaction anyway. This can be used as a flush mechanism for
2639 // previous async transactions.
2640 if (transactionFlags == 0 && (flags & eSynchronous)) {
2641 transactionFlags = eTransactionNeeded;
2642 }
2643
Mathias Agopian386aa982011-11-07 21:58:03 -08002644 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002645 if (mInterceptor.isEnabled()) {
2646 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2647 }
Irvel468051e2016-06-13 16:44:44 -07002648
Mathias Agopian386aa982011-11-07 21:58:03 -08002649 // this triggers the transaction
2650 setTransactionFlags(transactionFlags);
2651
2652 // if this is a synchronous transaction, wait for it to take effect
2653 // before returning.
2654 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002655 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002656 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002657 if (flags & eAnimation) {
2658 mAnimTransactionPending = true;
2659 }
2660 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002661 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2662 if (CC_UNLIKELY(err != NO_ERROR)) {
2663 // just in case something goes wrong in SF, return to the
2664 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002665 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2666 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002667 break;
2668 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002669 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670 }
2671}
2672
Mathias Agopiane57f2922012-08-09 16:29:12 -07002673uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2674{
Jesse Hall9a143922012-10-04 16:29:19 -07002675 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2676 if (dpyIdx < 0)
2677 return 0;
2678
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002680 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002681 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002682 const uint32_t what = s.what;
2683 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002684 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002685 disp.surface = s.surface;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 }
2689 if (what & DisplayState::eLayerStackChanged) {
2690 if (disp.layerStack != s.layerStack) {
2691 disp.layerStack = s.layerStack;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002695 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002696 if (disp.orientation != s.orientation) {
2697 disp.orientation = s.orientation;
2698 flags |= eDisplayTransactionNeeded;
2699 }
2700 if (disp.frame != s.frame) {
2701 disp.frame = s.frame;
2702 flags |= eDisplayTransactionNeeded;
2703 }
2704 if (disp.viewport != s.viewport) {
2705 disp.viewport = s.viewport;
2706 flags |= eDisplayTransactionNeeded;
2707 }
2708 }
Michael Lentine47e45402014-07-18 15:34:25 -07002709 if (what & DisplayState::eDisplaySizeChanged) {
2710 if (disp.width != s.width) {
2711 disp.width = s.width;
2712 flags |= eDisplayTransactionNeeded;
2713 }
2714 if (disp.height != s.height) {
2715 disp.height = s.height;
2716 flags |= eDisplayTransactionNeeded;
2717 }
2718 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002719 }
2720 return flags;
2721}
2722
2723uint32_t SurfaceFlinger::setClientStateLocked(
2724 const sp<Client>& client,
2725 const layer_state_t& s)
2726{
2727 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002728 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 if (layer != 0) {
2730 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002731 bool geometryAppliesWithResize =
2732 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002733 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002734 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002736 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002737 }
2738 if (what & layer_state_t::eLayerChanged) {
2739 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 const auto& p = layer->getParent();
2741 if (p == nullptr) {
2742 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2743 if (layer->setLayer(s.z) && idx >= 0) {
2744 mCurrentState.layersSortedByZ.removeAt(idx);
2745 mCurrentState.layersSortedByZ.add(layer);
2746 // we need traversal (state changed)
2747 // AND transaction (list changed)
2748 flags |= eTransactionNeeded|eTraversalNeeded;
2749 }
2750 } else {
2751 if (p->setChildLayer(layer, s.z)) {
2752 flags |= eTransactionNeeded|eTraversalNeeded;
2753 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002754 }
2755 }
2756 if (what & layer_state_t::eSizeChanged) {
2757 if (layer->setSize(s.w, s.h)) {
2758 flags |= eTraversalNeeded;
2759 }
2760 }
2761 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002762 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 flags |= eTraversalNeeded;
2764 }
2765 if (what & layer_state_t::eMatrixChanged) {
2766 if (layer->setMatrix(s.matrix))
2767 flags |= eTraversalNeeded;
2768 }
2769 if (what & layer_state_t::eTransparentRegionChanged) {
2770 if (layer->setTransparentRegionHint(s.transparentRegion))
2771 flags |= eTraversalNeeded;
2772 }
Dan Stoza23116082015-06-18 14:58:39 -07002773 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002774 if (layer->setFlags(s.flags, s.mask))
2775 flags |= eTraversalNeeded;
2776 }
2777 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002778 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002779 flags |= eTraversalNeeded;
2780 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002781 if (what & layer_state_t::eFinalCropChanged) {
2782 if (layer->setFinalCrop(s.finalCrop))
2783 flags |= eTraversalNeeded;
2784 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002785 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002786 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002787 // We only allow setting layer stacks for top level layers,
2788 // everything else inherits layer stack from its parent.
2789 if (layer->hasParent()) {
2790 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2791 layer->getName().string());
2792 } else if (idx < 0) {
2793 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2794 "that also does not appear in the top level layer list. Something"
2795 " has gone wrong.", layer->getName().string());
2796 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002797 mCurrentState.layersSortedByZ.removeAt(idx);
2798 mCurrentState.layersSortedByZ.add(layer);
2799 // we need traversal (state changed)
2800 // AND transaction (list changed)
2801 flags |= eTransactionNeeded|eTraversalNeeded;
2802 }
2803 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002804 if (what & layer_state_t::eDeferTransaction) {
2805 layer->deferTransactionUntil(s.handle, s.frameNumber);
2806 // We don't trigger a traversal here because if no other state is
2807 // changed, we don't want this to cause any more work
2808 }
Robert Carr1db73f62016-12-21 12:58:51 -08002809 if (what & layer_state_t::eReparentChildren) {
2810 if (layer->reparentChildren(s.reparentHandle)) {
2811 flags |= eTransactionNeeded|eTraversalNeeded;
2812 }
2813 }
Robert Carrc3574f72016-03-24 12:19:32 -07002814 if (what & layer_state_t::eOverrideScalingModeChanged) {
2815 layer->setOverrideScalingMode(s.overrideScalingMode);
2816 // We don't trigger a traversal here because if no other state is
2817 // changed, we don't want this to cause any more work
2818 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002819 }
2820 return flags;
2821}
2822
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002823status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002824 const String8& name,
2825 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002826 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002827 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2828 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002830 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002831 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002832 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002833 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002834 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002835
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002836 status_t result = NO_ERROR;
2837
2838 sp<Layer> layer;
2839
Mathias Agopian3165cc22012-08-08 19:42:09 -07002840 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2841 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002842 result = createNormalLayer(client,
2843 name, w, h, flags, format,
2844 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002846 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002847 result = createDimLayer(client,
2848 name, w, h, flags,
2849 handle, gbp, &layer);
2850 break;
2851 default:
2852 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 break;
2854 }
2855
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 if (result != NO_ERROR) {
2857 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002859
Albert Chaulk479c60c2017-01-27 14:21:34 -05002860 layer->setInfo(windowType, ownerUid);
2861
Robert Carr1f0a16a2016-10-24 16:27:39 -07002862 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002863 if (result != NO_ERROR) {
2864 return result;
2865 }
Irvelffc9efc2016-07-27 15:16:37 -07002866 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002867
2868 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002869 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870}
2871
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002872status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2873 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2874 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875{
2876 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002877 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 case PIXEL_FORMAT_TRANSPARENT:
2879 case PIXEL_FORMAT_TRANSLUCENT:
2880 format = PIXEL_FORMAT_RGBA_8888;
2881 break;
2882 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002883 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 break;
2885 }
2886
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002887 *outLayer = new Layer(this, client, name, w, h, flags);
2888 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2889 if (err == NO_ERROR) {
2890 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002891 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893
2894 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2895 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896}
2897
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002898status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2899 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2900 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002902 *outLayer = new LayerDim(this, client, name, w, h, flags);
2903 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002904 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002905 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002906}
2907
Mathias Agopianac9fa422013-02-11 16:40:36 -08002908status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909{
Mathias Agopian67106042013-03-14 19:18:13 -07002910 // called by the window manager when it wants to remove a Layer
2911 status_t err = NO_ERROR;
2912 sp<Layer> l(client->getLayerUser(handle));
2913 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002914 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002915 err = removeLayer(l);
2916 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2917 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002918 }
2919 return err;
2920}
2921
Mathias Agopian13127d82013-03-05 17:47:11 -08002922status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002923{
Mathias Agopian67106042013-03-14 19:18:13 -07002924 // called by ~LayerCleaner() when all references to the IBinder (handle)
2925 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002926 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927}
2928
Mathias Agopianb60314a2012-04-10 22:09:54 -07002929// ---------------------------------------------------------------------------
2930
Andy McFadden13a082e2012-08-24 10:16:42 -07002931void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002932 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002933 Vector<ComposerState> state;
2934 Vector<DisplayState> displays;
2935 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002936 d.what = DisplayState::eDisplayProjectionChanged |
2937 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002938 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002939 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002940 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002941 d.frame.makeInvalid();
2942 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002943 d.width = 0;
2944 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002945 displays.add(d);
2946 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002947 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002948
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2950 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002951 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002952
2953 {
2954 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2955 mCompositorTiming.interval = period;
2956 }
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");
Andy McFadden4803b742012-09-24 19:07:20 -07003215#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003216 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003217#endif
3218#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003220#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003221 if (isLayerTripleBufferingDisabled())
3222 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003223 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003224}
3225
Dan Stozab90cf072015-03-05 11:05:59 -08003226void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3227{
3228 result.appendFormat("Static screen stats:\n");
3229 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3230 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3231 float percent = 100.0f *
3232 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3233 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3234 b + 1, bucketTimeSec, percent);
3235 }
3236 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3237 float percent = 100.0f *
3238 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3239 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3240 NUM_BUCKETS - 1, bucketTimeSec, percent);
3241}
3242
Dan Stozae77c7662016-05-13 11:37:28 -07003243void SurfaceFlinger::recordBufferingStats(const char* layerName,
3244 std::vector<OccupancyTracker::Segment>&& history) {
3245 Mutex::Autolock lock(mBufferingStatsMutex);
3246 auto& stats = mBufferingStats[layerName];
3247 for (const auto& segment : history) {
3248 if (!segment.usedThirdBuffer) {
3249 stats.twoBufferTime += segment.totalTime;
3250 }
3251 if (segment.occupancyAverage < 1.0f) {
3252 stats.doubleBufferedTime += segment.totalTime;
3253 } else if (segment.occupancyAverage < 2.0f) {
3254 stats.tripleBufferedTime += segment.totalTime;
3255 }
3256 ++stats.numSegments;
3257 stats.totalTime += segment.totalTime;
3258 }
3259}
3260
Brian Andersond6927fb2016-07-23 23:37:30 -07003261void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3262 result.appendFormat("Layer frame timestamps:\n");
3263
3264 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3265 const size_t count = currentLayers.size();
3266 for (size_t i=0 ; i<count ; i++) {
3267 currentLayers[i]->dumpFrameEvents(result);
3268 }
3269}
3270
Dan Stozae77c7662016-05-13 11:37:28 -07003271void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3272 result.append("Buffering stats:\n");
3273 result.append(" [Layer name] <Active time> <Two buffer> "
3274 "<Double buffered> <Triple buffered>\n");
3275 Mutex::Autolock lock(mBufferingStatsMutex);
3276 typedef std::tuple<std::string, float, float, float> BufferTuple;
3277 std::map<float, BufferTuple, std::greater<float>> sorted;
3278 for (const auto& statsPair : mBufferingStats) {
3279 const char* name = statsPair.first.c_str();
3280 const BufferingStats& stats = statsPair.second;
3281 if (stats.numSegments == 0) {
3282 continue;
3283 }
3284 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3285 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3286 stats.totalTime;
3287 float doubleBufferRatio = static_cast<float>(
3288 stats.doubleBufferedTime) / stats.totalTime;
3289 float tripleBufferRatio = static_cast<float>(
3290 stats.tripleBufferedTime) / stats.totalTime;
3291 sorted.insert({activeTime, {name, twoBufferRatio,
3292 doubleBufferRatio, tripleBufferRatio}});
3293 }
3294 for (const auto& sortedPair : sorted) {
3295 float activeTime = sortedPair.first;
3296 const BufferTuple& values = sortedPair.second;
3297 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3298 std::get<0>(values).c_str(), activeTime,
3299 std::get<1>(values), std::get<2>(values),
3300 std::get<3>(values));
3301 }
3302 result.append("\n");
3303}
3304
3305
Mathias Agopian74d211a2013-04-22 16:55:35 +02003306void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3307 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003308{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003309 bool colorize = false;
3310 if (index < args.size()
3311 && (args[index] == String16("--color"))) {
3312 colorize = true;
3313 index++;
3314 }
3315
3316 Colorizer colorizer(colorize);
3317
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003318 // figure out if we're stuck somewhere
3319 const nsecs_t now = systemTime();
3320 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3321 const nsecs_t inTransaction(mDebugInTransaction);
3322 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3323 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3324
3325 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003326 * Dump library configuration.
3327 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003328
3329 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003330 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003331 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003332 appendSfConfigString(result);
3333 appendUiConfigString(result);
3334 appendGuiConfigString(result);
3335 result.append("\n");
3336
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003337 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003338 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003339 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003340 result.append(SyncFeatures::getInstance().toString());
3341 result.append("\n");
3342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3344
Andy McFadden41d67d72014-04-25 16:58:34 -07003345 colorizer.bold(result);
3346 result.append("DispSync configuration: ");
3347 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003348 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3349 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003350 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3351 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003352 result.append("\n");
3353
Dan Stozab90cf072015-03-05 11:05:59 -08003354 // Dump static screen stats
3355 result.append("\n");
3356 dumpStaticScreenStats(result);
3357 result.append("\n");
3358
Dan Stozae77c7662016-05-13 11:37:28 -07003359 dumpBufferingStats(result);
3360
Andy McFadden4803b742012-09-24 19:07:20 -07003361 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003362 * Dump the visible layer list
3363 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003365 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003366 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003367 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003368 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003369 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003370
3371 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003372 * Dump Display state
3373 */
3374
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003375 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003376 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003377 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003378 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3379 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003380 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003381 }
3382
3383 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003384 * Dump SurfaceFlinger global state
3385 */
3386
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003387 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003388 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003389 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390
Mathias Agopian888c8222012-08-04 21:10:38 -07003391 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003392 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003393
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003394 colorizer.bold(result);
3395 result.appendFormat("EGL implementation : %s\n",
3396 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3397 colorizer.reset(result);
3398 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003399 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003400
Mathias Agopian875d8e12013-06-07 15:35:48 -07003401 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402
Mathias Agopian42977342012-08-05 00:40:46 -07003403 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003404 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3405 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003406 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003407 " last eglSwapBuffers() time: %f us\n"
3408 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003409 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003410 " refresh-rate : %f fps\n"
3411 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003412 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003413 " gpu_to_cpu_unsupported : %d\n"
3414 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003415 mLastSwapBufferTime/1000.0,
3416 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003417 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003418 1e9 / activeConfig->getVsyncPeriod(),
3419 activeConfig->getDpiX(),
3420 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003421 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003422
Mathias Agopian74d211a2013-04-22 16:55:35 +02003423 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425
Mathias Agopian74d211a2013-04-22 16:55:35 +02003426 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003427 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428
3429 /*
3430 * VSYNC state
3431 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003433 result.append("\n");
3434
3435 /*
3436 * HWC layer minidump
3437 */
3438 for (size_t d = 0; d < mDisplays.size(); d++) {
3439 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3440 int32_t hwcId = displayDevice->getHwcDisplayId();
3441 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3442 continue;
3443 }
3444
3445 result.appendFormat("Display %d HWC layers:\n", hwcId);
3446 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003447 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003448 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003449 });
Dan Stozae22aec72016-08-01 13:20:59 -07003450 result.append("\n");
3451 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003452
3453 /*
3454 * Dump HWComposer state
3455 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003456 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003457 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003458 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003459 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003460 result.appendFormat(" h/w composer %s\n",
3461 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003462 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003463
3464 /*
3465 * Dump gralloc state
3466 */
3467 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3468 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469}
3470
Mathias Agopian13127d82013-03-05 17:47:11 -08003471const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003472SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003473 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003474 wp<IBinder> dpy;
3475 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3476 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3477 dpy = mDisplays.keyAt(i);
3478 break;
3479 }
3480 }
3481 if (dpy == NULL) {
3482 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3483 // Just use the primary display so we have something to return
3484 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3485 }
3486 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003487}
3488
Keun young Park63f165f2012-08-31 10:53:36 -07003489bool SurfaceFlinger::startDdmConnection()
3490{
3491 void* libddmconnection_dso =
3492 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3493 if (!libddmconnection_dso) {
3494 return false;
3495 }
3496 void (*DdmConnection_start)(const char* name);
3497 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003498 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003499 if (!DdmConnection_start) {
3500 dlclose(libddmconnection_dso);
3501 return false;
3502 }
3503 (*DdmConnection_start)(getServiceName());
3504 return true;
3505}
3506
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003507status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 switch (code) {
3509 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003510 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003512 case CLEAR_ANIMATION_FRAME_STATS:
3513 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003515 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 {
3517 // codes that require permission check
3518 IPCThreadState* ipc = IPCThreadState::self();
3519 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003520 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003521 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003522 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003523 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003524 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003526 break;
3527 }
Robert Carr1db73f62016-12-21 12:58:51 -08003528 /*
3529 * Calling setTransactionState is safe, because you need to have been
3530 * granted a reference to Client* and Handle* to do anything with it.
3531 *
3532 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3533 */
3534 case SET_TRANSACTION_STATE:
3535 case CREATE_SCOPED_CONNECTION:
3536 {
3537 return OK;
3538 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003539 case CAPTURE_SCREEN:
3540 {
3541 // codes that require permission check
3542 IPCThreadState* ipc = IPCThreadState::self();
3543 const int pid = ipc->getCallingPid();
3544 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003545 if ((uid != AID_GRAPHICS) &&
3546 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003547 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003548 return PERMISSION_DENIED;
3549 }
3550 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551 }
3552 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003553 return OK;
3554}
3555
3556status_t SurfaceFlinger::onTransact(
3557 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3558{
3559 status_t credentialCheck = CheckTransactCodeCredentials(code);
3560 if (credentialCheck != OK) {
3561 return credentialCheck;
3562 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3565 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003566 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003567 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003568 IPCThreadState* ipc = IPCThreadState::self();
3569 const int pid = ipc->getCallingPid();
3570 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003571 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003572 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 return PERMISSION_DENIED;
3574 }
3575 int n;
3576 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003577 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003578 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 return NO_ERROR;
3580 case 1002: // SHOW_UPDATES
3581 n = data.readInt32();
3582 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003583 invalidateHwcGeometry();
3584 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003587 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003588 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003590 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591 setTransactionFlags(
3592 eTransactionNeeded|
3593 eDisplayTransactionNeeded|
3594 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003595 return NO_ERROR;
3596 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003597 case 1006:{ // send empty update
3598 signalRefresh();
3599 return NO_ERROR;
3600 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003601 case 1008: // toggle use of hw composer
3602 n = data.readInt32();
3603 mDebugDisableHWC = n ? 1 : 0;
3604 invalidateHwcGeometry();
3605 repaintEverything();
3606 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003607 case 1009: // toggle use of transform hint
3608 n = data.readInt32();
3609 mDebugDisableTransformHint = n ? 1 : 0;
3610 invalidateHwcGeometry();
3611 repaintEverything();
3612 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003614 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 reply->writeInt32(0);
3616 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003617 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003618 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 return NO_ERROR;
3620 case 1013: {
3621 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003622 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3623 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003624 return NO_ERROR;
3625 }
3626 case 1014: {
3627 // daltonize
3628 n = data.readInt32();
3629 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003630 case 1:
3631 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3632 break;
3633 case 2:
3634 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3635 break;
3636 case 3:
3637 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3638 break;
3639 default:
3640 mDaltonizer.setType(ColorBlindnessType::None);
3641 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003642 }
3643 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003644 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003645 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003646 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003647 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003648 invalidateHwcGeometry();
3649 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003650 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003652 case 1015: {
3653 // apply a color matrix
3654 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003655 if (n) {
3656 // color matrix is sent as mat3 matrix followed by vec3
3657 // offset, then packed into a mat4 where the last row is
3658 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003659 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003660 for (size_t j = 0; j < 4; j++) {
3661 mColorMatrix[i][j] = data.readFloat();
3662 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003663 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003664 } else {
3665 mColorMatrix = mat4();
3666 }
3667 invalidateHwcGeometry();
3668 repaintEverything();
3669 return NO_ERROR;
3670 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003671 // This is an experimental interface
3672 // Needs to be shifted to proper binder interface when we productize
3673 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003674 n = data.readInt32();
3675 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003676 return NO_ERROR;
3677 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003678 case 1017: {
3679 n = data.readInt32();
3680 mForceFullDamage = static_cast<bool>(n);
3681 return NO_ERROR;
3682 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003683 case 1018: { // Modify Choreographer's phase offset
3684 n = data.readInt32();
3685 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3686 return NO_ERROR;
3687 }
3688 case 1019: { // Modify SurfaceFlinger's phase offset
3689 n = data.readInt32();
3690 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3691 return NO_ERROR;
3692 }
Irvel468051e2016-06-13 16:44:44 -07003693 case 1020: { // Layer updates interceptor
3694 n = data.readInt32();
3695 if (n) {
3696 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003697 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003698 }
3699 else{
3700 ALOGV("Interceptor disabled");
3701 mInterceptor.disable();
3702 }
3703 return NO_ERROR;
3704 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003705 case 1021: { // Disable HWC virtual displays
3706 n = data.readInt32();
3707 mUseHwcVirtualDisplays = !n;
3708 return NO_ERROR;
3709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 }
3711 }
3712 return err;
3713}
3714
Mathias Agopian53331da2011-08-22 21:44:41 -07003715void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003716 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003717 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003718}
3719
Mathias Agopian59119e62010-10-11 12:37:43 -07003720// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003721// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003722// ---------------------------------------------------------------------------
3723
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003724/* The code below is here to handle b/8734824
3725 *
3726 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003727 * from the surfaceflinger thread to the calling binder thread, where they
3728 * are executed. This allows the calling thread in the calling process to be
3729 * reused and not depend on having "enough" binder threads to handle the
3730 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003731 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003732class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003733 /* Parts of GraphicProducerWrapper are run on two different threads,
3734 * communicating by sending messages via Looper but also by shared member
3735 * data. Coherence maintenance is subtle and in places implicit (ugh).
3736 *
3737 * Don't rely on Looper's sendMessage/handleMessage providing
3738 * release/acquire semantics for any data not actually in the Message.
3739 * Data going from surfaceflinger to binder threads needs to be
3740 * synchronized explicitly.
3741 *
3742 * Barrier open/wait do provide release/acquire semantics. This provides
3743 * implicit synchronization for data coming back from binder to
3744 * surfaceflinger threads.
3745 */
3746
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003747 sp<IGraphicBufferProducer> impl;
3748 sp<Looper> looper;
3749 status_t result;
3750 bool exitPending;
3751 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003752 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753 uint32_t code;
3754 Parcel const* data;
3755 Parcel* reply;
3756
3757 enum {
3758 MSG_API_CALL,
3759 MSG_EXIT
3760 };
3761
3762 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003763 * Called on surfaceflinger thread. This is called by our "fake"
3764 * BpGraphicBufferProducer. We package the data and reply Parcel and
3765 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003766 */
3767 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003768 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003769 this->code = code;
3770 this->data = &data;
3771 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003772 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003773 // if we've exited, we run the message synchronously right here.
3774 // note (JH): as far as I can tell from looking at the code, this
3775 // never actually happens. if it does, i'm not sure if it happens
3776 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003777 handleMessage(Message(MSG_API_CALL));
3778 } else {
3779 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003780 // Prevent stores to this->{code, data, reply} from being
3781 // reordered later than the construction of Message.
3782 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 looper->sendMessage(this, Message(MSG_API_CALL));
3784 barrier.wait();
3785 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003786 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 }
3788
3789 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003790 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003791 * call the real BpGraphicBufferProducer.
3792 */
3793 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003794 int what = message.what;
3795 // Prevent reads below from happening before the read from Message
3796 atomic_thread_fence(memory_order_acquire);
3797 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003798 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003799 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003800 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003801 exitRequested = true;
3802 }
3803 }
3804
3805public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003806 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003807 : impl(impl),
3808 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003809 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003810 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003811 exitRequested(false),
3812 code(0),
3813 data(NULL),
3814 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003815 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003816
Jesse Hallb154c422014-07-13 12:47:02 -07003817 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003818 status_t waitForResponse() {
3819 do {
3820 looper->pollOnce(-1);
3821 } while (!exitRequested);
3822 return result;
3823 }
3824
Jesse Hallb154c422014-07-13 12:47:02 -07003825 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003826 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003827 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003829 // Ensure this->result is visible to the binder thread before it
3830 // handles the message.
3831 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003832 looper->sendMessage(this, Message(MSG_EXIT));
3833 }
3834};
3835
3836
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003837status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3838 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003839 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003840 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003841 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003842
3843 if (CC_UNLIKELY(display == 0))
3844 return BAD_VALUE;
3845
3846 if (CC_UNLIKELY(producer == 0))
3847 return BAD_VALUE;
3848
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003849 // if we have secure windows on this display, never allow the screen capture
3850 // unless the producer interface is local (i.e.: we can take a screenshot for
3851 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003852 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003853
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003854 // Convert to surfaceflinger's internal rotation type.
3855 Transform::orientation_flags rotationFlags;
3856 switch (rotation) {
3857 case ISurfaceComposer::eRotateNone:
3858 rotationFlags = Transform::ROT_0;
3859 break;
3860 case ISurfaceComposer::eRotate90:
3861 rotationFlags = Transform::ROT_90;
3862 break;
3863 case ISurfaceComposer::eRotate180:
3864 rotationFlags = Transform::ROT_180;
3865 break;
3866 case ISurfaceComposer::eRotate270:
3867 rotationFlags = Transform::ROT_270;
3868 break;
3869 default:
3870 rotationFlags = Transform::ROT_0;
3871 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3872 break;
3873 }
3874
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003875 class MessageCaptureScreen : public MessageBase {
3876 SurfaceFlinger* flinger;
3877 sp<IBinder> display;
3878 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003879 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003880 uint32_t reqWidth, reqHeight;
3881 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003882 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003883 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003884 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003885 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003886 public:
3887 MessageCaptureScreen(SurfaceFlinger* flinger,
3888 const sp<IBinder>& display,
3889 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003890 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003891 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003892 bool useIdentityTransform,
3893 Transform::orientation_flags rotation,
3894 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003895 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003896 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003898 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003899 rotation(rotation), result(PERMISSION_DENIED),
3900 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 {
3902 }
3903 status_t getResult() const {
3904 return result;
3905 }
3906 virtual bool handler() {
3907 Mutex::Autolock _l(flinger->mStateLock);
3908 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003909 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003910 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003911 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003912 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003913 return true;
3914 }
3915 };
3916
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003917 // this creates a "fake" BBinder which will serve as a "fake" remote
3918 // binder to receive the marshaled calls and forward them to the
3919 // real remote (a BpGraphicBufferProducer)
3920 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3921
3922 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3923 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003924 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003925 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003926 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003927 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003928
3929 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003931 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003932 }
3933 return res;
3934}
3935
Mathias Agopian180f10d2013-04-10 22:55:41 -07003936
3937void SurfaceFlinger::renderScreenImplLocked(
3938 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003939 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003940 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003941 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003942{
3943 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003944 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003945
3946 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003947 const int32_t hw_w = hw->getWidth();
3948 const int32_t hw_h = hw->getHeight();
3949 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003950 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003951
Dan Stozac1879002014-05-22 15:59:05 -07003952 // if a default or invalid sourceCrop is passed in, set reasonable values
3953 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3954 !sourceCrop.isValid()) {
3955 sourceCrop.setLeftTop(Point(0, 0));
3956 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3957 }
3958
3959 // ensure that sourceCrop is inside screen
3960 if (sourceCrop.left < 0) {
3961 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3962 }
Dan Stozabe31f442014-06-11 11:20:54 -07003963 if (sourceCrop.right > hw_w) {
3964 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003965 }
3966 if (sourceCrop.top < 0) {
3967 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3968 }
Dan Stozabe31f442014-06-11 11:20:54 -07003969 if (sourceCrop.bottom > hw_h) {
3970 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003971 }
3972
Mathias Agopian180f10d2013-04-10 22:55:41 -07003973 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003974 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003975
3976 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003977 engine.setViewportAndProjection(
3978 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003979 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003980
3981 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003982 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003983
Robert Carr1f0a16a2016-10-24 16:27:39 -07003984 // We loop through the first level of layers without traversing,
3985 // as we need to interpret min/max layer Z in the top level Z space.
3986 for (const auto& layer : mDrawingState.layersSortedByZ) {
3987 if (layer->getLayerStack() != hw->getLayerStack()) {
3988 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003989 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003990 const Layer::State& state(layer->getDrawingState());
3991 if (state.z < minLayerZ || state.z > maxLayerZ) {
3992 continue;
3993 }
3994 layer->traverseInZOrder([&](Layer* layer) {
3995 if (!layer->isVisible()) {
3996 return;
3997 }
3998 if (filtering) layer->setFiltering(true);
3999 layer->draw(hw, useIdentityTransform);
4000 if (filtering) layer->setFiltering(false);
4001 });
4002 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004003
Mathias Agopian931bda12013-08-28 18:11:46 -07004004 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004005}
4006
4007
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004008status_t SurfaceFlinger::captureScreenImplLocked(
4009 const sp<const DisplayDevice>& hw,
4010 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004011 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004012 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004013 bool useIdentityTransform, Transform::orientation_flags rotation,
4014 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004015{
4016 ATRACE_CALL();
4017
Mathias Agopian180f10d2013-04-10 22:55:41 -07004018 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004019 uint32_t hw_w = hw->getWidth();
4020 uint32_t hw_h = hw->getHeight();
4021
4022 if (rotation & Transform::ROT_90) {
4023 std::swap(hw_w, hw_h);
4024 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004025
Mathias Agopian180f10d2013-04-10 22:55:41 -07004026 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4027 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4028 reqWidth, reqHeight, hw_w, hw_h);
4029 return BAD_VALUE;
4030 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004031
Mathias Agopian180f10d2013-04-10 22:55:41 -07004032 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4033 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4034
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004035 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004036 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004037 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004038 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4039 (state.z < minLayerZ || state.z > maxLayerZ)) {
4040 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004041 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004042 layer->traverseInZOrder([&](Layer *layer) {
4043 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4044 layer->isSecure());
4045 });
4046 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004047
4048 if (!isLocalScreenshot && secureLayerIsVisible) {
4049 ALOGW("FB is protected: PERMISSION_DENIED");
4050 return PERMISSION_DENIED;
4051 }
4052
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004053 // create a surface (because we're a producer, and we need to
4054 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004055 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004056
4057 // Put the screenshot Surface into async mode so that
4058 // Layer::headFenceHasSignaled will always return true and we'll latch the
4059 // first buffer regardless of whether or not its acquire fence has
4060 // signaled. This is needed to avoid a race condition in the rotation
4061 // animation. See b/30209608
4062 sur->setAsyncMode(true);
4063
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004064 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004065
Michael Lentine5a16a622015-05-21 13:48:24 -07004066 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4067 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004068 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4069 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004070
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004071 int err = 0;
4072 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004073 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4075 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004076
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004077 if (err == NO_ERROR) {
4078 ANativeWindowBuffer* buffer;
4079 /* TODO: Once we have the sync framework everywhere this can use
4080 * server-side waits on the fence that dequeueBuffer returns.
4081 */
4082 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4083 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004084 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004085 // create an EGLImage from the buffer so we can later
4086 // turn it into a texture
4087 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4088 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4089 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004090 // this binds the given EGLImage as a framebuffer for the
4091 // duration of this scope.
4092 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4093 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004094 // this will in fact render into our dequeued buffer
4095 // via an FBO, which means we didn't have to create
4096 // an EGLSurface and therefore we're not
4097 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004098 renderScreenImplLocked(
4099 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4100 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004101
Riley Andrews86639902014-08-15 12:27:24 -07004102 // Attempt to create a sync khr object that can produce a sync point. If that
4103 // isn't available, create a non-dupable sync object in the fallback path and
4104 // wait on it directly.
4105 EGLSyncKHR sync;
4106 if (!DEBUG_SCREENSHOTS) {
4107 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004108 // native fence fd will not be populated until flush() is done.
4109 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004110 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004111 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004112 }
Riley Andrews86639902014-08-15 12:27:24 -07004113 if (sync != EGL_NO_SYNC_KHR) {
4114 // get the sync fd
4115 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4116 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4117 ALOGW("captureScreen: failed to dup sync khr object");
4118 syncFd = -1;
4119 }
4120 eglDestroySyncKHR(mEGLDisplay, sync);
4121 } else {
4122 // fallback path
4123 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4124 if (sync != EGL_NO_SYNC_KHR) {
4125 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4126 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4127 EGLint eglErr = eglGetError();
4128 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4129 ALOGW("captureScreen: fence wait timed out");
4130 } else {
4131 ALOGW_IF(eglErr != EGL_SUCCESS,
4132 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4133 }
4134 eglDestroySyncKHR(mEGLDisplay, sync);
4135 } else {
4136 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4137 }
4138 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004139 if (DEBUG_SCREENSHOTS) {
4140 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4141 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4142 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4143 hw, minLayerZ, maxLayerZ);
4144 delete [] pixels;
4145 }
4146
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004147 } else {
4148 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4149 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004150 window->cancelBuffer(window, buffer, syncFd);
4151 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004152 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004153 // destroy our image
4154 eglDestroyImageKHR(mEGLDisplay, image);
4155 } else {
4156 result = BAD_VALUE;
4157 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004158 if (buffer) {
4159 // queueBuffer takes ownership of syncFd
4160 result = window->queueBuffer(window, buffer, syncFd);
4161 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004162 }
4163 } else {
4164 result = BAD_VALUE;
4165 }
4166 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4167 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004168
Mathias Agopian74c40c02010-09-29 13:02:36 -07004169 return result;
4170}
4171
Mathias Agopiand5556842013-09-19 17:08:37 -07004172void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004173 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004174 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004175 for (size_t y=0 ; y<h ; y++) {
4176 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4177 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004178 if (p[x] != 0xFF000000) return;
4179 }
4180 }
4181 ALOGE("*** we just took a black screenshot ***\n"
4182 "requested minz=%d, maxz=%d, layerStack=%d",
4183 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004184
Robert Carr2047fae2016-11-28 14:09:09 -08004185 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004186 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004187 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004188 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4189 state.z <= maxLayerZ) {
4190 layer->traverseInZOrder([&](Layer* layer) {
4191 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4192 layer->isVisible() ? '+' : '-',
4193 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004194 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004195 i++;
4196 });
4197 }
4198 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004199 }
4200}
4201
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004202// ---------------------------------------------------------------------------
4203
Robert Carr2047fae2016-11-28 14:09:09 -08004204void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4205 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004206}
4207
Robert Carr2047fae2016-11-28 14:09:09 -08004208void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4209 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004210}
4211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004212}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004213
4214
4215#if defined(__gl_h_)
4216#error "don't include gl/gl.h in this file"
4217#endif
4218
4219#if defined(__gl2_h_)
4220#error "don't include gl2/gl2.h in this file"
4221#endif