blob: 62c9f25da3985bef32220e903f77014390bb5b1b [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),
Robert Carr0d480722017-01-10 16:42:54 -0800170 mInterceptor(this),
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);
Robert Carr0d480722017-01-10 16:42:54 -0800632 return authenticateSurfaceTextureLocked(bufferProducer);
633}
634
635bool SurfaceFlinger::authenticateSurfaceTextureLocked(
636 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800637 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700638 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800639}
640
Brian Anderson069b3652016-07-22 10:32:47 -0700641status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700642 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700643 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700644 FrameEvent::REQUESTED_PRESENT,
645 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700646 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700647 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700648 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700649 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700650 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700651 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700652 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700653 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700654 };
655 return NO_ERROR;
656}
657
Dan Stoza7f7da322014-05-02 15:26:25 -0700658status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
659 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700660 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700661 return BAD_VALUE;
662 }
663
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500664 if (!display.get())
665 return NAME_NOT_FOUND;
666
Jesse Hall692c7232012-11-08 15:41:56 -0800667 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700668 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800669 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700670 type = i;
671 break;
672 }
673 }
674
675 if (type < 0) {
676 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700677 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700678
Mathias Agopian8b736f12012-08-13 17:54:26 -0700679 // TODO: Not sure if display density should handled by SF any longer
680 class Density {
681 static int getDensityFromProperty(char const* propName) {
682 char property[PROPERTY_VALUE_MAX];
683 int density = 0;
684 if (property_get(propName, property, NULL) > 0) {
685 density = atoi(property);
686 }
687 return density;
688 }
689 public:
690 static int getEmuDensity() {
691 return getDensityFromProperty("qemu.sf.lcd_density"); }
692 static int getBuildDensity() {
693 return getDensityFromProperty("ro.sf.lcd_density"); }
694 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700695
Dan Stoza7f7da322014-05-02 15:26:25 -0700696 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700697
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700699 DisplayInfo info = DisplayInfo();
700
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 float xdpi = hwConfig->getDpiX();
702 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700703
704 if (type == DisplayDevice::DISPLAY_PRIMARY) {
705 // The density of the device is provided by a build property
706 float density = Density::getBuildDensity() / 160.0f;
707 if (density == 0) {
708 // the build doesn't provide a density -- this is wrong!
709 // use xdpi instead
710 ALOGE("ro.sf.lcd_density must be defined as a build property");
711 density = xdpi / 160.0f;
712 }
713 if (Density::getEmuDensity()) {
714 // if "qemu.sf.lcd_density" is specified, it overrides everything
715 xdpi = ydpi = density = Density::getEmuDensity();
716 density /= 160.0f;
717 }
718 info.density = density;
719
720 // TODO: this needs to go away (currently needed only by webkit)
721 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
722 info.orientation = hw->getOrientation();
723 } else {
724 // TODO: where should this value come from?
725 static const int TV_DENSITY = 213;
726 info.density = TV_DENSITY / 160.0f;
727 info.orientation = 0;
728 }
729
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 info.w = hwConfig->getWidth();
731 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700732 info.xdpi = xdpi;
733 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900735 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800736
Andy McFadden91b2ca82014-06-13 14:04:23 -0700737 // This is how far in advance a buffer must be queued for
738 // presentation at a given time. If you want a buffer to appear
739 // on the screen at time N, you must submit the buffer before
740 // (N - presentationDeadline).
741 //
742 // Normally it's one full refresh period (to give SF a chance to
743 // latch the buffer), but this can be reduced by configuring a
744 // DispSync offset. Any additional delays introduced by the hardware
745 // composer or panel must be accounted for here.
746 //
747 // We add an additional 1ms to allow for processing time and
748 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 info.presentationDeadline = hwConfig->getVsyncPeriod() -
750 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700751
752 // All non-virtual displays are currently considered secure.
753 info.secure = true;
754
Michael Wright28f24d02016-07-12 13:30:53 -0700755 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 }
757
Dan Stoza7f7da322014-05-02 15:26:25 -0700758 return NO_ERROR;
759}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700760
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800761status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700762 DisplayStatInfo* stats) {
763 if (stats == NULL) {
764 return BAD_VALUE;
765 }
766
767 // FIXME for now we always return stats for the primary display
768 memset(stats, 0, sizeof(*stats));
769 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
770 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
771 return NO_ERROR;
772}
773
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700774int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800775 if (display == NULL) {
776 ALOGE("%s : display is NULL", __func__);
777 return BAD_VALUE;
778 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700779 sp<DisplayDevice> device(getDisplayDevice(display));
780 if (device != NULL) {
781 return device->getActiveConfig();
782 }
783 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700784}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700785
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700786void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
787 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
788 this);
789 int32_t type = hw->getDisplayType();
790 int currentMode = hw->getActiveConfig();
791
792 if (mode == currentMode) {
793 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
794 return;
795 }
796
797 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
798 ALOGW("Trying to set config for virtual display");
799 return;
800 }
801
802 hw->setActiveConfig(mode);
803 getHwComposer().setActiveConfig(type, mode);
804}
805
806status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
807 class MessageSetActiveConfig: public MessageBase {
808 SurfaceFlinger& mFlinger;
809 sp<IBinder> mDisplay;
810 int mMode;
811 public:
812 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
813 int mode) :
814 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
815 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700816 Vector<DisplayInfo> configs;
817 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700818 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700819 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700820 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700821 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700822 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700823 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
824 if (hw == NULL) {
825 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700826 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700827 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
828 ALOGW("Attempt to set active config = %d for virtual display",
829 mMode);
830 } else {
831 mFlinger.setActiveConfigInternal(hw, mMode);
832 }
833 return true;
834 }
835 };
836 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
837 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700838 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700839}
Michael Wright28f24d02016-07-12 13:30:53 -0700840status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
841 Vector<android_color_mode_t>* outColorModes) {
842 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
843 return BAD_VALUE;
844 }
845
846 if (!display.get()) {
847 return NAME_NOT_FOUND;
848 }
849
850 int32_t type = NAME_NOT_FOUND;
851 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
852 if (display == mBuiltinDisplays[i]) {
853 type = i;
854 break;
855 }
856 }
857
858 if (type < 0) {
859 return type;
860 }
861
862 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
863 outColorModes->clear();
864 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
865
866 return NO_ERROR;
867}
868
869android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
870 sp<DisplayDevice> device(getDisplayDevice(display));
871 if (device != nullptr) {
872 return device->getActiveColorMode();
873 }
874 return static_cast<android_color_mode_t>(BAD_VALUE);
875}
876
877void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
878 android_color_mode_t mode) {
879 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
880 this);
881 int32_t type = hw->getDisplayType();
882 android_color_mode_t currentMode = hw->getActiveColorMode();
883
884 if (mode == currentMode) {
885 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
886 return;
887 }
888
889 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
890 ALOGW("Trying to set config for virtual display");
891 return;
892 }
893
894 hw->setActiveColorMode(mode);
895 getHwComposer().setActiveColorMode(type, mode);
896}
897
898
899status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
900 android_color_mode_t colorMode) {
901 class MessageSetActiveColorMode: public MessageBase {
902 SurfaceFlinger& mFlinger;
903 sp<IBinder> mDisplay;
904 android_color_mode_t mMode;
905 public:
906 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
907 android_color_mode_t mode) :
908 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
909 virtual bool handler() {
910 Vector<android_color_mode_t> modes;
911 mFlinger.getDisplayColorModes(mDisplay, &modes);
912 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
913 if (mMode < 0 || !exists) {
914 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
915 mDisplay.get());
916 return true;
917 }
918 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
919 if (hw == nullptr) {
920 ALOGE("Attempt to set active color mode = %d for null display %p",
921 mMode, mDisplay.get());
922 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
923 ALOGW("Attempt to set active color mode= %d for virtual display",
924 mMode);
925 } else {
926 mFlinger.setActiveColorModeInternal(hw, mMode);
927 }
928 return true;
929 }
930 };
931 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
932 postMessageSync(msg);
933 return NO_ERROR;
934}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700935
Svetoslavd85084b2014-03-20 10:28:31 -0700936status_t SurfaceFlinger::clearAnimationFrameStats() {
937 Mutex::Autolock _l(mStateLock);
938 mAnimFrameTracker.clearStats();
939 return NO_ERROR;
940}
941
942status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
943 Mutex::Autolock _l(mStateLock);
944 mAnimFrameTracker.getStats(outStats);
945 return NO_ERROR;
946}
947
Dan Stozac4f471e2016-03-24 09:31:08 -0700948status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
949 HdrCapabilities* outCapabilities) const {
950 Mutex::Autolock _l(mStateLock);
951
952 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
953 if (displayDevice == nullptr) {
954 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
955 return BAD_VALUE;
956 }
957
958 std::unique_ptr<HdrCapabilities> capabilities =
959 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
960 if (capabilities) {
961 std::swap(*outCapabilities, *capabilities);
962 } else {
963 return BAD_VALUE;
964 }
965
966 return NO_ERROR;
967}
968
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700969status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
970 if (enable == mInjectVSyncs) {
971 return NO_ERROR;
972 }
973
974 if (enable) {
975 mInjectVSyncs = enable;
976 ALOGV("VSync Injections enabled");
977 if (mVSyncInjector.get() == nullptr) {
978 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700979 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700980 }
981 mEventQueue.setEventThread(mInjectorEventThread);
982 } else {
983 mInjectVSyncs = enable;
984 ALOGV("VSync Injections disabled");
985 mEventQueue.setEventThread(mSFEventThread);
986 mVSyncInjector.clear();
987 }
988 return NO_ERROR;
989}
990
991status_t SurfaceFlinger::injectVSync(nsecs_t when) {
992 if (!mInjectVSyncs) {
993 ALOGE("VSync Injections not enabled");
994 return BAD_VALUE;
995 }
996 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
997 ALOGV("Injecting VSync inside SurfaceFlinger");
998 mVSyncInjector->onInjectSyncEvent(when);
999 }
1000 return NO_ERROR;
1001}
1002
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001003// ----------------------------------------------------------------------------
1004
1005sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001006 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001007}
1008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001010
1011void SurfaceFlinger::waitForEvent() {
1012 mEventQueue.waitMessage();
1013}
1014
1015void SurfaceFlinger::signalTransaction() {
1016 mEventQueue.invalidate();
1017}
1018
1019void SurfaceFlinger::signalLayerUpdate() {
1020 mEventQueue.invalidate();
1021}
1022
1023void SurfaceFlinger::signalRefresh() {
1024 mEventQueue.refresh();
1025}
1026
1027status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue.postMessage(msg, reltime);
1030}
1031
1032status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001033 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001034 status_t res = mEventQueue.postMessage(msg, reltime);
1035 if (res == NO_ERROR) {
1036 msg->wait();
1037 }
1038 return res;
1039}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001041void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001042 do {
1043 waitForEvent();
1044 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045}
1046
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001047void SurfaceFlinger::enableHardwareVsync() {
1048 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001049 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001051 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1052 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001054 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055}
1056
Jesse Hall948fe0c2013-10-14 12:56:09 -07001057void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001058 Mutex::Autolock _l(mHWVsyncLock);
1059
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060 if (makeAvailable) {
1061 mHWVsyncAvailable = true;
1062 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001063 // Hardware vsync is not currently available, so abort the resync
1064 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001065 return;
1066 }
1067
Dan Stoza9e56aa02015-11-02 13:00:03 -08001068 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1069 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070
1071 mPrimaryDispSync.reset();
1072 mPrimaryDispSync.setPeriod(period);
1073
1074 if (!mPrimaryHWVsyncEnabled) {
1075 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001076 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1077 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078 mPrimaryHWVsyncEnabled = true;
1079 }
1080}
1081
Jesse Hall948fe0c2013-10-14 12:56:09 -07001082void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 Mutex::Autolock _l(mHWVsyncLock);
1084 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001085 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1086 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087 mPrimaryDispSync.endResync();
1088 mPrimaryHWVsyncEnabled = false;
1089 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001090 if (makeUnavailable) {
1091 mHWVsyncAvailable = false;
1092 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093}
1094
Tim Murray4a4e4a22016-04-19 16:29:23 +00001095void SurfaceFlinger::resyncWithRateLimit() {
1096 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1097 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001098 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001099 }
1100}
1101
Steven Thomas3cfac282017-02-06 12:29:30 -08001102void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1103 nsecs_t timestamp) {
1104 Mutex::Autolock lock(mStateLock);
1105 // Ignore any vsyncs from the non-active hardware composer.
1106 if (composer != mHwc) {
1107 return;
1108 }
1109
Jamie Gennisd1700752013-10-14 12:22:52 -07001110 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111
Jamie Gennisd1700752013-10-14 12:22:52 -07001112 { // Scope for the lock
1113 Mutex::Autolock _l(mHWVsyncLock);
1114 if (type == 0 && mPrimaryHWVsyncEnabled) {
1115 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001117 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001118
1119 if (needsHwVsync) {
1120 enableHardwareVsync();
1121 } else {
1122 disableHardwareVsync(false);
1123 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001124}
1125
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001126void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1127 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1128 *compositorTiming = mCompositorTiming;
1129}
1130
Dan Stoza9e56aa02015-11-02 13:00:03 -08001131void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1132 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1133 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1134 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136 // All non-virtual displays are currently considered secure.
1137 bool isSecure = true;
1138
1139 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001140
1141 // When we're using the vr composer, the assumption is that we've
1142 // already created the IBinder object for the primary display.
1143 if (!mHwc->isUsingVrComposer()) {
1144 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1145 }
1146
Dan Stoza9e56aa02015-11-02 13:00:03 -08001147 wp<IBinder> token = mBuiltinDisplays[type];
1148
1149 sp<IGraphicBufferProducer> producer;
1150 sp<IGraphicBufferConsumer> consumer;
1151 BufferQueue::createBufferQueue(&producer, &consumer,
1152 new GraphicBufferAlloc());
1153
1154 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1155 DisplayDevice::DISPLAY_PRIMARY, consumer);
1156 sp<DisplayDevice> hw = new DisplayDevice(this,
1157 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1158 producer, mRenderEngine->getEGLConfig());
1159 mDisplays.add(token, hw);
1160 } else {
1161 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001162 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001163 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001164 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001165 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001166 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1167 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001168 }
1169 setTransactionFlags(eDisplayTransactionNeeded);
1170
Andy McFadden9e9689c2012-10-10 18:17:51 -07001171 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001172 }
Mathias Agopian86303202012-07-24 22:46:10 -07001173}
1174
Steven Thomas3cfac282017-02-06 12:29:30 -08001175void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1176 Mutex::Autolock lock(mStateLock);
1177 if (composer == mHwc) {
1178 repaintEverything();
1179 } else {
1180 // This isn't from our current hardware composer. If it's a callback
1181 // from the real composer, forward the refresh request to vr
1182 // flinger. Otherwise ignore it.
1183 if (!composer->isUsingVrComposer()) {
1184 mVrFlinger->OnHardwareComposerRefresh();
1185 }
1186 }
1187}
1188
Dan Stoza9e56aa02015-11-02 13:00:03 -08001189void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001191 getHwComposer().setVsyncEnabled(disp,
1192 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001193}
1194
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001195void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1196 for (size_t i = 0; i < layers.size(); ++i) {
1197 layers[i]->clearHwcLayers();
1198 }
1199}
1200
1201void SurfaceFlinger::resetHwc() {
1202 disableHardwareVsync(true);
1203 clearHwcLayers(mDrawingState.layersSortedByZ);
1204 clearHwcLayers(mCurrentState.layersSortedByZ);
1205 // Clear the drawing state so that the logic inside of
1206 // handleTransactionLocked will fire. It will determine the delta between
1207 // mCurrentState and mDrawingState and re-apply all changes when we make the
1208 // transition.
1209 mDrawingState.displays.clear();
1210 mDisplays.clear();
1211}
1212
1213void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001214 bool enteringVrMode = mEnterVrMode;
1215 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1216 return;
1217 }
1218 if (enteringVrMode && !mVrHwc) {
1219 // Construct new HWComposer without holding any locks.
1220 mVrHwc = new HWComposer(true);
1221 ALOGV("Vr HWC created");
1222 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001223 {
1224 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001225
1226 if (enteringVrMode) {
1227 // Start vrflinger thread, if it hasn't been started already.
1228 if (!mVrFlinger) {
1229 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1230 int err = mVrFlinger->Run(mHwc->getComposer());
1231 if (err != NO_ERROR) {
1232 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1233 mVrFlinger.reset();
1234 mEnterVrMode = false;
1235 return;
1236 }
1237 }
1238
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001239 resetHwc();
1240
1241 mHwc = mVrHwc;
1242 mVrFlinger->EnterVrMode();
1243 } else {
1244 mVrFlinger->ExitVrMode();
1245
1246 resetHwc();
1247
1248 mHwc = mRealHwc;
1249 enableHardwareVsync();
1250 }
1251
1252 mVisibleRegionsDirty = true;
1253 invalidateHwcGeometry();
1254 android_atomic_or(1, &mRepaintEverything);
1255 setTransactionFlags(eDisplayTransactionNeeded);
1256 }
1257 if (mVrHwc) {
1258 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1259 }
1260}
1261
Mathias Agopian4fec8732012-06-29 14:12:52 -07001262void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001263 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001265 case MessageQueue::INVALIDATE: {
Corey Tabakace2c1982017-02-15 17:07:20 -08001266 // TODO(eieio): Disabled until SELinux issues are resolved.
1267 //updateVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001268
Dan Stoza50182882016-07-08 12:02:20 -07001269 bool frameMissed = !mHadClientComposition &&
1270 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001271 (mPreviousPresentFence->getSignalTime() ==
1272 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001273 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001274 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001275 signalLayerUpdate();
1276 break;
1277 }
1278
Dan Stoza6b9454d2014-11-07 16:00:59 -08001279 bool refreshNeeded = handleMessageTransaction();
1280 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001281 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001283 // Signal a refresh if a transaction modified the window state,
1284 // a new buffer was latched, or if HWC has requested a full
1285 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001286 signalRefresh();
1287 }
1288 break;
1289 }
1290 case MessageQueue::REFRESH: {
1291 handleMessageRefresh();
1292 break;
1293 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001294 }
1295}
1296
Dan Stoza6b9454d2014-11-07 16:00:59 -08001297bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001298 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001299 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001300 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001301 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001302 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001303 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001304}
1305
Dan Stoza6b9454d2014-11-07 16:00:59 -08001306bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001307 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001308 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001309}
1310
1311void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001312 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001313
Pablo Ceballos40845df2016-01-25 17:41:15 -08001314 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001315
Brian Andersond6927fb2016-07-23 23:37:30 -07001316 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001317 rebuildLayerStacks();
1318 setUpHWComposer();
1319 doDebugFlashRegions();
1320 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001321 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001322
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001323 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001324
1325 mHadClientComposition = false;
1326 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1327 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1328 mHadClientComposition = mHadClientComposition ||
1329 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1330 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001331
Dan Stoza9e56aa02015-11-02 13:00:03 -08001332 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001334
Mathias Agopiancd60f992012-08-16 16:28:27 -07001335void SurfaceFlinger::doDebugFlashRegions()
1336{
1337 // is debugging enabled
1338 if (CC_LIKELY(!mDebugRegion))
1339 return;
1340
1341 const bool repaintEverything = mRepaintEverything;
1342 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1343 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001344 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001345 // transform the dirty region into this screen's coordinate space
1346 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1347 if (!dirtyRegion.isEmpty()) {
1348 // redraw the whole screen
1349 doComposeSurfaces(hw, Region(hw->bounds()));
1350
1351 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001352 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001353 RenderEngine& engine(getRenderEngine());
1354 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1355
Mathias Agopianda27af92012-09-13 18:17:13 -07001356 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001357 }
1358 }
1359 }
1360
1361 postFramebuffer();
1362
1363 if (mDebugRegion > 1) {
1364 usleep(mDebugRegion * 1000);
1365 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001366
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001368 auto& displayDevice = mDisplays[displayId];
1369 if (!displayDevice->isDisplayOn()) {
1370 continue;
1371 }
1372
1373 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1375 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001376 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001377}
1378
Brian Andersond6927fb2016-07-23 23:37:30 -07001379void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381 ATRACE_CALL();
1382 ALOGV("preComposition");
1383
Mathias Agopiancd60f992012-08-16 16:28:27 -07001384 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001385 mDrawingState.traverseInZOrder([&](Layer* layer) {
1386 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387 needExtraInvalidate = true;
1388 }
Robert Carr2047fae2016-11-28 14:09:09 -08001389 });
1390
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391 if (needExtraInvalidate) {
1392 signalLayerUpdate();
1393 }
1394}
1395
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396void SurfaceFlinger::updateCompositorTiming(
1397 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1398 std::shared_ptr<FenceTime>& presentFenceTime) {
1399 // Update queue of past composite+present times and determine the
1400 // most recently known composite to present latency.
1401 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1402 nsecs_t compositeToPresentLatency = -1;
1403 while (!mCompositePresentTimes.empty()) {
1404 CompositePresentTime& cpt = mCompositePresentTimes.front();
1405 // Cached values should have been updated before calling this method,
1406 // which helps avoid duplicate syscalls.
1407 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1408 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1409 break;
1410 }
1411 compositeToPresentLatency = displayTime - cpt.composite;
1412 mCompositePresentTimes.pop();
1413 }
1414
1415 // Don't let mCompositePresentTimes grow unbounded, just in case.
1416 while (mCompositePresentTimes.size() > 16) {
1417 mCompositePresentTimes.pop();
1418 }
1419
1420 // Integer division and modulo round toward 0 not -inf, so we need to
1421 // treat negative and positive offsets differently.
1422 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1423 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1424 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1425
1426 // Snap the latency to a value that removes scheduling jitter from the
1427 // composition and present times, which often have >1ms of jitter.
1428 // Reducing jitter is important if an app attempts to extrapolate
1429 // something (such as user input) to an accurate diasplay time.
1430 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1431 // with (presentLatency % interval).
1432 nsecs_t snappedCompositeToPresentLatency = -1;
1433 if (compositeToPresentLatency >= 0) {
1434 nsecs_t bias = vsyncInterval / 2;
1435 int64_t extraVsyncs =
1436 (compositeToPresentLatency - idealLatency + bias) /
1437 vsyncInterval;
1438 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1439 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1440 }
1441
1442 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1443 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1444 mCompositorTiming.interval = vsyncInterval;
1445 if (snappedCompositeToPresentLatency >= 0) {
1446 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1447 }
1448}
1449
1450void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001452 ATRACE_CALL();
1453 ALOGV("postComposition");
1454
Brian Anderson3546a3f2016-07-14 11:51:14 -07001455 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001456 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001457 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001458 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001459 }
1460
Brian Andersond6927fb2016-07-23 23:37:30 -07001461 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001462
1463 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1464 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1465 glCompositionDoneFenceTime =
1466 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1467 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1468 } else {
1469 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1470 }
1471 mGlCompositionDoneTimeline.updateSignalTimes();
1472
1473 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1474 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1475 mDisplayTimeline.push(displayFenceTime);
1476 mDisplayTimeline.updateSignalTimes();
1477
1478 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1479 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1480 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1481 presentFenceTime = &displayFenceTime;
1482 } else {
1483 retireFenceTime = &displayFenceTime;
1484 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001485
1486 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1487 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1488
1489 // We use the refreshStartTime which might be sampled a little later than
1490 // when we started doing work for this frame, but that should be okay
1491 // since updateCompositorTiming has snapping logic.
1492 updateCompositorTiming(
1493 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1494
Robert Carr2047fae2016-11-28 14:09:09 -08001495 mDrawingState.traverseInZOrder([&](Layer* layer) {
1496 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001498 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001499 recordBufferingStats(layer->getName().string(),
1500 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001501 }
Robert Carr2047fae2016-11-28 14:09:09 -08001502 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001503
Brian Anderson3d4039d2016-09-23 16:31:30 -07001504 if (displayFence->isValid()) {
1505 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001506 enableHardwareVsync();
1507 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001508 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001509 }
1510 }
1511
Andy McFadden5167ec62014-05-22 13:08:43 -07001512 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001513 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001514 enableHardwareVsync();
1515 }
1516 }
1517
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001518 if (mAnimCompositionPending) {
1519 mAnimCompositionPending = false;
1520
Brian Anderson3d4039d2016-09-23 16:31:30 -07001521 if (displayFenceTime->isValid()) {
1522 mAnimFrameTracker.setActualPresentFence(
1523 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001524 } else {
1525 // The HWC doesn't support present fences, so use the refresh
1526 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001527 nsecs_t presentTime =
1528 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001529 mAnimFrameTracker.setActualPresentTime(presentTime);
1530 }
1531 mAnimFrameTracker.advanceFrame();
1532 }
Dan Stozab90cf072015-03-05 11:05:59 -08001533
1534 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1535 return;
1536 }
1537
1538 nsecs_t currentTime = systemTime();
1539 if (mHasPoweredOff) {
1540 mHasPoweredOff = false;
1541 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001542 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001543 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001544 if (numPeriods < NUM_BUCKETS - 1) {
1545 mFrameBuckets[numPeriods] += elapsedTime;
1546 } else {
1547 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1548 }
1549 mTotalTime += elapsedTime;
1550 }
1551 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552}
1553
1554void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001555 ATRACE_CALL();
1556 ALOGV("rebuildLayerStacks");
1557
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001559 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001561 mVisibleRegionsDirty = false;
1562 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001563
Mathias Agopian92a979a2012-08-02 18:32:23 -07001564 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001565 Region opaqueRegion;
1566 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 Vector<sp<Layer>> layersSortedByZ;
1568 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1569 const Transform& tr(displayDevice->getTransform());
1570 const Rect bounds(displayDevice->getBounds());
1571 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001572 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001573 displayDevice->getLayerStack(), dirtyRegion,
1574 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001575
Robert Carr2047fae2016-11-28 14:09:09 -08001576 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001577 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001578 Region drawRegion(tr.transform(
1579 layer->visibleNonTransparentRegion));
1580 drawRegion.andSelf(bounds);
1581 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001582 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001583 } else {
1584 // Clear out the HWC layer if this layer was
1585 // previously visible, but no longer is
1586 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1587 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001588 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001589 }
Robert Carr2047fae2016-11-28 14:09:09 -08001590 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001591 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1593 displayDevice->undefinedRegion.set(bounds);
1594 displayDevice->undefinedRegion.subtractSelf(
1595 tr.transform(opaqueRegion));
1596 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001597 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001598 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001600
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001602 ATRACE_CALL();
1603 ALOGV("setUpHWComposer");
1604
Jesse Hall028dc8f2013-08-20 16:35:32 -07001605 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001606 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1607 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1608 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1609
1610 // If nothing has changed (!dirty), don't recompose.
1611 // If something changed, but we don't currently have any visible layers,
1612 // and didn't when we last did a composition, then skip it this time.
1613 // The second rule does two things:
1614 // - When all layers are removed from a display, we'll emit one black
1615 // frame, then nothing more until we get new layers.
1616 // - When a display is created with a private layer stack, we won't
1617 // emit any black frames until a layer is added to the layer stack.
1618 bool mustRecompose = dirty && !(empty && wasEmpty);
1619
1620 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1621 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1622 mustRecompose ? "doing" : "skipping",
1623 dirty ? "+" : "-",
1624 empty ? "+" : "-",
1625 wasEmpty ? "+" : "-");
1626
Dan Stoza71433162014-02-04 16:22:36 -08001627 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001628
1629 if (mustRecompose) {
1630 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1631 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001632 }
1633
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 // build the h/w work list
1635 if (CC_UNLIKELY(mGeometryInvalid)) {
1636 mGeometryInvalid = false;
1637 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1638 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1639 const auto hwcId = displayDevice->getHwcDisplayId();
1640 if (hwcId >= 0) {
1641 const Vector<sp<Layer>>& currentLayers(
1642 displayDevice->getVisibleLayersSortedByZ());
1643 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001644 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001645 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 if (!layer->hasHwcLayer(hwcId)) {
1647 auto hwcLayer = mHwc->createLayer(hwcId);
1648 if (hwcLayer) {
1649 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1650 } else {
1651 layer->forceClientComposition(hwcId);
1652 foundLayerWithoutHwc = true;
1653 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001654 }
1655 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001656
Robert Carrae060832016-11-28 10:51:00 -08001657 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001658 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001660 }
1661 }
1662 }
1663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 }
Riley Andrews03414a12014-07-01 14:22:59 -07001665
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001666
1667 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1668
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 // Set the per-frame data
1670 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1671 auto& displayDevice = mDisplays[displayId];
1672 const auto hwcId = displayDevice->getHwcDisplayId();
1673 if (hwcId < 0) {
1674 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001675 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001676 if (colorMatrix != mPreviousColorMatrix) {
1677 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1678 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1679 "display %zd: %d", displayId, result);
1680 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1682 layer->setPerFrameData(displayDevice);
1683 }
1684 }
1685
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001686 mPreviousColorMatrix = colorMatrix;
1687
Dan Stoza9e56aa02015-11-02 13:00:03 -08001688 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001689 auto& displayDevice = mDisplays[displayId];
1690 if (!displayDevice->isDisplayOn()) {
1691 continue;
1692 }
1693
1694 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1696 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001697 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001699
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700void SurfaceFlinger::doComposition() {
1701 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 ALOGV("doComposition");
1703
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001704 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001705 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001706 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001707 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708 // transform the dirty region into this screen's coordinate space
1709 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001710
1711 // repaint the framebuffer (if needed)
1712 doDisplayComposition(hw, dirtyRegion);
1713
Mathias Agopiancd60f992012-08-16 16:28:27 -07001714 hw->dirtyRegion.clear();
1715 hw->flip(hw->swapRegion);
1716 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001717 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001718 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001719 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001720}
1721
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001722void SurfaceFlinger::postFramebuffer()
1723{
Mathias Agopian841cde52012-03-01 15:44:37 -08001724 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001725 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001726
Mathias Agopiana44b0412011-10-16 18:46:35 -07001727 const nsecs_t now = systemTime();
1728 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001729
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1731 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001732 if (!displayDevice->isDisplayOn()) {
1733 continue;
1734 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 const auto hwcId = displayDevice->getHwcDisplayId();
1736 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001737 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001738 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001739 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001740 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1742 sp<Fence> releaseFence = Fence::NO_FENCE;
1743 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1744 releaseFence = displayDevice->getClientTargetAcquireFence();
1745 } else {
1746 auto hwcLayer = layer->getHwcLayer(hwcId);
1747 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001748 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 layer->onLayerDisplayed(releaseFence);
1750 }
1751 if (hwcId >= 0) {
1752 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001753 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001754 }
1755
Mathias Agopiana44b0412011-10-16 18:46:35 -07001756 mLastSwapBufferTime = systemTime() - now;
1757 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001758
1759 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1760 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1761 logFrameStats();
1762 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001763}
1764
Mathias Agopian87baae12012-07-31 12:38:26 -07001765void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001766{
Mathias Agopian841cde52012-03-01 15:44:37 -08001767 ATRACE_CALL();
1768
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001769 // here we keep a copy of the drawing state (that is the state that's
1770 // going to be overwritten by handleTransactionLocked()) outside of
1771 // mStateLock so that the side-effects of the State assignment
1772 // don't happen with mStateLock held (which can cause deadlocks).
1773 State drawingState(mDrawingState);
1774
Mathias Agopianca4d3602011-05-19 15:38:14 -07001775 Mutex::Autolock _l(mStateLock);
1776 const nsecs_t now = systemTime();
1777 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001778
Mathias Agopianca4d3602011-05-19 15:38:14 -07001779 // Here we're guaranteed that some transaction flags are set
1780 // so we can call handleTransactionLocked() unconditionally.
1781 // We call getTransactionFlags(), which will also clear the flags,
1782 // with mStateLock held to guarantee that mCurrentState won't change
1783 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001784
Mathias Agopiane57f2922012-08-09 16:29:12 -07001785 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001786 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001787
Mathias Agopianca4d3602011-05-19 15:38:14 -07001788 mLastTransactionTime = systemTime() - now;
1789 mDebugInTransaction = 0;
1790 invalidateHwcGeometry();
1791 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001792}
1793
Mathias Agopian87baae12012-07-31 12:38:26 -07001794void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001795{
Dan Stoza7dde5992015-05-22 09:51:44 -07001796 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001797 mCurrentState.traverseInZOrder([](Layer* layer) {
1798 layer->notifyAvailableFrames();
1799 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001800
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801 /*
1802 * Traversal of the children
1803 * (perform the transaction for each of them if needed)
1804 */
1805
Mathias Agopian3559b072012-08-15 13:46:03 -07001806 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001807 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001808 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001809 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810
1811 const uint32_t flags = layer->doTransaction(0);
1812 if (flags & Layer::eVisibleRegion)
1813 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001814 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815 }
1816
1817 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001818 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819 */
1820
Mathias Agopiane57f2922012-08-09 16:29:12 -07001821 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001822 // here we take advantage of Vector's copy-on-write semantics to
1823 // improve performance by skipping the transaction entirely when
1824 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001825 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1826 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001827 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001829 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001830 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001831
1832 // find the displays that were removed
1833 // (ie: in drawing state but not in current state)
1834 // also handle displays that changed
1835 // (ie: displays that are in both lists)
1836 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001837 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1838 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001840 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001841 // Call makeCurrent() on the primary display so we can
1842 // be sure that nothing associated with this display
1843 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001844 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001845 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001846 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1847 if (hw != NULL)
1848 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001849 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001850 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001851 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001852 } else {
1853 ALOGW("trying to remove the main display");
1854 }
1855 } else {
1856 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001857 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001858 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001859 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1860 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001861 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001862 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001863 // recreating the DisplayDevice, so we just remove it
1864 // from the drawing state, so that it get re-added
1865 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001866 sp<DisplayDevice> hw(getDisplayDevice(display));
1867 if (hw != NULL)
1868 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001869 mDisplays.removeItem(display);
1870 mDrawingState.displays.removeItemsAt(i);
1871 dc--; i--;
1872 // at this point we must loop to the next item
1873 continue;
1874 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001875
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001876 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001877 if (disp != NULL) {
1878 if (state.layerStack != draw[i].layerStack) {
1879 disp->setLayerStack(state.layerStack);
1880 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001881 if ((state.orientation != draw[i].orientation)
1882 || (state.viewport != draw[i].viewport)
1883 || (state.frame != draw[i].frame))
1884 {
1885 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001886 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001887 }
Michael Lentine47e45402014-07-18 15:34:25 -07001888 if (state.width != draw[i].width || state.height != draw[i].height) {
1889 disp->setDisplaySize(state.width, state.height);
1890 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001891 }
1892 }
1893 }
1894
1895 // find displays that were added
1896 // (ie: in current state but not in drawing state)
1897 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001898 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001899 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001900
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001901 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001902 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001903 sp<IGraphicBufferProducer> bqProducer;
1904 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001905 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1906 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001907
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001909 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001910 // Virtual displays without a surface are dormant:
1911 // they have external state (layer stack, projection,
1912 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001913 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001914
Dan Stoza8cf150a2016-08-02 10:27:31 -07001915 if (mUseHwcVirtualDisplays) {
1916 int width = 0;
1917 int status = state.surface->query(
1918 NATIVE_WINDOW_WIDTH, &width);
1919 ALOGE_IF(status != NO_ERROR,
1920 "Unable to query width (%d)", status);
1921 int height = 0;
1922 status = state.surface->query(
1923 NATIVE_WINDOW_HEIGHT, &height);
1924 ALOGE_IF(status != NO_ERROR,
1925 "Unable to query height (%d)", status);
1926 int intFormat = 0;
1927 status = state.surface->query(
1928 NATIVE_WINDOW_FORMAT, &intFormat);
1929 ALOGE_IF(status != NO_ERROR,
1930 "Unable to query format (%d)", status);
1931 auto format = static_cast<android_pixel_format_t>(
1932 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001933
Dan Stoza8cf150a2016-08-02 10:27:31 -07001934 mHwc->allocateVirtualDisplay(width, height, &format,
1935 &hwcId);
1936 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937
Dan Stoza5cf424b2016-05-20 14:02:39 -07001938 // TODO: Plumb requested format back up to consumer
1939
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 sp<VirtualDisplaySurface> vds =
1941 new VirtualDisplaySurface(*mHwc,
1942 hwcId, state.surface, bqProducer,
1943 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001944
1945 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001946 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001947 }
1948 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001949 ALOGE_IF(state.surface!=NULL,
1950 "adding a supported display, but rendering "
1951 "surface is provided (%p), ignoring it",
1952 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001953
1954 hwcId = state.type;
1955 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1956 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001957 }
1958
1959 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001960 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001961 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 state.type, hwcId, state.isSecure, display,
1963 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001964 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001965 hw->setLayerStack(state.layerStack);
1966 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001967 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001968 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001969 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001971 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001972 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001973 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001974 }
1975 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001978
Mathias Agopian84300952012-11-21 16:02:13 -08001979 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1980 // The transform hint might have changed for some layers
1981 // (either because a display has changed, or because a layer
1982 // as changed).
1983 //
1984 // Walk through all the layers in currentLayers,
1985 // and update their transform hint.
1986 //
1987 // If a layer is visible only on a single display, then that
1988 // display is used to calculate the hint, otherwise we use the
1989 // default display.
1990 //
1991 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1992 // the hint is set before we acquire a buffer from the surface texture.
1993 //
1994 // NOTE: layer transactions have taken place already, so we use their
1995 // drawing state. However, SurfaceFlinger's own transaction has not
1996 // happened yet, so we must use the current state layer list
1997 // (soon to become the drawing state list).
1998 //
1999 sp<const DisplayDevice> disp;
2000 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002001 bool first = true;
2002 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002003 // NOTE: we rely on the fact that layers are sorted by
2004 // layerStack first (so we don't have to traverse the list
2005 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002006 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002007 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002008 currentlayerStack = layerStack;
2009 // figure out if this layerstack is mirrored
2010 // (more than one display) if so, pick the default display,
2011 // if not, pick the only display it's on.
2012 disp.clear();
2013 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2014 sp<const DisplayDevice> hw(mDisplays[dpy]);
2015 if (hw->getLayerStack() == currentlayerStack) {
2016 if (disp == NULL) {
2017 disp = hw;
2018 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002019 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002020 break;
2021 }
2022 }
2023 }
2024 }
Chet Haase91d25932013-04-11 15:24:55 -07002025 if (disp == NULL) {
2026 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2027 // redraw after transform hint changes. See bug 8508397.
2028
2029 // could be null when this layer is using a layerStack
2030 // that is not visible on any display. Also can occur at
2031 // screen off/on times.
2032 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002033 }
Chet Haase91d25932013-04-11 15:24:55 -07002034 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002035
2036 first = false;
2037 });
Mathias Agopian84300952012-11-21 16:02:13 -08002038 }
2039
2040
Mathias Agopian3559b072012-08-15 13:46:03 -07002041 /*
2042 * Perform our own transaction if needed
2043 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002044
2045 if (mLayersAdded) {
2046 mLayersAdded = false;
2047 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002048 mVisibleRegionsDirty = true;
2049 }
2050
2051 // some layers might have been removed, so
2052 // we need to update the regions they're exposing.
2053 if (mLayersRemoved) {
2054 mLayersRemoved = false;
2055 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002056 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002057 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002058 // this layer is not visible anymore
2059 // TODO: we could traverse the tree from front to back and
2060 // compute the actual visible region
2061 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002062 Region visibleReg;
2063 visibleReg.set(layer->computeScreenBounds());
2064 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002065 }
Robert Carr2047fae2016-11-28 14:09:09 -08002066 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067 }
2068
2069 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002070
2071 updateCursorAsync();
2072}
2073
2074void SurfaceFlinger::updateCursorAsync()
2075{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2077 auto& displayDevice = mDisplays[displayId];
2078 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002079 continue;
2080 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081
2082 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2083 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002084 }
2085 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002086}
2087
2088void SurfaceFlinger::commitTransaction()
2089{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002090 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002092 for (const auto& l : mLayersPendingRemoval) {
2093 recordBufferingStats(l->getName().string(),
2094 l->getOccupancyHistory(true));
2095 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096 }
2097 mLayersPendingRemoval.clear();
2098 }
2099
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002100 // If this transaction is part of a window animation then the next frame
2101 // we composite should be considered an animation as well.
2102 mAnimCompositionPending = mAnimTransactionPending;
2103
Mathias Agopian4fec8732012-06-29 14:12:52 -07002104 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002105 mDrawingState.traverseInZOrder([](Layer* layer) {
2106 layer->commitChildList();
2107 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002108 mTransactionPending = false;
2109 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002110 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111}
2112
Robert Carr2047fae2016-11-28 14:09:09 -08002113void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002114 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115{
Mathias Agopian841cde52012-03-01 15:44:37 -08002116 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119 Region aboveOpaqueLayers;
2120 Region aboveCoveredLayers;
2121 Region dirty;
2122
Mathias Agopian87baae12012-07-31 12:38:26 -07002123 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124
Robert Carr2047fae2016-11-28 14:09:09 -08002125 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002127 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128
Jesse Hall01e29052013-02-19 16:13:35 -08002129 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002130 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002131 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002132
Mathias Agopianab028732010-03-16 16:41:46 -07002133 /*
2134 * opaqueRegion: area of a surface that is fully opaque.
2135 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002137
2138 /*
2139 * visibleRegion: area of a surface that is visible on screen
2140 * and not fully transparent. This is essentially the layer's
2141 * footprint minus the opaque regions above it.
2142 * Areas covered by a translucent surface are considered visible.
2143 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002145
2146 /*
2147 * coveredRegion: area of a surface that is covered by all
2148 * visible regions above it (which includes the translucent areas).
2149 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002151
Jesse Halla8026d22012-09-25 13:25:04 -07002152 /*
2153 * transparentRegion: area of a surface that is hinted to be completely
2154 * transparent. This is only used to tell when the layer has no visible
2155 * non-transparent regions and can be removed from the layer list. It
2156 * does not affect the visibleRegion of this layer or any layers
2157 * beneath it. The hint may not be correct if apps don't respect the
2158 * SurfaceView restrictions (which, sadly, some don't).
2159 */
2160 Region transparentRegion;
2161
Mathias Agopianab028732010-03-16 16:41:46 -07002162
2163 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002164 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002165 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002166 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002168 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002169 if (!visibleRegion.isEmpty()) {
2170 // Remove the transparent area from the visible region
2171 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002172 if (tr.preserveRects()) {
2173 // transform the transparent region
2174 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002175 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002176 // transformation too complex, can't do the
2177 // transparent region optimization.
2178 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002179 }
Mathias Agopianab028732010-03-16 16:41:46 -07002180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002181
Mathias Agopianab028732010-03-16 16:41:46 -07002182 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002183 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002185 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2186 // the opaque region is the layer's footprint
2187 opaqueRegion = visibleRegion;
2188 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002189 }
2190 }
2191
Mathias Agopianab028732010-03-16 16:41:46 -07002192 // Clip the covered region to the visible region
2193 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2194
2195 // Update aboveCoveredLayers for next (lower) layer
2196 aboveCoveredLayers.orSelf(visibleRegion);
2197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198 // subtract the opaque region covered by the layers above us
2199 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200
2201 // compute this layer's dirty region
2202 if (layer->contentDirty) {
2203 // we need to invalidate the whole region
2204 dirty = visibleRegion;
2205 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002206 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002207 layer->contentDirty = false;
2208 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002209 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002210 * the exposed region consists of two components:
2211 * 1) what's VISIBLE now and was COVERED before
2212 * 2) what's EXPOSED now less what was EXPOSED before
2213 *
2214 * note that (1) is conservative, we start with the whole
2215 * visible region but only keep what used to be covered by
2216 * something -- which mean it may have been exposed.
2217 *
2218 * (2) handles areas that were not covered by anything but got
2219 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002220 */
Mathias Agopianab028732010-03-16 16:41:46 -07002221 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002222 const Region oldVisibleRegion = layer->visibleRegion;
2223 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002224 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2225 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 }
2227 dirty.subtractSelf(aboveOpaqueLayers);
2228
2229 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002230 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231
Mathias Agopianab028732010-03-16 16:41:46 -07002232 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002234
Jesse Halla8026d22012-09-25 13:25:04 -07002235 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236 layer->setVisibleRegion(visibleRegion);
2237 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002238 layer->setVisibleNonTransparentRegion(
2239 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002240 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241
Mathias Agopian87baae12012-07-31 12:38:26 -07002242 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243}
2244
Mathias Agopian87baae12012-07-31 12:38:26 -07002245void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2246 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002247 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002248 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2249 if (hw->getLayerStack() == layerStack) {
2250 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002251 }
2252 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002253}
2254
Dan Stoza6b9454d2014-11-07 16:00:59 -08002255bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002257 ALOGV("handlePageFlip");
2258
Brian Andersond6927fb2016-07-23 23:37:30 -07002259 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002260
Mathias Agopian4fec8732012-06-29 14:12:52 -07002261 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002262 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002263
2264 // Store the set of layers that need updates. This set must not change as
2265 // buffers are being latched, as this could result in a deadlock.
2266 // Example: Two producers share the same command stream and:
2267 // 1.) Layer 0 is latched
2268 // 2.) Layer 0 gets a new frame
2269 // 2.) Layer 1 gets a new frame
2270 // 3.) Layer 1 is latched.
2271 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2272 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002273 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002274 if (layer->hasQueuedFrame()) {
2275 frameQueued = true;
2276 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002277 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002278 } else {
2279 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002280 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002281 } else {
2282 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002283 }
Robert Carr2047fae2016-11-28 14:09:09 -08002284 });
2285
Dan Stoza9e56aa02015-11-02 13:00:03 -08002286 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002287 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002288 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002289 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002291
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002292 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002293
2294 // If we will need to wake up at some time in the future to deal with a
2295 // queued frame that shouldn't be displayed during this vsync period, wake
2296 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002297 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002298 signalLayerUpdate();
2299 }
2300
2301 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002302 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303}
2304
Mathias Agopianad456f92011-01-13 17:53:01 -08002305void SurfaceFlinger::invalidateHwcGeometry()
2306{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002308}
2309
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002310
Fabien Sanglard830b8472016-11-30 16:35:58 -08002311void SurfaceFlinger::doDisplayComposition(
2312 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002313 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314{
Dan Stoza71433162014-02-04 16:22:36 -08002315 // We only need to actually compose the display if:
2316 // 1) It is being handled by hardware composer, which may need this to
2317 // keep its virtual display state machine in sync, or
2318 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002319 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002320 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002321 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002322 return;
2323 }
2324
Dan Stoza9e56aa02015-11-02 13:00:03 -08002325 ALOGV("doDisplayComposition");
2326
Mathias Agopian87baae12012-07-31 12:38:26 -07002327 Region dirtyRegion(inDirtyRegion);
2328
Mathias Agopianb8a55602009-06-26 19:06:36 -07002329 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002330 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002333 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002334 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2335 // takes a rectangle, we must make sure to update that whole
2336 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002338 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002339 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002340 // We need to redraw the rectangle that will be updated
2341 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002342 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002343 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002344 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002345 } else {
2346 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002347 dirtyRegion.set(displayDevice->bounds());
2348 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 }
2350 }
2351
Fabien Sanglard830b8472016-11-30 16:35:58 -08002352 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002354 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002355 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002356
2357 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002358 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359}
2360
Dan Stoza9e56aa02015-11-02 13:00:03 -08002361bool SurfaceFlinger::doComposeSurfaces(
2362 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002363{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002365
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002367
2368 mat4 oldColorMatrix;
2369 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2370 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2371 if (applyColorMatrix) {
2372 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2373 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2374 }
2375
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2377 if (hasClientComposition) {
2378 ALOGV("hasClientComposition");
2379
2380 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002381 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002382 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002383 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2384 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2385 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2386 }
2387 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002388 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002389
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002390 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2392 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002393 // when using overlays, we assume a fully transparent framebuffer
2394 // NOTE: we could reduce how much we need to clear, for instance
2395 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002396 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002397 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002399 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002400 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002402
2403 // we remove the scissor part
2404 // we're left with the letterbox region
2405 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002407
2408 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002410
2411 // but limit it to the dirty region
2412 region.andSelf(dirty);
2413
Mathias Agopianb9494d52012-04-18 02:28:45 -07002414 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002415 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002416 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002418 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002419 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002420
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002422 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002423 // scissor on the main display. It should never be needed
2424 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002425 const Rect& bounds(displayDevice->getBounds());
2426 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002427 if (scissor != bounds) {
2428 // scissor doesn't match the screen's dimensions, so we
2429 // need to clear everything outside of it and enable
2430 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002431
Mathias Agopianf45c5102012-10-24 16:29:17 -07002432 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002433 const uint32_t height = displayDevice->getHeight();
2434 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002435 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002436 }
2437 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002438 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002439
Mathias Agopian85d751c2012-08-29 16:59:24 -07002440 /*
2441 * and then, render the layers targeted at the framebuffer
2442 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002443
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ALOGV("Rendering client layers");
2445 const Transform& displayTransform = displayDevice->getTransform();
2446 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002447 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 bool firstLayer = true;
2449 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2450 const Region clip(dirty.intersect(
2451 displayTransform.transform(layer->visibleRegion)));
2452 ALOGV("Layer: %s", layer->getName().string());
2453 ALOGV(" Composition type: %s",
2454 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002455 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 switch (layer->getCompositionType(hwcId)) {
2457 case HWC2::Composition::Cursor:
2458 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002459 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002461 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2463 layer->isOpaque(state) && (state.alpha == 1.0f)
2464 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002465 // never clear the very first layer since we're
2466 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002467 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002468 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002469 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 case HWC2::Composition::Client: {
2472 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002473 break;
2474 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002476 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002477 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 } else {
2479 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002480 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002482 }
2483 } else {
2484 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002486 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002488 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002490 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002491 }
2492 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002493
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002494 if (applyColorMatrix) {
2495 getRenderEngine().setupColorTransform(oldColorMatrix);
2496 }
2497
Mathias Agopianf45c5102012-10-24 16:29:17 -07002498 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002500 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Fabien Sanglard830b8472016-11-30 16:35:58 -08002503void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2504 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002505 RenderEngine& engine(getRenderEngine());
2506 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507}
2508
Dan Stoza7d89d062015-04-30 13:29:25 -07002509status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002510 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002511 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002512 const sp<Layer>& lbc,
2513 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002514{
Dan Stoza7d89d062015-04-30 13:29:25 -07002515 // add this layer to the current state list
2516 {
2517 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002518 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002519 return NO_MEMORY;
2520 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002521 if (parent == nullptr) {
2522 mCurrentState.layersSortedByZ.add(lbc);
2523 } else {
2524 parent->addChild(lbc);
2525 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002526 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002527 mLayersAdded = true;
2528 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002529 }
2530
Mathias Agopian96f08192010-06-02 23:28:45 -07002531 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002532 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002533
Dan Stoza7d89d062015-04-30 13:29:25 -07002534 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002535}
2536
Robert Carr9524cb32017-02-13 11:32:32 -08002537status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 const auto& p = layer->getParent();
2539 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2540 mCurrentState.layersSortedByZ.remove(layer);
2541
Robert Carr136e2f62017-02-08 17:54:29 -08002542 // As a matter of normal operation, the LayerCleaner will produce a second
2543 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2544 // so we will succeed in promoting it, but it's already been removed
2545 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2546 // otherwise something has gone wrong and we are leaking the layer.
2547 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2549 layer->getName().string(),
2550 (p != nullptr) ? p->getName().string() : "no-parent");
2551 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002552 } else if (index < 0) {
2553 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002554 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555
2556 mLayersPendingRemoval.add(layer);
2557 mLayersRemoved = true;
2558 mNumLayers--;
2559 setTransactionFlags(eTransactionNeeded);
2560 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561}
2562
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002563uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002564 return android_atomic_release_load(&mTransactionFlags);
2565}
2566
Mathias Agopian3f844832013-08-07 21:24:32 -07002567uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2569}
2570
Mathias Agopian3f844832013-08-07 21:24:32 -07002571uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2573 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002574 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 }
2576 return old;
2577}
2578
Mathias Agopian8b33f032012-07-24 20:43:54 -07002579void SurfaceFlinger::setTransactionState(
2580 const Vector<ComposerState>& state,
2581 const Vector<DisplayState>& displays,
2582 uint32_t flags)
2583{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002584 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002585 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002586 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002587
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002588 if (flags & eAnimation) {
2589 // For window updates that are part of an animation we must wait for
2590 // previous animation "frames" to be handled.
2591 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002592 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002593 if (CC_UNLIKELY(err != NO_ERROR)) {
2594 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002595 // caller after a few seconds.
2596 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2597 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002598 mAnimTransactionPending = false;
2599 break;
2600 }
2601 }
2602 }
2603
Mathias Agopiane57f2922012-08-09 16:29:12 -07002604 size_t count = displays.size();
2605 for (size_t i=0 ; i<count ; i++) {
2606 const DisplayState& s(displays[i]);
2607 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002608 }
2609
Mathias Agopiane57f2922012-08-09 16:29:12 -07002610 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002611 for (size_t i=0 ; i<count ; i++) {
2612 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002613 // Here we need to check that the interface we're given is indeed
2614 // one of our own. A malicious client could give us a NULL
2615 // IInterface, or one of its own or even one of our own but a
2616 // different type. All these situations would cause us to crash.
2617 //
2618 // NOTE: it would be better to use RTTI as we could directly check
2619 // that we have a Client*. however, RTTI is disabled in Android.
2620 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002621 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002622 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002623 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002624 sp<Client> client( static_cast<Client *>(s.client.get()) );
2625 transactionFlags |= setClientStateLocked(client, s.state);
2626 }
2627 }
2628 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002629 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002630
Robert Carr2a7dbb42016-05-24 11:41:28 -07002631 // If a synchronous transaction is explicitly requested without any changes,
2632 // force a transaction anyway. This can be used as a flush mechanism for
2633 // previous async transactions.
2634 if (transactionFlags == 0 && (flags & eSynchronous)) {
2635 transactionFlags = eTransactionNeeded;
2636 }
2637
Mathias Agopian386aa982011-11-07 21:58:03 -08002638 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002639 if (mInterceptor.isEnabled()) {
2640 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2641 }
Irvel468051e2016-06-13 16:44:44 -07002642
Mathias Agopian386aa982011-11-07 21:58:03 -08002643 // this triggers the transaction
2644 setTransactionFlags(transactionFlags);
2645
2646 // if this is a synchronous transaction, wait for it to take effect
2647 // before returning.
2648 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002649 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002651 if (flags & eAnimation) {
2652 mAnimTransactionPending = true;
2653 }
2654 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002655 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2656 if (CC_UNLIKELY(err != NO_ERROR)) {
2657 // just in case something goes wrong in SF, return to the
2658 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002659 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2660 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002661 break;
2662 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 }
2665}
2666
Mathias Agopiane57f2922012-08-09 16:29:12 -07002667uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2668{
Jesse Hall9a143922012-10-04 16:29:19 -07002669 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2670 if (dpyIdx < 0)
2671 return 0;
2672
Mathias Agopiane57f2922012-08-09 16:29:12 -07002673 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002674 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002675 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676 const uint32_t what = s.what;
2677 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002678 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679 disp.surface = s.surface;
2680 flags |= eDisplayTransactionNeeded;
2681 }
2682 }
2683 if (what & DisplayState::eLayerStackChanged) {
2684 if (disp.layerStack != s.layerStack) {
2685 disp.layerStack = s.layerStack;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002689 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002690 if (disp.orientation != s.orientation) {
2691 disp.orientation = s.orientation;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 if (disp.frame != s.frame) {
2695 disp.frame = s.frame;
2696 flags |= eDisplayTransactionNeeded;
2697 }
2698 if (disp.viewport != s.viewport) {
2699 disp.viewport = s.viewport;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 }
Michael Lentine47e45402014-07-18 15:34:25 -07002703 if (what & DisplayState::eDisplaySizeChanged) {
2704 if (disp.width != s.width) {
2705 disp.width = s.width;
2706 flags |= eDisplayTransactionNeeded;
2707 }
2708 if (disp.height != s.height) {
2709 disp.height = s.height;
2710 flags |= eDisplayTransactionNeeded;
2711 }
2712 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713 }
2714 return flags;
2715}
2716
2717uint32_t SurfaceFlinger::setClientStateLocked(
2718 const sp<Client>& client,
2719 const layer_state_t& s)
2720{
2721 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002722 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002723 if (layer != 0) {
2724 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002725 bool geometryAppliesWithResize =
2726 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002727 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002728 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002730 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 }
2732 if (what & layer_state_t::eLayerChanged) {
2733 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 const auto& p = layer->getParent();
2735 if (p == nullptr) {
2736 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2737 if (layer->setLayer(s.z) && idx >= 0) {
2738 mCurrentState.layersSortedByZ.removeAt(idx);
2739 mCurrentState.layersSortedByZ.add(layer);
2740 // we need traversal (state changed)
2741 // AND transaction (list changed)
2742 flags |= eTransactionNeeded|eTraversalNeeded;
2743 }
2744 } else {
2745 if (p->setChildLayer(layer, s.z)) {
2746 flags |= eTransactionNeeded|eTraversalNeeded;
2747 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002748 }
2749 }
2750 if (what & layer_state_t::eSizeChanged) {
2751 if (layer->setSize(s.w, s.h)) {
2752 flags |= eTraversalNeeded;
2753 }
2754 }
2755 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 flags |= eTraversalNeeded;
2758 }
2759 if (what & layer_state_t::eMatrixChanged) {
2760 if (layer->setMatrix(s.matrix))
2761 flags |= eTraversalNeeded;
2762 }
2763 if (what & layer_state_t::eTransparentRegionChanged) {
2764 if (layer->setTransparentRegionHint(s.transparentRegion))
2765 flags |= eTraversalNeeded;
2766 }
Dan Stoza23116082015-06-18 14:58:39 -07002767 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002768 if (layer->setFlags(s.flags, s.mask))
2769 flags |= eTraversalNeeded;
2770 }
2771 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002772 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 flags |= eTraversalNeeded;
2774 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002775 if (what & layer_state_t::eFinalCropChanged) {
2776 if (layer->setFinalCrop(s.finalCrop))
2777 flags |= eTraversalNeeded;
2778 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002779 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 // We only allow setting layer stacks for top level layers,
2782 // everything else inherits layer stack from its parent.
2783 if (layer->hasParent()) {
2784 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2785 layer->getName().string());
2786 } else if (idx < 0) {
2787 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2788 "that also does not appear in the top level layer list. Something"
2789 " has gone wrong.", layer->getName().string());
2790 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791 mCurrentState.layersSortedByZ.removeAt(idx);
2792 mCurrentState.layersSortedByZ.add(layer);
2793 // we need traversal (state changed)
2794 // AND transaction (list changed)
2795 flags |= eTransactionNeeded|eTraversalNeeded;
2796 }
2797 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002798 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002799 if (s.barrierHandle != nullptr) {
2800 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2801 } else if (s.barrierGbp != nullptr) {
2802 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2803 if (authenticateSurfaceTextureLocked(gbp)) {
2804 const auto& otherLayer =
2805 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2806 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2807 } else {
2808 ALOGE("Attempt to defer transaction to to an"
2809 " unrecognized GraphicBufferProducer");
2810 }
2811 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002812 // We don't trigger a traversal here because if no other state is
2813 // changed, we don't want this to cause any more work
2814 }
Robert Carr1db73f62016-12-21 12:58:51 -08002815 if (what & layer_state_t::eReparentChildren) {
2816 if (layer->reparentChildren(s.reparentHandle)) {
2817 flags |= eTransactionNeeded|eTraversalNeeded;
2818 }
2819 }
Robert Carr9524cb32017-02-13 11:32:32 -08002820 if (what & layer_state_t::eDetachChildren) {
2821 layer->detachChildren();
2822 }
Robert Carrc3574f72016-03-24 12:19:32 -07002823 if (what & layer_state_t::eOverrideScalingModeChanged) {
2824 layer->setOverrideScalingMode(s.overrideScalingMode);
2825 // We don't trigger a traversal here because if no other state is
2826 // changed, we don't want this to cause any more work
2827 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002828 }
2829 return flags;
2830}
2831
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002832status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002833 const String8& name,
2834 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002835 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002836 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2837 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002839 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002840 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002841 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002842 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002843 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002844
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002845 status_t result = NO_ERROR;
2846
2847 sp<Layer> layer;
2848
Mathias Agopian3165cc22012-08-08 19:42:09 -07002849 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2850 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002851 result = createNormalLayer(client,
2852 name, w, h, flags, format,
2853 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002855 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002856 result = createDimLayer(client,
2857 name, w, h, flags,
2858 handle, gbp, &layer);
2859 break;
2860 default:
2861 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 break;
2863 }
2864
Dan Stoza7d89d062015-04-30 13:29:25 -07002865 if (result != NO_ERROR) {
2866 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002868
Albert Chaulk479c60c2017-01-27 14:21:34 -05002869 layer->setInfo(windowType, ownerUid);
2870
Robert Carr1f0a16a2016-10-24 16:27:39 -07002871 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002872 if (result != NO_ERROR) {
2873 return result;
2874 }
Irvelffc9efc2016-07-27 15:16:37 -07002875 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002876
2877 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002878 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879}
2880
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002881status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2882 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2883 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884{
2885 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002886 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 case PIXEL_FORMAT_TRANSPARENT:
2888 case PIXEL_FORMAT_TRANSLUCENT:
2889 format = PIXEL_FORMAT_RGBA_8888;
2890 break;
2891 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002892 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 break;
2894 }
2895
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002896 *outLayer = new Layer(this, client, name, w, h, flags);
2897 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2898 if (err == NO_ERROR) {
2899 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002900 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002902
2903 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2904 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905}
2906
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002907status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2908 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2909 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002911 *outLayer = new LayerDim(this, client, name, w, h, flags);
2912 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002913 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002914 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002915}
2916
Mathias Agopianac9fa422013-02-11 16:40:36 -08002917status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918{
Robert Carr9524cb32017-02-13 11:32:32 -08002919 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002920 status_t err = NO_ERROR;
2921 sp<Layer> l(client->getLayerUser(handle));
2922 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002923 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002924 err = removeLayer(l);
2925 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2926 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002927 }
2928 return err;
2929}
2930
Mathias Agopian13127d82013-03-05 17:47:11 -08002931status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002932{
Mathias Agopian67106042013-03-14 19:18:13 -07002933 // called by ~LayerCleaner() when all references to the IBinder (handle)
2934 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002935 sp<Layer> l = layer.promote();
2936 if (l == nullptr) {
2937 // The layer has already been removed, carry on
2938 return NO_ERROR;
2939 } if (l->getParent() != nullptr) {
2940 // If we have a parent, then we can continue to live as long as it does.
2941 return NO_ERROR;
2942 }
2943 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944}
2945
Mathias Agopianb60314a2012-04-10 22:09:54 -07002946// ---------------------------------------------------------------------------
2947
Andy McFadden13a082e2012-08-24 10:16:42 -07002948void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002949 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002950 Vector<ComposerState> state;
2951 Vector<DisplayState> displays;
2952 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002953 d.what = DisplayState::eDisplayProjectionChanged |
2954 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002955 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002956 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002957 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002958 d.frame.makeInvalid();
2959 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002960 d.width = 0;
2961 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002962 displays.add(d);
2963 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002964 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002965
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2967 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002968 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002969
2970 {
2971 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2972 mCompositorTiming.interval = period;
2973 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002974}
2975
2976void SurfaceFlinger::initializeDisplays() {
2977 class MessageScreenInitialized : public MessageBase {
2978 SurfaceFlinger* flinger;
2979 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002980 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002981 virtual bool handler() {
2982 flinger->onInitializeDisplays();
2983 return true;
2984 }
2985 };
2986 sp<MessageBase> msg = new MessageScreenInitialized(this);
2987 postMessageAsync(msg); // we may be called from main thread, use async message
2988}
2989
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002990void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2991 int mode) {
2992 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2993 this);
2994 int32_t type = hw->getDisplayType();
2995 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002996
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997 if (mode == currentMode) {
2998 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002999 return;
3000 }
3001
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003002 hw->setPowerMode(mode);
3003 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3004 ALOGW("Trying to set power mode for virtual display");
3005 return;
3006 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003007
Irvelffc9efc2016-07-27 15:16:37 -07003008 if (mInterceptor.isEnabled()) {
3009 Mutex::Autolock _l(mStateLock);
3010 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3011 if (idx < 0) {
3012 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3013 return;
3014 }
3015 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3016 }
3017
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003018 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003019 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003020 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003021 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3022 // FIXME: eventthread only knows about the main display right now
3023 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003024 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003025 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003026
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003027 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003028 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003030
3031 struct sched_param param = {0};
3032 param.sched_priority = 1;
3033 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3034 ALOGW("Couldn't set SCHED_FIFO on display on");
3035 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003036 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003037 // Turn off the display
3038 struct sched_param param = {0};
3039 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3040 ALOGW("Couldn't set SCHED_OTHER on display off");
3041 }
3042
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003043 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003044 disableHardwareVsync(true); // also cancels any in-progress resync
3045
Mathias Agopiancde87a32012-09-13 14:09:01 -07003046 // FIXME: eventthread only knows about the main display right now
3047 mEventThread->onScreenReleased();
3048 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003049
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003050 getHwComposer().setPowerMode(type, mode);
3051 mVisibleRegionsDirty = true;
3052 // from this point on, SF will stop drawing on this display
3053 } else {
3054 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056}
3057
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003058void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3059 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003060 SurfaceFlinger& mFlinger;
3061 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003062 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003063 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003064 MessageSetPowerMode(SurfaceFlinger& flinger,
3065 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3066 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003068 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003069 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003070 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003071 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003072 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003073 ALOGW("Attempt to set power mode = %d for virtual display",
3074 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003075 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003076 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003077 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003078 return true;
3079 }
3080 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003081 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003082 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003083}
3084
3085// ---------------------------------------------------------------------------
3086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3088{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003090
Mathias Agopianbd115332013-04-18 16:41:04 -07003091 IPCThreadState* ipc = IPCThreadState::self();
3092 const int pid = ipc->getCallingPid();
3093 const int uid = ipc->getCallingUid();
3094 if ((uid != AID_SHELL) &&
3095 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003096 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003097 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003099 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003100 // (this would indicate SF is stuck, but we want to be able to
3101 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003102 status_t err = mStateLock.timedLock(s2ns(1));
3103 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003104 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003105 result.appendFormat(
3106 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3107 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003108 }
3109
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003110 bool dumpAll = true;
3111 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112 size_t numArgs = args.size();
3113 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003114 if ((index < numArgs) &&
3115 (args[index] == String16("--list"))) {
3116 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003117 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003118 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003119 }
3120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003123 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003124 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003125 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003126 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003127
3128 if ((index < numArgs) &&
3129 (args[index] == String16("--latency-clear"))) {
3130 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003131 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003132 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003133 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003134
3135 if ((index < numArgs) &&
3136 (args[index] == String16("--dispsync"))) {
3137 index++;
3138 mPrimaryDispSync.dump(result);
3139 dumpAll = false;
3140 }
Dan Stozab90cf072015-03-05 11:05:59 -08003141
3142 if ((index < numArgs) &&
3143 (args[index] == String16("--static-screen"))) {
3144 index++;
3145 dumpStaticScreenStats(result);
3146 dumpAll = false;
3147 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003148
3149 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003150 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003151 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003152 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003153 dumpAll = false;
3154 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003156
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003157 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003158 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003159 }
3160
Mathias Agopian9795c422009-08-26 16:36:26 -07003161 if (locked) {
3162 mStateLock.unlock();
3163 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 }
3165 write(fd, result.string(), result.size());
3166 return NO_ERROR;
3167}
3168
Dan Stozac7014012014-02-14 15:03:43 -08003169void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3170 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003171{
Robert Carr2047fae2016-11-28 14:09:09 -08003172 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003173 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003174 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003175}
3176
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003177void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003178 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003179{
3180 String8 name;
3181 if (index < args.size()) {
3182 name = String8(args[index]);
3183 index++;
3184 }
3185
Dan Stoza9e56aa02015-11-02 13:00:03 -08003186 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3187 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003188 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003189
3190 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003191 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003192 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003194 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003195 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003196 }
Robert Carr2047fae2016-11-28 14:09:09 -08003197 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003198 }
3199}
3200
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003201void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003202 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003203{
3204 String8 name;
3205 if (index < args.size()) {
3206 name = String8(args[index]);
3207 index++;
3208 }
3209
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003211 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003212 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003213 }
Robert Carr2047fae2016-11-28 14:09:09 -08003214 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003215
Svetoslavd85084b2014-03-20 10:28:31 -07003216 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003217}
3218
Jamie Gennis6547ff42013-07-16 20:12:42 -07003219// This should only be called from the main thread. Otherwise it would need
3220// the lock and should use mCurrentState rather than mDrawingState.
3221void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003223 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003224 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003225
3226 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3227}
3228
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003229void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003230{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003231 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003232#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003233 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003234#endif
3235#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003236 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003237#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003238 if (isLayerTripleBufferingDisabled())
3239 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003240 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003241}
3242
Dan Stozab90cf072015-03-05 11:05:59 -08003243void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3244{
3245 result.appendFormat("Static screen stats:\n");
3246 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3247 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3248 float percent = 100.0f *
3249 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3250 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3251 b + 1, bucketTimeSec, percent);
3252 }
3253 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3254 float percent = 100.0f *
3255 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3256 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3257 NUM_BUCKETS - 1, bucketTimeSec, percent);
3258}
3259
Dan Stozae77c7662016-05-13 11:37:28 -07003260void SurfaceFlinger::recordBufferingStats(const char* layerName,
3261 std::vector<OccupancyTracker::Segment>&& history) {
3262 Mutex::Autolock lock(mBufferingStatsMutex);
3263 auto& stats = mBufferingStats[layerName];
3264 for (const auto& segment : history) {
3265 if (!segment.usedThirdBuffer) {
3266 stats.twoBufferTime += segment.totalTime;
3267 }
3268 if (segment.occupancyAverage < 1.0f) {
3269 stats.doubleBufferedTime += segment.totalTime;
3270 } else if (segment.occupancyAverage < 2.0f) {
3271 stats.tripleBufferedTime += segment.totalTime;
3272 }
3273 ++stats.numSegments;
3274 stats.totalTime += segment.totalTime;
3275 }
3276}
3277
Brian Andersond6927fb2016-07-23 23:37:30 -07003278void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3279 result.appendFormat("Layer frame timestamps:\n");
3280
3281 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3282 const size_t count = currentLayers.size();
3283 for (size_t i=0 ; i<count ; i++) {
3284 currentLayers[i]->dumpFrameEvents(result);
3285 }
3286}
3287
Dan Stozae77c7662016-05-13 11:37:28 -07003288void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3289 result.append("Buffering stats:\n");
3290 result.append(" [Layer name] <Active time> <Two buffer> "
3291 "<Double buffered> <Triple buffered>\n");
3292 Mutex::Autolock lock(mBufferingStatsMutex);
3293 typedef std::tuple<std::string, float, float, float> BufferTuple;
3294 std::map<float, BufferTuple, std::greater<float>> sorted;
3295 for (const auto& statsPair : mBufferingStats) {
3296 const char* name = statsPair.first.c_str();
3297 const BufferingStats& stats = statsPair.second;
3298 if (stats.numSegments == 0) {
3299 continue;
3300 }
3301 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3302 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3303 stats.totalTime;
3304 float doubleBufferRatio = static_cast<float>(
3305 stats.doubleBufferedTime) / stats.totalTime;
3306 float tripleBufferRatio = static_cast<float>(
3307 stats.tripleBufferedTime) / stats.totalTime;
3308 sorted.insert({activeTime, {name, twoBufferRatio,
3309 doubleBufferRatio, tripleBufferRatio}});
3310 }
3311 for (const auto& sortedPair : sorted) {
3312 float activeTime = sortedPair.first;
3313 const BufferTuple& values = sortedPair.second;
3314 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3315 std::get<0>(values).c_str(), activeTime,
3316 std::get<1>(values), std::get<2>(values),
3317 std::get<3>(values));
3318 }
3319 result.append("\n");
3320}
3321
3322
Mathias Agopian74d211a2013-04-22 16:55:35 +02003323void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3324 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003325{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003326 bool colorize = false;
3327 if (index < args.size()
3328 && (args[index] == String16("--color"))) {
3329 colorize = true;
3330 index++;
3331 }
3332
3333 Colorizer colorizer(colorize);
3334
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003335 // figure out if we're stuck somewhere
3336 const nsecs_t now = systemTime();
3337 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3338 const nsecs_t inTransaction(mDebugInTransaction);
3339 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3340 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3341
3342 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003343 * Dump library configuration.
3344 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003345
3346 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003347 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003348 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003349 appendSfConfigString(result);
3350 appendUiConfigString(result);
3351 appendGuiConfigString(result);
3352 result.append("\n");
3353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003354 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003355 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003356 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003357 result.append(SyncFeatures::getInstance().toString());
3358 result.append("\n");
3359
Dan Stoza9e56aa02015-11-02 13:00:03 -08003360 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3361
Andy McFadden41d67d72014-04-25 16:58:34 -07003362 colorizer.bold(result);
3363 result.append("DispSync configuration: ");
3364 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003365 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3366 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3368 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003369 result.append("\n");
3370
Dan Stozab90cf072015-03-05 11:05:59 -08003371 // Dump static screen stats
3372 result.append("\n");
3373 dumpStaticScreenStats(result);
3374 result.append("\n");
3375
Dan Stozae77c7662016-05-13 11:37:28 -07003376 dumpBufferingStats(result);
3377
Andy McFadden4803b742012-09-24 19:07:20 -07003378 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003379 * Dump the visible layer list
3380 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003382 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003384 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003386 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003387
3388 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003389 * Dump Display state
3390 */
3391
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003392 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003393 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003394 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003395 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3396 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003397 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003398 }
3399
3400 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003401 * Dump SurfaceFlinger global state
3402 */
3403
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003404 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003405 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003406 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003407
Mathias Agopian888c8222012-08-04 21:10:38 -07003408 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003409 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003410
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003411 colorizer.bold(result);
3412 result.appendFormat("EGL implementation : %s\n",
3413 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3414 colorizer.reset(result);
3415 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003416 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003417
Mathias Agopian875d8e12013-06-07 15:35:48 -07003418 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419
Mathias Agopian42977342012-08-05 00:40:46 -07003420 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003421 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3422 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003423 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424 " last eglSwapBuffers() time: %f us\n"
3425 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003426 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003427 " refresh-rate : %f fps\n"
3428 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003429 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003430 " gpu_to_cpu_unsupported : %d\n"
3431 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003432 mLastSwapBufferTime/1000.0,
3433 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003434 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003435 1e9 / activeConfig->getVsyncPeriod(),
3436 activeConfig->getDpiX(),
3437 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003438 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003439
Mathias Agopian74d211a2013-04-22 16:55:35 +02003440 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003441 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003442
Mathias Agopian74d211a2013-04-22 16:55:35 +02003443 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003444 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003445
3446 /*
3447 * VSYNC state
3448 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003449 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003450 result.append("\n");
3451
3452 /*
3453 * HWC layer minidump
3454 */
3455 for (size_t d = 0; d < mDisplays.size(); d++) {
3456 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3457 int32_t hwcId = displayDevice->getHwcDisplayId();
3458 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3459 continue;
3460 }
3461
3462 result.appendFormat("Display %d HWC layers:\n", hwcId);
3463 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003464 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003465 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 });
Dan Stozae22aec72016-08-01 13:20:59 -07003467 result.append("\n");
3468 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469
3470 /*
3471 * Dump HWComposer state
3472 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003473 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003474 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003475 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003476 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003477 result.appendFormat(" h/w composer %s\n",
3478 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003479 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003480
3481 /*
3482 * Dump gralloc state
3483 */
3484 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3485 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003486}
3487
Mathias Agopian13127d82013-03-05 17:47:11 -08003488const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003489SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003490 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003491 wp<IBinder> dpy;
3492 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3493 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3494 dpy = mDisplays.keyAt(i);
3495 break;
3496 }
3497 }
3498 if (dpy == NULL) {
3499 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3500 // Just use the primary display so we have something to return
3501 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3502 }
3503 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003504}
3505
Keun young Park63f165f2012-08-31 10:53:36 -07003506bool SurfaceFlinger::startDdmConnection()
3507{
3508 void* libddmconnection_dso =
3509 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3510 if (!libddmconnection_dso) {
3511 return false;
3512 }
3513 void (*DdmConnection_start)(const char* name);
3514 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003515 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003516 if (!DdmConnection_start) {
3517 dlclose(libddmconnection_dso);
3518 return false;
3519 }
3520 (*DdmConnection_start)(getServiceName());
3521 return true;
3522}
3523
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003524status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 switch (code) {
3526 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003527 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003529 case CLEAR_ANIMATION_FRAME_STATS:
3530 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003531 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003532 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 {
3534 // codes that require permission check
3535 IPCThreadState* ipc = IPCThreadState::self();
3536 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003537 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003538 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003539 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003540 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003541 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003543 break;
3544 }
Robert Carr1db73f62016-12-21 12:58:51 -08003545 /*
3546 * Calling setTransactionState is safe, because you need to have been
3547 * granted a reference to Client* and Handle* to do anything with it.
3548 *
3549 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3550 */
3551 case SET_TRANSACTION_STATE:
3552 case CREATE_SCOPED_CONNECTION:
3553 {
3554 return OK;
3555 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003556 case CAPTURE_SCREEN:
3557 {
3558 // codes that require permission check
3559 IPCThreadState* ipc = IPCThreadState::self();
3560 const int pid = ipc->getCallingPid();
3561 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003562 if ((uid != AID_GRAPHICS) &&
3563 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003564 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003565 return PERMISSION_DENIED;
3566 }
3567 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 }
3569 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003570 return OK;
3571}
3572
3573status_t SurfaceFlinger::onTransact(
3574 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3575{
3576 status_t credentialCheck = CheckTransactCodeCredentials(code);
3577 if (credentialCheck != OK) {
3578 return credentialCheck;
3579 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003580
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3582 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003583 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003584 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003585 IPCThreadState* ipc = IPCThreadState::self();
3586 const int pid = ipc->getCallingPid();
3587 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003588 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003589 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 return PERMISSION_DENIED;
3591 }
3592 int n;
3593 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003594 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003595 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 return NO_ERROR;
3597 case 1002: // SHOW_UPDATES
3598 n = data.readInt32();
3599 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003600 invalidateHwcGeometry();
3601 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003604 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003605 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003607 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003608 setTransactionFlags(
3609 eTransactionNeeded|
3610 eDisplayTransactionNeeded|
3611 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003612 return NO_ERROR;
3613 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003614 case 1006:{ // send empty update
3615 signalRefresh();
3616 return NO_ERROR;
3617 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003618 case 1008: // toggle use of hw composer
3619 n = data.readInt32();
3620 mDebugDisableHWC = n ? 1 : 0;
3621 invalidateHwcGeometry();
3622 repaintEverything();
3623 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003624 case 1009: // toggle use of transform hint
3625 n = data.readInt32();
3626 mDebugDisableTransformHint = n ? 1 : 0;
3627 invalidateHwcGeometry();
3628 repaintEverything();
3629 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003631 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632 reply->writeInt32(0);
3633 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003634 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003635 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 return NO_ERROR;
3637 case 1013: {
3638 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003639 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3640 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003641 return NO_ERROR;
3642 }
3643 case 1014: {
3644 // daltonize
3645 n = data.readInt32();
3646 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003647 case 1:
3648 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3649 break;
3650 case 2:
3651 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3652 break;
3653 case 3:
3654 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3655 break;
3656 default:
3657 mDaltonizer.setType(ColorBlindnessType::None);
3658 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003659 }
3660 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003661 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003662 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003663 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003664 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003665 invalidateHwcGeometry();
3666 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003667 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003669 case 1015: {
3670 // apply a color matrix
3671 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003672 if (n) {
3673 // color matrix is sent as mat3 matrix followed by vec3
3674 // offset, then packed into a mat4 where the last row is
3675 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003676 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003677 for (size_t j = 0; j < 4; j++) {
3678 mColorMatrix[i][j] = data.readFloat();
3679 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003680 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003681 } else {
3682 mColorMatrix = mat4();
3683 }
3684 invalidateHwcGeometry();
3685 repaintEverything();
3686 return NO_ERROR;
3687 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003688 // This is an experimental interface
3689 // Needs to be shifted to proper binder interface when we productize
3690 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003691 n = data.readInt32();
3692 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003693 return NO_ERROR;
3694 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003695 case 1017: {
3696 n = data.readInt32();
3697 mForceFullDamage = static_cast<bool>(n);
3698 return NO_ERROR;
3699 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003700 case 1018: { // Modify Choreographer's phase offset
3701 n = data.readInt32();
3702 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3703 return NO_ERROR;
3704 }
3705 case 1019: { // Modify SurfaceFlinger's phase offset
3706 n = data.readInt32();
3707 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3708 return NO_ERROR;
3709 }
Irvel468051e2016-06-13 16:44:44 -07003710 case 1020: { // Layer updates interceptor
3711 n = data.readInt32();
3712 if (n) {
3713 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003714 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003715 }
3716 else{
3717 ALOGV("Interceptor disabled");
3718 mInterceptor.disable();
3719 }
3720 return NO_ERROR;
3721 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003722 case 1021: { // Disable HWC virtual displays
3723 n = data.readInt32();
3724 mUseHwcVirtualDisplays = !n;
3725 return NO_ERROR;
3726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 }
3728 }
3729 return err;
3730}
3731
Mathias Agopian53331da2011-08-22 21:44:41 -07003732void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003733 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003734 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003735}
3736
Mathias Agopian59119e62010-10-11 12:37:43 -07003737// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003738// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003739// ---------------------------------------------------------------------------
3740
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003741/* The code below is here to handle b/8734824
3742 *
3743 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003744 * from the surfaceflinger thread to the calling binder thread, where they
3745 * are executed. This allows the calling thread in the calling process to be
3746 * reused and not depend on having "enough" binder threads to handle the
3747 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003748 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003749class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003750 /* Parts of GraphicProducerWrapper are run on two different threads,
3751 * communicating by sending messages via Looper but also by shared member
3752 * data. Coherence maintenance is subtle and in places implicit (ugh).
3753 *
3754 * Don't rely on Looper's sendMessage/handleMessage providing
3755 * release/acquire semantics for any data not actually in the Message.
3756 * Data going from surfaceflinger to binder threads needs to be
3757 * synchronized explicitly.
3758 *
3759 * Barrier open/wait do provide release/acquire semantics. This provides
3760 * implicit synchronization for data coming back from binder to
3761 * surfaceflinger threads.
3762 */
3763
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003764 sp<IGraphicBufferProducer> impl;
3765 sp<Looper> looper;
3766 status_t result;
3767 bool exitPending;
3768 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003769 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003770 uint32_t code;
3771 Parcel const* data;
3772 Parcel* reply;
3773
3774 enum {
3775 MSG_API_CALL,
3776 MSG_EXIT
3777 };
3778
3779 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003780 * Called on surfaceflinger thread. This is called by our "fake"
3781 * BpGraphicBufferProducer. We package the data and reply Parcel and
3782 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 */
3784 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003785 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003786 this->code = code;
3787 this->data = &data;
3788 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003789 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003790 // if we've exited, we run the message synchronously right here.
3791 // note (JH): as far as I can tell from looking at the code, this
3792 // never actually happens. if it does, i'm not sure if it happens
3793 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003794 handleMessage(Message(MSG_API_CALL));
3795 } else {
3796 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003797 // Prevent stores to this->{code, data, reply} from being
3798 // reordered later than the construction of Message.
3799 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003800 looper->sendMessage(this, Message(MSG_API_CALL));
3801 barrier.wait();
3802 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003803 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003804 }
3805
3806 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003807 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003808 * call the real BpGraphicBufferProducer.
3809 */
3810 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003811 int what = message.what;
3812 // Prevent reads below from happening before the read from Message
3813 atomic_thread_fence(memory_order_acquire);
3814 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003815 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003816 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003817 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003818 exitRequested = true;
3819 }
3820 }
3821
3822public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003823 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003824 : impl(impl),
3825 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003826 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003827 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003828 exitRequested(false),
3829 code(0),
3830 data(NULL),
3831 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003832 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003833
Jesse Hallb154c422014-07-13 12:47:02 -07003834 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003835 status_t waitForResponse() {
3836 do {
3837 looper->pollOnce(-1);
3838 } while (!exitRequested);
3839 return result;
3840 }
3841
Jesse Hallb154c422014-07-13 12:47:02 -07003842 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003843 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003844 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003845 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003846 // Ensure this->result is visible to the binder thread before it
3847 // handles the message.
3848 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849 looper->sendMessage(this, Message(MSG_EXIT));
3850 }
3851};
3852
3853
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003854status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3855 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003856 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003857 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003858 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003859
3860 if (CC_UNLIKELY(display == 0))
3861 return BAD_VALUE;
3862
3863 if (CC_UNLIKELY(producer == 0))
3864 return BAD_VALUE;
3865
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003866 // if we have secure windows on this display, never allow the screen capture
3867 // unless the producer interface is local (i.e.: we can take a screenshot for
3868 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003869 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003870
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003871 // Convert to surfaceflinger's internal rotation type.
3872 Transform::orientation_flags rotationFlags;
3873 switch (rotation) {
3874 case ISurfaceComposer::eRotateNone:
3875 rotationFlags = Transform::ROT_0;
3876 break;
3877 case ISurfaceComposer::eRotate90:
3878 rotationFlags = Transform::ROT_90;
3879 break;
3880 case ISurfaceComposer::eRotate180:
3881 rotationFlags = Transform::ROT_180;
3882 break;
3883 case ISurfaceComposer::eRotate270:
3884 rotationFlags = Transform::ROT_270;
3885 break;
3886 default:
3887 rotationFlags = Transform::ROT_0;
3888 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3889 break;
3890 }
3891
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003892 class MessageCaptureScreen : public MessageBase {
3893 SurfaceFlinger* flinger;
3894 sp<IBinder> display;
3895 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003896 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 uint32_t reqWidth, reqHeight;
3898 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003899 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003900 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003902 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903 public:
3904 MessageCaptureScreen(SurfaceFlinger* flinger,
3905 const sp<IBinder>& display,
3906 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003907 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003908 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003909 bool useIdentityTransform,
3910 Transform::orientation_flags rotation,
3911 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003912 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003913 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003914 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003915 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003916 rotation(rotation), result(PERMISSION_DENIED),
3917 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003918 {
3919 }
3920 status_t getResult() const {
3921 return result;
3922 }
3923 virtual bool handler() {
3924 Mutex::Autolock _l(flinger->mStateLock);
3925 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003926 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003927 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003928 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003929 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 return true;
3931 }
3932 };
3933
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003934 // this creates a "fake" BBinder which will serve as a "fake" remote
3935 // binder to receive the marshaled calls and forward them to the
3936 // real remote (a BpGraphicBufferProducer)
3937 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3938
3939 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3940 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003941 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003942 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003943 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003944 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003945
3946 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003947 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003948 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003949 }
3950 return res;
3951}
3952
Mathias Agopian180f10d2013-04-10 22:55:41 -07003953
3954void SurfaceFlinger::renderScreenImplLocked(
3955 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003956 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003957 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003958 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003959{
3960 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003961 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003962
3963 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003964 const int32_t hw_w = hw->getWidth();
3965 const int32_t hw_h = hw->getHeight();
3966 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003967 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003968
Dan Stozac1879002014-05-22 15:59:05 -07003969 // if a default or invalid sourceCrop is passed in, set reasonable values
3970 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3971 !sourceCrop.isValid()) {
3972 sourceCrop.setLeftTop(Point(0, 0));
3973 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3974 }
3975
3976 // ensure that sourceCrop is inside screen
3977 if (sourceCrop.left < 0) {
3978 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3979 }
Dan Stozabe31f442014-06-11 11:20:54 -07003980 if (sourceCrop.right > hw_w) {
3981 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003982 }
3983 if (sourceCrop.top < 0) {
3984 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3985 }
Dan Stozabe31f442014-06-11 11:20:54 -07003986 if (sourceCrop.bottom > hw_h) {
3987 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003988 }
3989
Mathias Agopian180f10d2013-04-10 22:55:41 -07003990 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003991 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003992
3993 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003994 engine.setViewportAndProjection(
3995 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003996 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003997
3998 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003999 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004000
Robert Carr1f0a16a2016-10-24 16:27:39 -07004001 // We loop through the first level of layers without traversing,
4002 // as we need to interpret min/max layer Z in the top level Z space.
4003 for (const auto& layer : mDrawingState.layersSortedByZ) {
4004 if (layer->getLayerStack() != hw->getLayerStack()) {
4005 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004006 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004007 const Layer::State& state(layer->getDrawingState());
4008 if (state.z < minLayerZ || state.z > maxLayerZ) {
4009 continue;
4010 }
4011 layer->traverseInZOrder([&](Layer* layer) {
4012 if (!layer->isVisible()) {
4013 return;
4014 }
4015 if (filtering) layer->setFiltering(true);
4016 layer->draw(hw, useIdentityTransform);
4017 if (filtering) layer->setFiltering(false);
4018 });
4019 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004020
Mathias Agopian931bda12013-08-28 18:11:46 -07004021 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022}
4023
4024
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004025status_t SurfaceFlinger::captureScreenImplLocked(
4026 const sp<const DisplayDevice>& hw,
4027 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004028 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004029 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004030 bool useIdentityTransform, Transform::orientation_flags rotation,
4031 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004032{
4033 ATRACE_CALL();
4034
Mathias Agopian180f10d2013-04-10 22:55:41 -07004035 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004036 uint32_t hw_w = hw->getWidth();
4037 uint32_t hw_h = hw->getHeight();
4038
4039 if (rotation & Transform::ROT_90) {
4040 std::swap(hw_w, hw_h);
4041 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004042
Mathias Agopian180f10d2013-04-10 22:55:41 -07004043 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4044 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4045 reqWidth, reqHeight, hw_w, hw_h);
4046 return BAD_VALUE;
4047 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004048
Mathias Agopian180f10d2013-04-10 22:55:41 -07004049 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4050 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4051
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004052 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004053 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004054 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004055 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4056 (state.z < minLayerZ || state.z > maxLayerZ)) {
4057 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004058 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 layer->traverseInZOrder([&](Layer *layer) {
4060 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4061 layer->isSecure());
4062 });
4063 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004064
4065 if (!isLocalScreenshot && secureLayerIsVisible) {
4066 ALOGW("FB is protected: PERMISSION_DENIED");
4067 return PERMISSION_DENIED;
4068 }
4069
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 // create a surface (because we're a producer, and we need to
4071 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004072 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004073
4074 // Put the screenshot Surface into async mode so that
4075 // Layer::headFenceHasSignaled will always return true and we'll latch the
4076 // first buffer regardless of whether or not its acquire fence has
4077 // signaled. This is needed to avoid a race condition in the rotation
4078 // animation. See b/30209608
4079 sur->setAsyncMode(true);
4080
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004082
Michael Lentine5a16a622015-05-21 13:48:24 -07004083 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4084 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004085 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4086 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004087
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004088 int err = 0;
4089 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004090 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004091 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4092 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004093
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004094 if (err == NO_ERROR) {
4095 ANativeWindowBuffer* buffer;
4096 /* TODO: Once we have the sync framework everywhere this can use
4097 * server-side waits on the fence that dequeueBuffer returns.
4098 */
4099 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4100 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004101 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004102 // create an EGLImage from the buffer so we can later
4103 // turn it into a texture
4104 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4105 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4106 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004107 // this binds the given EGLImage as a framebuffer for the
4108 // duration of this scope.
4109 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4110 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004111 // this will in fact render into our dequeued buffer
4112 // via an FBO, which means we didn't have to create
4113 // an EGLSurface and therefore we're not
4114 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004115 renderScreenImplLocked(
4116 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4117 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004118
Riley Andrews86639902014-08-15 12:27:24 -07004119 // Attempt to create a sync khr object that can produce a sync point. If that
4120 // isn't available, create a non-dupable sync object in the fallback path and
4121 // wait on it directly.
4122 EGLSyncKHR sync;
4123 if (!DEBUG_SCREENSHOTS) {
4124 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004125 // native fence fd will not be populated until flush() is done.
4126 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004127 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004128 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004129 }
Riley Andrews86639902014-08-15 12:27:24 -07004130 if (sync != EGL_NO_SYNC_KHR) {
4131 // get the sync fd
4132 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4133 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4134 ALOGW("captureScreen: failed to dup sync khr object");
4135 syncFd = -1;
4136 }
4137 eglDestroySyncKHR(mEGLDisplay, sync);
4138 } else {
4139 // fallback path
4140 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4141 if (sync != EGL_NO_SYNC_KHR) {
4142 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4143 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4144 EGLint eglErr = eglGetError();
4145 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4146 ALOGW("captureScreen: fence wait timed out");
4147 } else {
4148 ALOGW_IF(eglErr != EGL_SUCCESS,
4149 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4150 }
4151 eglDestroySyncKHR(mEGLDisplay, sync);
4152 } else {
4153 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4154 }
4155 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004156 if (DEBUG_SCREENSHOTS) {
4157 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4158 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4159 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4160 hw, minLayerZ, maxLayerZ);
4161 delete [] pixels;
4162 }
4163
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004164 } else {
4165 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4166 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004167 window->cancelBuffer(window, buffer, syncFd);
4168 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004169 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004170 // destroy our image
4171 eglDestroyImageKHR(mEGLDisplay, image);
4172 } else {
4173 result = BAD_VALUE;
4174 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004175 if (buffer) {
4176 // queueBuffer takes ownership of syncFd
4177 result = window->queueBuffer(window, buffer, syncFd);
4178 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004179 }
4180 } else {
4181 result = BAD_VALUE;
4182 }
4183 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4184 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004185
Mathias Agopian74c40c02010-09-29 13:02:36 -07004186 return result;
4187}
4188
Mathias Agopiand5556842013-09-19 17:08:37 -07004189void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004190 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004191 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004192 for (size_t y=0 ; y<h ; y++) {
4193 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4194 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 if (p[x] != 0xFF000000) return;
4196 }
4197 }
4198 ALOGE("*** we just took a black screenshot ***\n"
4199 "requested minz=%d, maxz=%d, layerStack=%d",
4200 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201
Robert Carr2047fae2016-11-28 14:09:09 -08004202 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004203 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004204 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4206 state.z <= maxLayerZ) {
4207 layer->traverseInZOrder([&](Layer* layer) {
4208 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4209 layer->isVisible() ? '+' : '-',
4210 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004211 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004212 i++;
4213 });
4214 }
4215 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004216 }
4217}
4218
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004219// ---------------------------------------------------------------------------
4220
Robert Carr2047fae2016-11-28 14:09:09 -08004221void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4222 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004223}
4224
Robert Carr2047fae2016-11-28 14:09:09 -08004225void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4226 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004227}
4228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004230
4231
4232#if defined(__gl_h_)
4233#error "don't include gl/gl.h in this file"
4234#endif
4235
4236#if defined(__gl2_h_)
4237#error "don't include gl2/gl2.h in this file"
4238#endif