blob: 60c71b39502797dc84d615ce25bb07b6e32d74f7 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
40
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Mathias Agopian921e6ac2012-07-23 23:11:29 -070044#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080049#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080078#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Mathias Agopianca088332013-03-28 17:44:13 -0700100EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107// This is the phase offset in nanoseconds of the software vsync event
108// relative to the vsync event reported by HWComposer. The software vsync
109// event is when SurfaceFlinger and Choreographer-based applications run each
110// frame.
111//
112// This phase offset allows adjustment of the minimum latency from application
113// wake-up (by Choregographer) time to the time at which the resulting window
114// image is displayed. This value may be either positive (after the HW vsync)
115// or negative (before the HW vsync). Setting it to 0 will result in a
116// minimum latency of two vsync periods because the app and SurfaceFlinger
117// will run just after the HW vsync. Setting it to a positive number will
118// result in the minimum latency being:
119//
120// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
121//
122// Note that reducing this latency makes it more likely for the applications
123// to not have their window content image ready in time. When this happens
124// the latency will end up being an additional vsync period, and animations
125// will hiccup. Therefore, this latency should be tuned somewhat
126// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900127static int64_t vsyncPhaseOffsetNs = getInt64<
128 ISurfaceFlingerConfigs,
129 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800132static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700149 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700150 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800151 mHwc(nullptr),
152 mRealHwc(nullptr),
153 mVrHwc(nullptr),
154 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800158 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800159 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700161 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700162 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700163 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700164 mDebugInSwapBuffers(0),
165 mLastSwapBufferTime(0),
166 mDebugInTransaction(0),
167 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700168 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700169 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700170 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000171 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700172 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700173 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800174 mHasColorMatrix(false),
175 mHasPoweredOff(false),
176 mFrameBuckets(),
177 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700178 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800179 mNumLayers(0)
180#ifdef USE_HWC2
181 ,mEnterVrMode(false)
182#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183{
Steve Blocka19954a2012-01-04 20:05:49 +0000184 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185
186 // debugging stuff...
187 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700188
Mathias Agopianb4b17302013-03-20 18:36:41 -0700189 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700190 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 property_get("debug.sf.showupdates", value, "0");
193 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700195 property_get("debug.sf.ddms", value, "0");
196 mDebugDDMS = atoi(value);
197 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700198 if (!startDdmConnection()) {
199 // start failed, and DDMS debugging not enabled
200 mDebugDDMS = 0;
201 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700203 ALOGI_IF(mDebugRegion, "showupdates enabled");
204 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700205
206 property_get("debug.sf.disable_backpressure", value, "0");
207 mPropagateBackpressure = !atoi(value);
208 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700209
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800210 property_get("debug.sf.enable_hwc_vds", value, "0");
211 mUseHwcVirtualDisplays = atoi(value);
212 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800213
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800214 property_get("ro.sf.disable_triple_buffer", value, "1");
215 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800216 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217}
218
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219void SurfaceFlinger::onFirstRef()
220{
221 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800222}
223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224SurfaceFlinger::~SurfaceFlinger()
225{
Mathias Agopiana4912602012-07-12 14:25:33 -0700226 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
227 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
228 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800229
230 if (mVrStateCallbacks.get()) {
231 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
232 defaultServiceManager()->checkService(String16("vrmanager")));
233 if (vrManagerService.get()) {
234 vrManagerService->unregisterListener(mVrStateCallbacks);
235 }
236 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237}
238
Dan Stozac7014012014-02-14 15:03:43 -0800239void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800240{
241 // the window manager died on us. prepare its eulogy.
242
Andy McFadden13a082e2012-08-24 10:16:42 -0700243 // restore initial conditions (default device unblank, etc)
244 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245
246 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700247 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248}
249
Robert Carr1db73f62016-12-21 12:58:51 -0800250static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700251 status_t err = client->initCheck();
252 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800253 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 }
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return nullptr;
256}
257
258sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
259 return initClient(new Client(this));
260}
261
262sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
263 const sp<IGraphicBufferProducer>& gbp) {
264 if (authenticateSurfaceTexture(gbp) == false) {
265 return nullptr;
266 }
267 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
268 if (layer == nullptr) {
269 return nullptr;
270 }
271
272 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273}
274
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700275sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
276 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277{
278 class DisplayToken : public BBinder {
279 sp<SurfaceFlinger> flinger;
280 virtual ~DisplayToken() {
281 // no more references, this display must be terminated
282 Mutex::Autolock _l(flinger->mStateLock);
283 flinger->mCurrentState.displays.removeItem(this);
284 flinger->setTransactionFlags(eDisplayTransactionNeeded);
285 }
286 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700287 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288 : flinger(flinger) {
289 }
290 };
291
292 sp<BBinder> token = new DisplayToken(this);
293
294 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700295 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700296 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700298 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 return token;
300}
301
Jesse Hall6c913be2013-08-08 12:15:49 -0700302void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
303 Mutex::Autolock _l(mStateLock);
304
305 ssize_t idx = mCurrentState.displays.indexOfKey(display);
306 if (idx < 0) {
307 ALOGW("destroyDisplay: invalid display token");
308 return;
309 }
310
311 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
312 if (!info.isVirtualDisplay()) {
313 ALOGE("destroyDisplay called for non-virtual display");
314 return;
315 }
Irvelffc9efc2016-07-27 15:16:37 -0700316 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700317 mCurrentState.displays.removeItemsAt(idx);
318 setTransactionFlags(eDisplayTransactionNeeded);
319}
320
Jesse Hall692c7232012-11-08 15:41:56 -0800321void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800322 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800323 ALOGW_IF(mBuiltinDisplays[type],
324 "Overwriting display token for display type %d", type);
325 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800326 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700327 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800328 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700329 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800330}
331
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700333 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
335 return NULL;
336 }
Jesse Hall692c7232012-11-08 15:41:56 -0800337 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338}
339
Jamie Gennis9a78c902011-01-12 18:30:40 -0800340sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
341{
342 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
343 return gba;
344}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346void SurfaceFlinger::bootFinished()
347{
Wei Wangb254fa32017-01-31 17:43:23 -0800348 if (mStartBootAnimThread->join() != NO_ERROR) {
349 ALOGE("Join StartBootAnimThread failed!");
350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 const nsecs_t now = systemTime();
352 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000353 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700354 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700355
356 // wait patiently for the window manager death
357 const String16 name("window");
358 sp<IBinder> window(defaultServiceManager()->getService(name));
359 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700360 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700361 }
362
363 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 // formerly we would just kill the process, but we now ask it to exit so it
365 // can choose where to stop the animation.
366 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700367
368 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
369 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
370 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800371
372 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
373 defaultServiceManager()->checkService(String16("vrmanager")));
374 if (vrManagerService.get()) {
375 mVrStateCallbacks = new VrStateCallbacks(*this);
376 vrManagerService->registerListener(mVrStateCallbacks);
377 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800573 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800574 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800575 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
577
Jesse Hall692c7232012-11-08 15:41:56 -0800578 Mutex::Autolock _l(mStateLock);
579
Mathias Agopian875d8e12013-06-07 15:35:48 -0700580 // retrieve the EGL context that was selected/created
581 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700582
Mathias Agopianda27af92012-09-13 18:17:13 -0700583 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
584 "couldn't create EGLContext");
585
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 // make the GLContext current so that we can create textures when creating
587 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700588 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
589
Jamie Gennisd1700752013-10-14 12:22:52 -0700590 mEventControlThread = new EventControlThread(this);
591 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
592
Mathias Agopian92a979a2012-08-02 18:32:23 -0700593 // initialize our drawing state
594 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700595
Andy McFadden13a082e2012-08-24 10:16:42 -0700596 // set initial conditions (e.g. unblank default device)
597 initializeDisplays();
598
Dan Stoza4e637772016-07-28 13:31:51 -0700599 mRenderEngine->primeCache();
600
Wei Wangb254fa32017-01-31 17:43:23 -0800601 mStartBootAnimThread = new StartBootAnimThread();
602 if (mStartBootAnimThread->Start() != NO_ERROR) {
603 ALOGE("Run StartBootAnimThread failed!");
604 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800605
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700607}
608
Mathias Agopiana67e4182012-06-19 17:26:12 -0700609void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800610 // Start boot animation service by setting a property mailbox
611 // if property setting thread is already running, Start() will be just a NOP
612 mStartBootAnimThread->Start();
613 // Wait until property was set
614 if (mStartBootAnimThread->join() != NO_ERROR) {
615 ALOGE("Join StartBootAnimThread failed!");
616 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700617}
618
Mathias Agopian875d8e12013-06-07 15:35:48 -0700619size_t SurfaceFlinger::getMaxTextureSize() const {
620 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700621}
622
Mathias Agopian875d8e12013-06-07 15:35:48 -0700623size_t SurfaceFlinger::getMaxViewportDims() const {
624 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700625}
626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800628
Jamie Gennis582270d2011-08-17 18:19:00 -0700629bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800630 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800631 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800632 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700633 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800634}
635
Brian Anderson069b3652016-07-22 10:32:47 -0700636status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700637 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700638 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700639 FrameEvent::REQUESTED_PRESENT,
640 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700641 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700642 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700643 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700644 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700645 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700647 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700648 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700649 };
650 return NO_ERROR;
651}
652
Dan Stoza7f7da322014-05-02 15:26:25 -0700653status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
654 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700655 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700656 return BAD_VALUE;
657 }
658
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500659 if (!display.get())
660 return NAME_NOT_FOUND;
661
Jesse Hall692c7232012-11-08 15:41:56 -0800662 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700663 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800664 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700665 type = i;
666 break;
667 }
668 }
669
670 if (type < 0) {
671 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700672 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700673
Mathias Agopian8b736f12012-08-13 17:54:26 -0700674 // TODO: Not sure if display density should handled by SF any longer
675 class Density {
676 static int getDensityFromProperty(char const* propName) {
677 char property[PROPERTY_VALUE_MAX];
678 int density = 0;
679 if (property_get(propName, property, NULL) > 0) {
680 density = atoi(property);
681 }
682 return density;
683 }
684 public:
685 static int getEmuDensity() {
686 return getDensityFromProperty("qemu.sf.lcd_density"); }
687 static int getBuildDensity() {
688 return getDensityFromProperty("ro.sf.lcd_density"); }
689 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700690
Dan Stoza7f7da322014-05-02 15:26:25 -0700691 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700694 DisplayInfo info = DisplayInfo();
695
Dan Stoza9e56aa02015-11-02 13:00:03 -0800696 float xdpi = hwConfig->getDpiX();
697 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700698
699 if (type == DisplayDevice::DISPLAY_PRIMARY) {
700 // The density of the device is provided by a build property
701 float density = Density::getBuildDensity() / 160.0f;
702 if (density == 0) {
703 // the build doesn't provide a density -- this is wrong!
704 // use xdpi instead
705 ALOGE("ro.sf.lcd_density must be defined as a build property");
706 density = xdpi / 160.0f;
707 }
708 if (Density::getEmuDensity()) {
709 // if "qemu.sf.lcd_density" is specified, it overrides everything
710 xdpi = ydpi = density = Density::getEmuDensity();
711 density /= 160.0f;
712 }
713 info.density = density;
714
715 // TODO: this needs to go away (currently needed only by webkit)
716 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
717 info.orientation = hw->getOrientation();
718 } else {
719 // TODO: where should this value come from?
720 static const int TV_DENSITY = 213;
721 info.density = TV_DENSITY / 160.0f;
722 info.orientation = 0;
723 }
724
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725 info.w = hwConfig->getWidth();
726 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700727 info.xdpi = xdpi;
728 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900730 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731
Andy McFadden91b2ca82014-06-13 14:04:23 -0700732 // This is how far in advance a buffer must be queued for
733 // presentation at a given time. If you want a buffer to appear
734 // on the screen at time N, you must submit the buffer before
735 // (N - presentationDeadline).
736 //
737 // Normally it's one full refresh period (to give SF a chance to
738 // latch the buffer), but this can be reduced by configuring a
739 // DispSync offset. Any additional delays introduced by the hardware
740 // composer or panel must be accounted for here.
741 //
742 // We add an additional 1ms to allow for processing time and
743 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 info.presentationDeadline = hwConfig->getVsyncPeriod() -
745 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700746
747 // All non-virtual displays are currently considered secure.
748 info.secure = true;
749
Michael Wright28f24d02016-07-12 13:30:53 -0700750 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 }
752
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 return NO_ERROR;
754}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700755
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800756status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700757 DisplayStatInfo* stats) {
758 if (stats == NULL) {
759 return BAD_VALUE;
760 }
761
762 // FIXME for now we always return stats for the primary display
763 memset(stats, 0, sizeof(*stats));
764 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
765 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
766 return NO_ERROR;
767}
768
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700769int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800770 if (display == NULL) {
771 ALOGE("%s : display is NULL", __func__);
772 return BAD_VALUE;
773 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700774 sp<DisplayDevice> device(getDisplayDevice(display));
775 if (device != NULL) {
776 return device->getActiveConfig();
777 }
778 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700779}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700780
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700781void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
782 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
783 this);
784 int32_t type = hw->getDisplayType();
785 int currentMode = hw->getActiveConfig();
786
787 if (mode == currentMode) {
788 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
789 return;
790 }
791
792 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
793 ALOGW("Trying to set config for virtual display");
794 return;
795 }
796
797 hw->setActiveConfig(mode);
798 getHwComposer().setActiveConfig(type, mode);
799}
800
801status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
802 class MessageSetActiveConfig: public MessageBase {
803 SurfaceFlinger& mFlinger;
804 sp<IBinder> mDisplay;
805 int mMode;
806 public:
807 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
808 int mode) :
809 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
810 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700811 Vector<DisplayInfo> configs;
812 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700813 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700814 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700815 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700816 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700817 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700818 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
819 if (hw == NULL) {
820 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700821 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700822 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
823 ALOGW("Attempt to set active config = %d for virtual display",
824 mMode);
825 } else {
826 mFlinger.setActiveConfigInternal(hw, mMode);
827 }
828 return true;
829 }
830 };
831 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
832 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700833 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700834}
Michael Wright28f24d02016-07-12 13:30:53 -0700835status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
836 Vector<android_color_mode_t>* outColorModes) {
837 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
838 return BAD_VALUE;
839 }
840
841 if (!display.get()) {
842 return NAME_NOT_FOUND;
843 }
844
845 int32_t type = NAME_NOT_FOUND;
846 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
847 if (display == mBuiltinDisplays[i]) {
848 type = i;
849 break;
850 }
851 }
852
853 if (type < 0) {
854 return type;
855 }
856
857 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
858 outColorModes->clear();
859 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
860
861 return NO_ERROR;
862}
863
864android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
865 sp<DisplayDevice> device(getDisplayDevice(display));
866 if (device != nullptr) {
867 return device->getActiveColorMode();
868 }
869 return static_cast<android_color_mode_t>(BAD_VALUE);
870}
871
872void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
873 android_color_mode_t mode) {
874 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
875 this);
876 int32_t type = hw->getDisplayType();
877 android_color_mode_t currentMode = hw->getActiveColorMode();
878
879 if (mode == currentMode) {
880 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
881 return;
882 }
883
884 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
885 ALOGW("Trying to set config for virtual display");
886 return;
887 }
888
889 hw->setActiveColorMode(mode);
890 getHwComposer().setActiveColorMode(type, mode);
891}
892
893
894status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
895 android_color_mode_t colorMode) {
896 class MessageSetActiveColorMode: public MessageBase {
897 SurfaceFlinger& mFlinger;
898 sp<IBinder> mDisplay;
899 android_color_mode_t mMode;
900 public:
901 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
902 android_color_mode_t mode) :
903 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
904 virtual bool handler() {
905 Vector<android_color_mode_t> modes;
906 mFlinger.getDisplayColorModes(mDisplay, &modes);
907 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
908 if (mMode < 0 || !exists) {
909 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
910 mDisplay.get());
911 return true;
912 }
913 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
914 if (hw == nullptr) {
915 ALOGE("Attempt to set active color mode = %d for null display %p",
916 mMode, mDisplay.get());
917 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
918 ALOGW("Attempt to set active color mode= %d for virtual display",
919 mMode);
920 } else {
921 mFlinger.setActiveColorModeInternal(hw, mMode);
922 }
923 return true;
924 }
925 };
926 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
927 postMessageSync(msg);
928 return NO_ERROR;
929}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700930
Svetoslavd85084b2014-03-20 10:28:31 -0700931status_t SurfaceFlinger::clearAnimationFrameStats() {
932 Mutex::Autolock _l(mStateLock);
933 mAnimFrameTracker.clearStats();
934 return NO_ERROR;
935}
936
937status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
938 Mutex::Autolock _l(mStateLock);
939 mAnimFrameTracker.getStats(outStats);
940 return NO_ERROR;
941}
942
Dan Stozac4f471e2016-03-24 09:31:08 -0700943status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
944 HdrCapabilities* outCapabilities) const {
945 Mutex::Autolock _l(mStateLock);
946
947 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
948 if (displayDevice == nullptr) {
949 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
950 return BAD_VALUE;
951 }
952
953 std::unique_ptr<HdrCapabilities> capabilities =
954 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
955 if (capabilities) {
956 std::swap(*outCapabilities, *capabilities);
957 } else {
958 return BAD_VALUE;
959 }
960
961 return NO_ERROR;
962}
963
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700964status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
965 if (enable == mInjectVSyncs) {
966 return NO_ERROR;
967 }
968
969 if (enable) {
970 mInjectVSyncs = enable;
971 ALOGV("VSync Injections enabled");
972 if (mVSyncInjector.get() == nullptr) {
973 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700974 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700975 }
976 mEventQueue.setEventThread(mInjectorEventThread);
977 } else {
978 mInjectVSyncs = enable;
979 ALOGV("VSync Injections disabled");
980 mEventQueue.setEventThread(mSFEventThread);
981 mVSyncInjector.clear();
982 }
983 return NO_ERROR;
984}
985
986status_t SurfaceFlinger::injectVSync(nsecs_t when) {
987 if (!mInjectVSyncs) {
988 ALOGE("VSync Injections not enabled");
989 return BAD_VALUE;
990 }
991 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
992 ALOGV("Injecting VSync inside SurfaceFlinger");
993 mVSyncInjector->onInjectSyncEvent(when);
994 }
995 return NO_ERROR;
996}
997
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800998// ----------------------------------------------------------------------------
999
1000sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001001 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001002}
1003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001004// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001005
1006void SurfaceFlinger::waitForEvent() {
1007 mEventQueue.waitMessage();
1008}
1009
1010void SurfaceFlinger::signalTransaction() {
1011 mEventQueue.invalidate();
1012}
1013
1014void SurfaceFlinger::signalLayerUpdate() {
1015 mEventQueue.invalidate();
1016}
1017
1018void SurfaceFlinger::signalRefresh() {
1019 mEventQueue.refresh();
1020}
1021
1022status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001023 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001024 return mEventQueue.postMessage(msg, reltime);
1025}
1026
1027status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001028 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001029 status_t res = mEventQueue.postMessage(msg, reltime);
1030 if (res == NO_ERROR) {
1031 msg->wait();
1032 }
1033 return res;
1034}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001036void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001037 do {
1038 waitForEvent();
1039 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040}
1041
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001042void SurfaceFlinger::enableHardwareVsync() {
1043 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001044 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001045 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001046 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1047 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001048 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001049 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050}
1051
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 Mutex::Autolock _l(mHWVsyncLock);
1054
Jesse Hall948fe0c2013-10-14 12:56:09 -07001055 if (makeAvailable) {
1056 mHWVsyncAvailable = true;
1057 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001058 // Hardware vsync is not currently available, so abort the resync
1059 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060 return;
1061 }
1062
Dan Stoza9e56aa02015-11-02 13:00:03 -08001063 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1064 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065
1066 mPrimaryDispSync.reset();
1067 mPrimaryDispSync.setPeriod(period);
1068
1069 if (!mPrimaryHWVsyncEnabled) {
1070 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001071 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1072 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 mPrimaryHWVsyncEnabled = true;
1074 }
1075}
1076
Jesse Hall948fe0c2013-10-14 12:56:09 -07001077void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078 Mutex::Autolock _l(mHWVsyncLock);
1079 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001080 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1081 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 mPrimaryDispSync.endResync();
1083 mPrimaryHWVsyncEnabled = false;
1084 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001085 if (makeUnavailable) {
1086 mHWVsyncAvailable = false;
1087 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088}
1089
Tim Murray4a4e4a22016-04-19 16:29:23 +00001090void SurfaceFlinger::resyncWithRateLimit() {
1091 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1092 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001093 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001094 }
1095}
1096
Steven Thomas3cfac282017-02-06 12:29:30 -08001097void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1098 nsecs_t timestamp) {
1099 Mutex::Autolock lock(mStateLock);
1100 // Ignore any vsyncs from the non-active hardware composer.
1101 if (composer != mHwc) {
1102 return;
1103 }
1104
Jamie Gennisd1700752013-10-14 12:22:52 -07001105 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 { // Scope for the lock
1108 Mutex::Autolock _l(mHWVsyncLock);
1109 if (type == 0 && mPrimaryHWVsyncEnabled) {
1110 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001112 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001113
1114 if (needsHwVsync) {
1115 enableHardwareVsync();
1116 } else {
1117 disableHardwareVsync(false);
1118 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001119}
1120
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001121void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1122 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1123 *compositorTiming = mCompositorTiming;
1124}
1125
Dan Stoza9e56aa02015-11-02 13:00:03 -08001126void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1127 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1128 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1129 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001130
Dan Stoza9e56aa02015-11-02 13:00:03 -08001131 // All non-virtual displays are currently considered secure.
1132 bool isSecure = true;
1133
1134 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001135
1136 // When we're using the vr composer, the assumption is that we've
1137 // already created the IBinder object for the primary display.
1138 if (!mHwc->isUsingVrComposer()) {
1139 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1140 }
1141
Dan Stoza9e56aa02015-11-02 13:00:03 -08001142 wp<IBinder> token = mBuiltinDisplays[type];
1143
1144 sp<IGraphicBufferProducer> producer;
1145 sp<IGraphicBufferConsumer> consumer;
1146 BufferQueue::createBufferQueue(&producer, &consumer,
1147 new GraphicBufferAlloc());
1148
1149 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1150 DisplayDevice::DISPLAY_PRIMARY, consumer);
1151 sp<DisplayDevice> hw = new DisplayDevice(this,
1152 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1153 producer, mRenderEngine->getEGLConfig());
1154 mDisplays.add(token, hw);
1155 } else {
1156 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001157 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001158 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001160 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001161 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1162 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001163 }
1164 setTransactionFlags(eDisplayTransactionNeeded);
1165
Andy McFadden9e9689c2012-10-10 18:17:51 -07001166 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001167 }
Mathias Agopian86303202012-07-24 22:46:10 -07001168}
1169
Steven Thomas3cfac282017-02-06 12:29:30 -08001170void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1171 Mutex::Autolock lock(mStateLock);
1172 if (composer == mHwc) {
1173 repaintEverything();
1174 } else {
1175 // This isn't from our current hardware composer. If it's a callback
1176 // from the real composer, forward the refresh request to vr
1177 // flinger. Otherwise ignore it.
1178 if (!composer->isUsingVrComposer()) {
1179 mVrFlinger->OnHardwareComposerRefresh();
1180 }
1181 }
1182}
1183
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 getHwComposer().setVsyncEnabled(disp,
1187 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001188}
1189
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001190void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1191 for (size_t i = 0; i < layers.size(); ++i) {
1192 layers[i]->clearHwcLayers();
1193 }
1194}
1195
1196void SurfaceFlinger::resetHwc() {
1197 disableHardwareVsync(true);
1198 clearHwcLayers(mDrawingState.layersSortedByZ);
1199 clearHwcLayers(mCurrentState.layersSortedByZ);
1200 // Clear the drawing state so that the logic inside of
1201 // handleTransactionLocked will fire. It will determine the delta between
1202 // mCurrentState and mDrawingState and re-apply all changes when we make the
1203 // transition.
1204 mDrawingState.displays.clear();
1205 mDisplays.clear();
1206}
1207
1208void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001209 bool enteringVrMode = mEnterVrMode;
1210 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1211 return;
1212 }
1213 if (enteringVrMode && !mVrHwc) {
1214 // Construct new HWComposer without holding any locks.
1215 mVrHwc = new HWComposer(true);
1216 ALOGV("Vr HWC created");
1217 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001218 {
1219 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001220
1221 if (enteringVrMode) {
1222 // Start vrflinger thread, if it hasn't been started already.
1223 if (!mVrFlinger) {
1224 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1225 int err = mVrFlinger->Run(mHwc->getComposer());
1226 if (err != NO_ERROR) {
1227 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1228 mVrFlinger.reset();
1229 mEnterVrMode = false;
1230 return;
1231 }
1232 }
1233
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001234 resetHwc();
1235
1236 mHwc = mVrHwc;
1237 mVrFlinger->EnterVrMode();
1238 } else {
1239 mVrFlinger->ExitVrMode();
1240
1241 resetHwc();
1242
1243 mHwc = mRealHwc;
1244 enableHardwareVsync();
1245 }
1246
1247 mVisibleRegionsDirty = true;
1248 invalidateHwcGeometry();
1249 android_atomic_or(1, &mRepaintEverything);
1250 setTransactionFlags(eDisplayTransactionNeeded);
1251 }
1252 if (mVrHwc) {
1253 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1254 }
1255}
1256
Mathias Agopian4fec8732012-06-29 14:12:52 -07001257void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001258 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 case MessageQueue::INVALIDATE: {
Corey Tabakace2c1982017-02-15 17:07:20 -08001261 // TODO(eieio): Disabled until SELinux issues are resolved.
1262 //updateVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001263
Dan Stoza50182882016-07-08 12:02:20 -07001264 bool frameMissed = !mHadClientComposition &&
1265 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001266 (mPreviousPresentFence->getSignalTime() ==
1267 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001268 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001269 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001270 signalLayerUpdate();
1271 break;
1272 }
1273
Dan Stoza6b9454d2014-11-07 16:00:59 -08001274 bool refreshNeeded = handleMessageTransaction();
1275 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001276 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001277 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001278 // Signal a refresh if a transaction modified the window state,
1279 // a new buffer was latched, or if HWC has requested a full
1280 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001281 signalRefresh();
1282 }
1283 break;
1284 }
1285 case MessageQueue::REFRESH: {
1286 handleMessageRefresh();
1287 break;
1288 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289 }
1290}
1291
Dan Stoza6b9454d2014-11-07 16:00:59 -08001292bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001293 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001294 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001295 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001296 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001297 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001298 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001299}
1300
Dan Stoza6b9454d2014-11-07 16:00:59 -08001301bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001302 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001303 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001304}
1305
1306void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001307 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001308
Pablo Ceballos40845df2016-01-25 17:41:15 -08001309 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001310
Brian Andersond6927fb2016-07-23 23:37:30 -07001311 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001312 rebuildLayerStacks();
1313 setUpHWComposer();
1314 doDebugFlashRegions();
1315 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001316 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001317
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001318 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001319
1320 mHadClientComposition = false;
1321 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1322 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1323 mHadClientComposition = mHadClientComposition ||
1324 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1325 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001326
Dan Stoza9e56aa02015-11-02 13:00:03 -08001327 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001328}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001329
Mathias Agopiancd60f992012-08-16 16:28:27 -07001330void SurfaceFlinger::doDebugFlashRegions()
1331{
1332 // is debugging enabled
1333 if (CC_LIKELY(!mDebugRegion))
1334 return;
1335
1336 const bool repaintEverything = mRepaintEverything;
1337 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1338 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001339 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001340 // transform the dirty region into this screen's coordinate space
1341 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1342 if (!dirtyRegion.isEmpty()) {
1343 // redraw the whole screen
1344 doComposeSurfaces(hw, Region(hw->bounds()));
1345
1346 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001347 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001348 RenderEngine& engine(getRenderEngine());
1349 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1350
Mathias Agopianda27af92012-09-13 18:17:13 -07001351 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001352 }
1353 }
1354 }
1355
1356 postFramebuffer();
1357
1358 if (mDebugRegion > 1) {
1359 usleep(mDebugRegion * 1000);
1360 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001361
Dan Stoza9e56aa02015-11-02 13:00:03 -08001362 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001363 auto& displayDevice = mDisplays[displayId];
1364 if (!displayDevice->isDisplayOn()) {
1365 continue;
1366 }
1367
1368 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001369 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1370 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001371 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372}
1373
Brian Andersond6927fb2016-07-23 23:37:30 -07001374void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 ATRACE_CALL();
1377 ALOGV("preComposition");
1378
Mathias Agopiancd60f992012-08-16 16:28:27 -07001379 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001380 mDrawingState.traverseInZOrder([&](Layer* layer) {
1381 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001382 needExtraInvalidate = true;
1383 }
Robert Carr2047fae2016-11-28 14:09:09 -08001384 });
1385
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386 if (needExtraInvalidate) {
1387 signalLayerUpdate();
1388 }
1389}
1390
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391void SurfaceFlinger::updateCompositorTiming(
1392 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1393 std::shared_ptr<FenceTime>& presentFenceTime) {
1394 // Update queue of past composite+present times and determine the
1395 // most recently known composite to present latency.
1396 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1397 nsecs_t compositeToPresentLatency = -1;
1398 while (!mCompositePresentTimes.empty()) {
1399 CompositePresentTime& cpt = mCompositePresentTimes.front();
1400 // Cached values should have been updated before calling this method,
1401 // which helps avoid duplicate syscalls.
1402 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1403 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1404 break;
1405 }
1406 compositeToPresentLatency = displayTime - cpt.composite;
1407 mCompositePresentTimes.pop();
1408 }
1409
1410 // Don't let mCompositePresentTimes grow unbounded, just in case.
1411 while (mCompositePresentTimes.size() > 16) {
1412 mCompositePresentTimes.pop();
1413 }
1414
1415 // Integer division and modulo round toward 0 not -inf, so we need to
1416 // treat negative and positive offsets differently.
1417 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1418 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1419 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1420
1421 // Snap the latency to a value that removes scheduling jitter from the
1422 // composition and present times, which often have >1ms of jitter.
1423 // Reducing jitter is important if an app attempts to extrapolate
1424 // something (such as user input) to an accurate diasplay time.
1425 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1426 // with (presentLatency % interval).
1427 nsecs_t snappedCompositeToPresentLatency = -1;
1428 if (compositeToPresentLatency >= 0) {
1429 nsecs_t bias = vsyncInterval / 2;
1430 int64_t extraVsyncs =
1431 (compositeToPresentLatency - idealLatency + bias) /
1432 vsyncInterval;
1433 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1434 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1435 }
1436
1437 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1438 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1439 mCompositorTiming.interval = vsyncInterval;
1440 if (snappedCompositeToPresentLatency >= 0) {
1441 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1442 }
1443}
1444
1445void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001447 ATRACE_CALL();
1448 ALOGV("postComposition");
1449
Brian Anderson3546a3f2016-07-14 11:51:14 -07001450 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001451 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001452 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001453 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001454 }
1455
Brian Andersond6927fb2016-07-23 23:37:30 -07001456 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001457
1458 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1459 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1460 glCompositionDoneFenceTime =
1461 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1462 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1463 } else {
1464 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1465 }
1466 mGlCompositionDoneTimeline.updateSignalTimes();
1467
1468 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1469 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1470 mDisplayTimeline.push(displayFenceTime);
1471 mDisplayTimeline.updateSignalTimes();
1472
1473 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1474 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1475 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1476 presentFenceTime = &displayFenceTime;
1477 } else {
1478 retireFenceTime = &displayFenceTime;
1479 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480
1481 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1482 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1483
1484 // We use the refreshStartTime which might be sampled a little later than
1485 // when we started doing work for this frame, but that should be okay
1486 // since updateCompositorTiming has snapping logic.
1487 updateCompositorTiming(
1488 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1489
Robert Carr2047fae2016-11-28 14:09:09 -08001490 mDrawingState.traverseInZOrder([&](Layer* layer) {
1491 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001492 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001493 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001494 recordBufferingStats(layer->getName().string(),
1495 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001496 }
Robert Carr2047fae2016-11-28 14:09:09 -08001497 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001498
Brian Anderson3d4039d2016-09-23 16:31:30 -07001499 if (displayFence->isValid()) {
1500 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001501 enableHardwareVsync();
1502 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001503 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001504 }
1505 }
1506
Andy McFadden5167ec62014-05-22 13:08:43 -07001507 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001508 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001509 enableHardwareVsync();
1510 }
1511 }
1512
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001513 if (mAnimCompositionPending) {
1514 mAnimCompositionPending = false;
1515
Brian Anderson3d4039d2016-09-23 16:31:30 -07001516 if (displayFenceTime->isValid()) {
1517 mAnimFrameTracker.setActualPresentFence(
1518 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001519 } else {
1520 // The HWC doesn't support present fences, so use the refresh
1521 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001522 nsecs_t presentTime =
1523 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001524 mAnimFrameTracker.setActualPresentTime(presentTime);
1525 }
1526 mAnimFrameTracker.advanceFrame();
1527 }
Dan Stozab90cf072015-03-05 11:05:59 -08001528
1529 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1530 return;
1531 }
1532
1533 nsecs_t currentTime = systemTime();
1534 if (mHasPoweredOff) {
1535 mHasPoweredOff = false;
1536 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001537 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001539 if (numPeriods < NUM_BUCKETS - 1) {
1540 mFrameBuckets[numPeriods] += elapsedTime;
1541 } else {
1542 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1543 }
1544 mTotalTime += elapsedTime;
1545 }
1546 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
1548
1549void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001550 ATRACE_CALL();
1551 ALOGV("rebuildLayerStacks");
1552
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001554 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001556 mVisibleRegionsDirty = false;
1557 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001558
Mathias Agopian92a979a2012-08-02 18:32:23 -07001559 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001560 Region opaqueRegion;
1561 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 Vector<sp<Layer>> layersSortedByZ;
1563 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1564 const Transform& tr(displayDevice->getTransform());
1565 const Rect bounds(displayDevice->getBounds());
1566 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001567 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001568 displayDevice->getLayerStack(), dirtyRegion,
1569 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001570
Robert Carr2047fae2016-11-28 14:09:09 -08001571 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001572 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001573 Region drawRegion(tr.transform(
1574 layer->visibleNonTransparentRegion));
1575 drawRegion.andSelf(bounds);
1576 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001577 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 } else {
1579 // Clear out the HWC layer if this layer was
1580 // previously visible, but no longer is
1581 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1582 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001583 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001584 }
Robert Carr2047fae2016-11-28 14:09:09 -08001585 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001586 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001587 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1588 displayDevice->undefinedRegion.set(bounds);
1589 displayDevice->undefinedRegion.subtractSelf(
1590 tr.transform(opaqueRegion));
1591 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001592 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001593 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001595
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001597 ATRACE_CALL();
1598 ALOGV("setUpHWComposer");
1599
Jesse Hall028dc8f2013-08-20 16:35:32 -07001600 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001601 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1602 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1603 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1604
1605 // If nothing has changed (!dirty), don't recompose.
1606 // If something changed, but we don't currently have any visible layers,
1607 // and didn't when we last did a composition, then skip it this time.
1608 // The second rule does two things:
1609 // - When all layers are removed from a display, we'll emit one black
1610 // frame, then nothing more until we get new layers.
1611 // - When a display is created with a private layer stack, we won't
1612 // emit any black frames until a layer is added to the layer stack.
1613 bool mustRecompose = dirty && !(empty && wasEmpty);
1614
1615 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1616 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1617 mustRecompose ? "doing" : "skipping",
1618 dirty ? "+" : "-",
1619 empty ? "+" : "-",
1620 wasEmpty ? "+" : "-");
1621
Dan Stoza71433162014-02-04 16:22:36 -08001622 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001623
1624 if (mustRecompose) {
1625 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1626 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001627 }
1628
Dan Stoza9e56aa02015-11-02 13:00:03 -08001629 // build the h/w work list
1630 if (CC_UNLIKELY(mGeometryInvalid)) {
1631 mGeometryInvalid = false;
1632 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1633 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1634 const auto hwcId = displayDevice->getHwcDisplayId();
1635 if (hwcId >= 0) {
1636 const Vector<sp<Layer>>& currentLayers(
1637 displayDevice->getVisibleLayersSortedByZ());
1638 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001639 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001640 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001641 if (!layer->hasHwcLayer(hwcId)) {
1642 auto hwcLayer = mHwc->createLayer(hwcId);
1643 if (hwcLayer) {
1644 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1645 } else {
1646 layer->forceClientComposition(hwcId);
1647 foundLayerWithoutHwc = true;
1648 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001649 }
1650 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001651
Robert Carrae060832016-11-28 10:51:00 -08001652 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001653 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001655 }
1656 }
1657 }
1658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 }
Riley Andrews03414a12014-07-01 14:22:59 -07001660
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001661
1662 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1663
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 // Set the per-frame data
1665 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1666 auto& displayDevice = mDisplays[displayId];
1667 const auto hwcId = displayDevice->getHwcDisplayId();
1668 if (hwcId < 0) {
1669 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001670 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001671 if (colorMatrix != mPreviousColorMatrix) {
1672 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1673 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1674 "display %zd: %d", displayId, result);
1675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001676 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1677 layer->setPerFrameData(displayDevice);
1678 }
1679 }
1680
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001681 mPreviousColorMatrix = colorMatrix;
1682
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001684 auto& displayDevice = mDisplays[displayId];
1685 if (!displayDevice->isDisplayOn()) {
1686 continue;
1687 }
1688
1689 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1691 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001692 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001694
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695void SurfaceFlinger::doComposition() {
1696 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 ALOGV("doComposition");
1698
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001699 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001700 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001701 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001702 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 // transform the dirty region into this screen's coordinate space
1704 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001705
1706 // repaint the framebuffer (if needed)
1707 doDisplayComposition(hw, dirtyRegion);
1708
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709 hw->dirtyRegion.clear();
1710 hw->flip(hw->swapRegion);
1711 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001712 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001714 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715}
1716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001717void SurfaceFlinger::postFramebuffer()
1718{
Mathias Agopian841cde52012-03-01 15:44:37 -08001719 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001720 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001721
Mathias Agopiana44b0412011-10-16 18:46:35 -07001722 const nsecs_t now = systemTime();
1723 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001724
Dan Stoza9e56aa02015-11-02 13:00:03 -08001725 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1726 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001727 if (!displayDevice->isDisplayOn()) {
1728 continue;
1729 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 const auto hwcId = displayDevice->getHwcDisplayId();
1731 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001732 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001733 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001734 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001735 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1737 sp<Fence> releaseFence = Fence::NO_FENCE;
1738 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1739 releaseFence = displayDevice->getClientTargetAcquireFence();
1740 } else {
1741 auto hwcLayer = layer->getHwcLayer(hwcId);
1742 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001743 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 layer->onLayerDisplayed(releaseFence);
1745 }
1746 if (hwcId >= 0) {
1747 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001748 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001749 }
1750
Mathias Agopiana44b0412011-10-16 18:46:35 -07001751 mLastSwapBufferTime = systemTime() - now;
1752 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001753
1754 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1755 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1756 logFrameStats();
1757 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001758}
1759
Mathias Agopian87baae12012-07-31 12:38:26 -07001760void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001761{
Mathias Agopian841cde52012-03-01 15:44:37 -08001762 ATRACE_CALL();
1763
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001764 // here we keep a copy of the drawing state (that is the state that's
1765 // going to be overwritten by handleTransactionLocked()) outside of
1766 // mStateLock so that the side-effects of the State assignment
1767 // don't happen with mStateLock held (which can cause deadlocks).
1768 State drawingState(mDrawingState);
1769
Mathias Agopianca4d3602011-05-19 15:38:14 -07001770 Mutex::Autolock _l(mStateLock);
1771 const nsecs_t now = systemTime();
1772 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773
Mathias Agopianca4d3602011-05-19 15:38:14 -07001774 // Here we're guaranteed that some transaction flags are set
1775 // so we can call handleTransactionLocked() unconditionally.
1776 // We call getTransactionFlags(), which will also clear the flags,
1777 // with mStateLock held to guarantee that mCurrentState won't change
1778 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001779
Mathias Agopiane57f2922012-08-09 16:29:12 -07001780 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001781 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001782
Mathias Agopianca4d3602011-05-19 15:38:14 -07001783 mLastTransactionTime = systemTime() - now;
1784 mDebugInTransaction = 0;
1785 invalidateHwcGeometry();
1786 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001787}
1788
Mathias Agopian87baae12012-07-31 12:38:26 -07001789void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001790{
Dan Stoza7dde5992015-05-22 09:51:44 -07001791 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001792 mCurrentState.traverseInZOrder([](Layer* layer) {
1793 layer->notifyAvailableFrames();
1794 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001795
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001796 /*
1797 * Traversal of the children
1798 * (perform the transaction for each of them if needed)
1799 */
1800
Mathias Agopian3559b072012-08-15 13:46:03 -07001801 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001802 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001803 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001804 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001805
1806 const uint32_t flags = layer->doTransaction(0);
1807 if (flags & Layer::eVisibleRegion)
1808 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001809 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810 }
1811
1812 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001813 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 */
1815
Mathias Agopiane57f2922012-08-09 16:29:12 -07001816 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001817 // here we take advantage of Vector's copy-on-write semantics to
1818 // improve performance by skipping the transaction entirely when
1819 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001820 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1821 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001822 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001823 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001824 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001825 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001826
1827 // find the displays that were removed
1828 // (ie: in drawing state but not in current state)
1829 // also handle displays that changed
1830 // (ie: displays that are in both lists)
1831 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001832 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1833 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001835 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001836 // Call makeCurrent() on the primary display so we can
1837 // be sure that nothing associated with this display
1838 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001839 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001840 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001841 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1842 if (hw != NULL)
1843 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001844 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001845 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001846 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001847 } else {
1848 ALOGW("trying to remove the main display");
1849 }
1850 } else {
1851 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001852 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001853 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001854 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1855 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001856 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001857 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001858 // recreating the DisplayDevice, so we just remove it
1859 // from the drawing state, so that it get re-added
1860 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001861 sp<DisplayDevice> hw(getDisplayDevice(display));
1862 if (hw != NULL)
1863 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001864 mDisplays.removeItem(display);
1865 mDrawingState.displays.removeItemsAt(i);
1866 dc--; i--;
1867 // at this point we must loop to the next item
1868 continue;
1869 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001870
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001871 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001872 if (disp != NULL) {
1873 if (state.layerStack != draw[i].layerStack) {
1874 disp->setLayerStack(state.layerStack);
1875 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001876 if ((state.orientation != draw[i].orientation)
1877 || (state.viewport != draw[i].viewport)
1878 || (state.frame != draw[i].frame))
1879 {
1880 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001881 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001882 }
Michael Lentine47e45402014-07-18 15:34:25 -07001883 if (state.width != draw[i].width || state.height != draw[i].height) {
1884 disp->setDisplaySize(state.width, state.height);
1885 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001886 }
1887 }
1888 }
1889
1890 // find displays that were added
1891 // (ie: in current state but not in drawing state)
1892 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001893 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001894 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001895
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001896 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001897 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001898 sp<IGraphicBufferProducer> bqProducer;
1899 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001900 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1901 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001902
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001904 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001905 // Virtual displays without a surface are dormant:
1906 // they have external state (layer stack, projection,
1907 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001908 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001909
Dan Stoza8cf150a2016-08-02 10:27:31 -07001910 if (mUseHwcVirtualDisplays) {
1911 int width = 0;
1912 int status = state.surface->query(
1913 NATIVE_WINDOW_WIDTH, &width);
1914 ALOGE_IF(status != NO_ERROR,
1915 "Unable to query width (%d)", status);
1916 int height = 0;
1917 status = state.surface->query(
1918 NATIVE_WINDOW_HEIGHT, &height);
1919 ALOGE_IF(status != NO_ERROR,
1920 "Unable to query height (%d)", status);
1921 int intFormat = 0;
1922 status = state.surface->query(
1923 NATIVE_WINDOW_FORMAT, &intFormat);
1924 ALOGE_IF(status != NO_ERROR,
1925 "Unable to query format (%d)", status);
1926 auto format = static_cast<android_pixel_format_t>(
1927 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001928
Dan Stoza8cf150a2016-08-02 10:27:31 -07001929 mHwc->allocateVirtualDisplay(width, height, &format,
1930 &hwcId);
1931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932
Dan Stoza5cf424b2016-05-20 14:02:39 -07001933 // TODO: Plumb requested format back up to consumer
1934
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 sp<VirtualDisplaySurface> vds =
1936 new VirtualDisplaySurface(*mHwc,
1937 hwcId, state.surface, bqProducer,
1938 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001939
1940 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001941 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001942 }
1943 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001944 ALOGE_IF(state.surface!=NULL,
1945 "adding a supported display, but rendering "
1946 "surface is provided (%p), ignoring it",
1947 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001948
1949 hwcId = state.type;
1950 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1951 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001952 }
1953
1954 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001955 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001956 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 state.type, hwcId, state.isSecure, display,
1958 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001959 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001960 hw->setLayerStack(state.layerStack);
1961 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001962 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001963 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001964 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001966 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001967 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001968 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001969 }
1970 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001972 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973
Mathias Agopian84300952012-11-21 16:02:13 -08001974 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1975 // The transform hint might have changed for some layers
1976 // (either because a display has changed, or because a layer
1977 // as changed).
1978 //
1979 // Walk through all the layers in currentLayers,
1980 // and update their transform hint.
1981 //
1982 // If a layer is visible only on a single display, then that
1983 // display is used to calculate the hint, otherwise we use the
1984 // default display.
1985 //
1986 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1987 // the hint is set before we acquire a buffer from the surface texture.
1988 //
1989 // NOTE: layer transactions have taken place already, so we use their
1990 // drawing state. However, SurfaceFlinger's own transaction has not
1991 // happened yet, so we must use the current state layer list
1992 // (soon to become the drawing state list).
1993 //
1994 sp<const DisplayDevice> disp;
1995 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001996 bool first = true;
1997 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001998 // NOTE: we rely on the fact that layers are sorted by
1999 // layerStack first (so we don't have to traverse the list
2000 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002001 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002002 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002003 currentlayerStack = layerStack;
2004 // figure out if this layerstack is mirrored
2005 // (more than one display) if so, pick the default display,
2006 // if not, pick the only display it's on.
2007 disp.clear();
2008 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2009 sp<const DisplayDevice> hw(mDisplays[dpy]);
2010 if (hw->getLayerStack() == currentlayerStack) {
2011 if (disp == NULL) {
2012 disp = hw;
2013 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002014 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002015 break;
2016 }
2017 }
2018 }
2019 }
Chet Haase91d25932013-04-11 15:24:55 -07002020 if (disp == NULL) {
2021 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2022 // redraw after transform hint changes. See bug 8508397.
2023
2024 // could be null when this layer is using a layerStack
2025 // that is not visible on any display. Also can occur at
2026 // screen off/on times.
2027 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002028 }
Chet Haase91d25932013-04-11 15:24:55 -07002029 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002030
2031 first = false;
2032 });
Mathias Agopian84300952012-11-21 16:02:13 -08002033 }
2034
2035
Mathias Agopian3559b072012-08-15 13:46:03 -07002036 /*
2037 * Perform our own transaction if needed
2038 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002039
2040 if (mLayersAdded) {
2041 mLayersAdded = false;
2042 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002043 mVisibleRegionsDirty = true;
2044 }
2045
2046 // some layers might have been removed, so
2047 // we need to update the regions they're exposing.
2048 if (mLayersRemoved) {
2049 mLayersRemoved = false;
2050 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002051 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002052 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002053 // this layer is not visible anymore
2054 // TODO: we could traverse the tree from front to back and
2055 // compute the actual visible region
2056 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002057 Region visibleReg;
2058 visibleReg.set(layer->computeScreenBounds());
2059 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002060 }
Robert Carr2047fae2016-11-28 14:09:09 -08002061 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062 }
2063
2064 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002065
2066 updateCursorAsync();
2067}
2068
2069void SurfaceFlinger::updateCursorAsync()
2070{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2072 auto& displayDevice = mDisplays[displayId];
2073 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002074 continue;
2075 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076
2077 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2078 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002079 }
2080 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002081}
2082
2083void SurfaceFlinger::commitTransaction()
2084{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002085 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002086 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002087 for (const auto& l : mLayersPendingRemoval) {
2088 recordBufferingStats(l->getName().string(),
2089 l->getOccupancyHistory(true));
2090 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091 }
2092 mLayersPendingRemoval.clear();
2093 }
2094
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095 // If this transaction is part of a window animation then the next frame
2096 // we composite should be considered an animation as well.
2097 mAnimCompositionPending = mAnimTransactionPending;
2098
Mathias Agopian4fec8732012-06-29 14:12:52 -07002099 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002100 mDrawingState.traverseInZOrder([](Layer* layer) {
2101 layer->commitChildList();
2102 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002103 mTransactionPending = false;
2104 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002105 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002106}
2107
Robert Carr2047fae2016-11-28 14:09:09 -08002108void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002109 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110{
Mathias Agopian841cde52012-03-01 15:44:37 -08002111 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114 Region aboveOpaqueLayers;
2115 Region aboveCoveredLayers;
2116 Region dirty;
2117
Mathias Agopian87baae12012-07-31 12:38:26 -07002118 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119
Robert Carr2047fae2016-11-28 14:09:09 -08002120 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002122 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123
Jesse Hall01e29052013-02-19 16:13:35 -08002124 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002125 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002126 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002127
Mathias Agopianab028732010-03-16 16:41:46 -07002128 /*
2129 * opaqueRegion: area of a surface that is fully opaque.
2130 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002132
2133 /*
2134 * visibleRegion: area of a surface that is visible on screen
2135 * and not fully transparent. This is essentially the layer's
2136 * footprint minus the opaque regions above it.
2137 * Areas covered by a translucent surface are considered visible.
2138 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002140
2141 /*
2142 * coveredRegion: area of a surface that is covered by all
2143 * visible regions above it (which includes the translucent areas).
2144 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002145 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002146
Jesse Halla8026d22012-09-25 13:25:04 -07002147 /*
2148 * transparentRegion: area of a surface that is hinted to be completely
2149 * transparent. This is only used to tell when the layer has no visible
2150 * non-transparent regions and can be removed from the layer list. It
2151 * does not affect the visibleRegion of this layer or any layers
2152 * beneath it. The hint may not be correct if apps don't respect the
2153 * SurfaceView restrictions (which, sadly, some don't).
2154 */
2155 Region transparentRegion;
2156
Mathias Agopianab028732010-03-16 16:41:46 -07002157
2158 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002159 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002160 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002161 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002163 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002164 if (!visibleRegion.isEmpty()) {
2165 // Remove the transparent area from the visible region
2166 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002167 if (tr.preserveRects()) {
2168 // transform the transparent region
2169 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002170 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002171 // transformation too complex, can't do the
2172 // transparent region optimization.
2173 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002174 }
Mathias Agopianab028732010-03-16 16:41:46 -07002175 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002176
Mathias Agopianab028732010-03-16 16:41:46 -07002177 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002178 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002180 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2181 // the opaque region is the layer's footprint
2182 opaqueRegion = visibleRegion;
2183 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002184 }
2185 }
2186
Mathias Agopianab028732010-03-16 16:41:46 -07002187 // Clip the covered region to the visible region
2188 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2189
2190 // Update aboveCoveredLayers for next (lower) layer
2191 aboveCoveredLayers.orSelf(visibleRegion);
2192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193 // subtract the opaque region covered by the layers above us
2194 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002195
2196 // compute this layer's dirty region
2197 if (layer->contentDirty) {
2198 // we need to invalidate the whole region
2199 dirty = visibleRegion;
2200 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002201 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202 layer->contentDirty = false;
2203 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002204 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002205 * the exposed region consists of two components:
2206 * 1) what's VISIBLE now and was COVERED before
2207 * 2) what's EXPOSED now less what was EXPOSED before
2208 *
2209 * note that (1) is conservative, we start with the whole
2210 * visible region but only keep what used to be covered by
2211 * something -- which mean it may have been exposed.
2212 *
2213 * (2) handles areas that were not covered by anything but got
2214 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002215 */
Mathias Agopianab028732010-03-16 16:41:46 -07002216 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002217 const Region oldVisibleRegion = layer->visibleRegion;
2218 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002219 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2220 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221 }
2222 dirty.subtractSelf(aboveOpaqueLayers);
2223
2224 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002225 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226
Mathias Agopianab028732010-03-16 16:41:46 -07002227 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002229
Jesse Halla8026d22012-09-25 13:25:04 -07002230 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231 layer->setVisibleRegion(visibleRegion);
2232 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002233 layer->setVisibleNonTransparentRegion(
2234 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002235 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236
Mathias Agopian87baae12012-07-31 12:38:26 -07002237 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238}
2239
Mathias Agopian87baae12012-07-31 12:38:26 -07002240void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2241 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002242 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002243 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2244 if (hw->getLayerStack() == layerStack) {
2245 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002246 }
2247 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002248}
2249
Dan Stoza6b9454d2014-11-07 16:00:59 -08002250bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002251{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 ALOGV("handlePageFlip");
2253
Brian Andersond6927fb2016-07-23 23:37:30 -07002254 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255
Mathias Agopian4fec8732012-06-29 14:12:52 -07002256 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002257 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002258
2259 // Store the set of layers that need updates. This set must not change as
2260 // buffers are being latched, as this could result in a deadlock.
2261 // Example: Two producers share the same command stream and:
2262 // 1.) Layer 0 is latched
2263 // 2.) Layer 0 gets a new frame
2264 // 2.) Layer 1 gets a new frame
2265 // 3.) Layer 1 is latched.
2266 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2267 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002268 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002269 if (layer->hasQueuedFrame()) {
2270 frameQueued = true;
2271 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002272 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002273 } else {
2274 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002275 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002276 } else {
2277 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002278 }
Robert Carr2047fae2016-11-28 14:09:09 -08002279 });
2280
Dan Stoza9e56aa02015-11-02 13:00:03 -08002281 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002282 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002283 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002284 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002285 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002286
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002287 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002288
2289 // If we will need to wake up at some time in the future to deal with a
2290 // queued frame that shouldn't be displayed during this vsync period, wake
2291 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002292 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002293 signalLayerUpdate();
2294 }
2295
2296 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002297 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298}
2299
Mathias Agopianad456f92011-01-13 17:53:01 -08002300void SurfaceFlinger::invalidateHwcGeometry()
2301{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002302 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002303}
2304
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002305
Fabien Sanglard830b8472016-11-30 16:35:58 -08002306void SurfaceFlinger::doDisplayComposition(
2307 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002308 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309{
Dan Stoza71433162014-02-04 16:22:36 -08002310 // We only need to actually compose the display if:
2311 // 1) It is being handled by hardware composer, which may need this to
2312 // keep its virtual display state machine in sync, or
2313 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002314 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002315 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002316 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002317 return;
2318 }
2319
Dan Stoza9e56aa02015-11-02 13:00:03 -08002320 ALOGV("doDisplayComposition");
2321
Mathias Agopian87baae12012-07-31 12:38:26 -07002322 Region dirtyRegion(inDirtyRegion);
2323
Mathias Agopianb8a55602009-06-26 19:06:36 -07002324 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002325 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326
Fabien Sanglard830b8472016-11-30 16:35:58 -08002327 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002328 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002329 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2330 // takes a rectangle, we must make sure to update that whole
2331 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002333 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002334 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002335 // We need to redraw the rectangle that will be updated
2336 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002337 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002338 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002340 } else {
2341 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 dirtyRegion.set(displayDevice->bounds());
2343 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 }
2345 }
2346
Fabien Sanglard830b8472016-11-30 16:35:58 -08002347 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002349 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002350 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002351
2352 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002353 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Dan Stoza9e56aa02015-11-02 13:00:03 -08002356bool SurfaceFlinger::doComposeSurfaces(
2357 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002358{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002359 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002360
Dan Stoza9e56aa02015-11-02 13:00:03 -08002361 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002362
2363 mat4 oldColorMatrix;
2364 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2365 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2366 if (applyColorMatrix) {
2367 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2368 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2369 }
2370
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2372 if (hasClientComposition) {
2373 ALOGV("hasClientComposition");
2374
2375 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002376 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002377 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002378 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2379 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2380 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2381 }
2382 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002383 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002384
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002385 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002386 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2387 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002388 // when using overlays, we assume a fully transparent framebuffer
2389 // NOTE: we could reduce how much we need to clear, for instance
2390 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002391 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002392 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002394 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002395 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002397
2398 // we remove the scissor part
2399 // we're left with the letterbox region
2400 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002402
2403 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002405
2406 // but limit it to the dirty region
2407 region.andSelf(dirty);
2408
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002410 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002411 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002413 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002414 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002415
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002417 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002418 // scissor on the main display. It should never be needed
2419 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 const Rect& bounds(displayDevice->getBounds());
2421 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002422 if (scissor != bounds) {
2423 // scissor doesn't match the screen's dimensions, so we
2424 // need to clear everything outside of it and enable
2425 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002426
Mathias Agopianf45c5102012-10-24 16:29:17 -07002427 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 const uint32_t height = displayDevice->getHeight();
2429 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002430 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002431 }
2432 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002433 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002434
Mathias Agopian85d751c2012-08-29 16:59:24 -07002435 /*
2436 * and then, render the layers targeted at the framebuffer
2437 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002438
Dan Stoza9e56aa02015-11-02 13:00:03 -08002439 ALOGV("Rendering client layers");
2440 const Transform& displayTransform = displayDevice->getTransform();
2441 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002442 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 bool firstLayer = true;
2444 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2445 const Region clip(dirty.intersect(
2446 displayTransform.transform(layer->visibleRegion)));
2447 ALOGV("Layer: %s", layer->getName().string());
2448 ALOGV(" Composition type: %s",
2449 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002450 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 switch (layer->getCompositionType(hwcId)) {
2452 case HWC2::Composition::Cursor:
2453 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002454 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002456 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2458 layer->isOpaque(state) && (state.alpha == 1.0f)
2459 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002460 // never clear the very first layer since we're
2461 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002462 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002463 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002464 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002465 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 case HWC2::Composition::Client: {
2467 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002468 break;
2469 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002471 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002472 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 } else {
2474 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002477 }
2478 } else {
2479 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002483 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002485 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002486 }
2487 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002488
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002489 if (applyColorMatrix) {
2490 getRenderEngine().setupColorTransform(oldColorMatrix);
2491 }
2492
Mathias Agopianf45c5102012-10-24 16:29:17 -07002493 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002495 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496}
2497
Fabien Sanglard830b8472016-11-30 16:35:58 -08002498void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2499 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002500 RenderEngine& engine(getRenderEngine());
2501 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502}
2503
Dan Stoza7d89d062015-04-30 13:29:25 -07002504status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002505 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002506 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002507 const sp<Layer>& lbc,
2508 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002509{
Dan Stoza7d89d062015-04-30 13:29:25 -07002510 // add this layer to the current state list
2511 {
2512 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002514 return NO_MEMORY;
2515 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002516 if (parent == nullptr) {
2517 mCurrentState.layersSortedByZ.add(lbc);
2518 } else {
2519 parent->addChild(lbc);
2520 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002521 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002522 mLayersAdded = true;
2523 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002524 }
2525
Mathias Agopian96f08192010-06-02 23:28:45 -07002526 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002527 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002528
Dan Stoza7d89d062015-04-30 13:29:25 -07002529 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002530}
2531
Dan Stoza22851c32016-08-09 13:21:03 -07002532status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002534 sp<Layer> layer = weakLayer.promote();
2535 if (layer == nullptr) {
2536 // The layer has already been removed, carry on
2537 return NO_ERROR;
2538 }
2539
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 const auto& p = layer->getParent();
2541 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2542 mCurrentState.layersSortedByZ.remove(layer);
2543
Robert Carr136e2f62017-02-08 17:54:29 -08002544 // As a matter of normal operation, the LayerCleaner will produce a second
2545 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2546 // so we will succeed in promoting it, but it's already been removed
2547 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2548 // otherwise something has gone wrong and we are leaking the layer.
2549 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2551 layer->getName().string(),
2552 (p != nullptr) ? p->getName().string() : "no-parent");
2553 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002554 } else if (index < 0) {
2555 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002556 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557
2558 mLayersPendingRemoval.add(layer);
2559 mLayersRemoved = true;
2560 mNumLayers--;
2561 setTransactionFlags(eTransactionNeeded);
2562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563}
2564
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002565uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002566 return android_atomic_release_load(&mTransactionFlags);
2567}
2568
Mathias Agopian3f844832013-08-07 21:24:32 -07002569uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2571}
2572
Mathias Agopian3f844832013-08-07 21:24:32 -07002573uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2575 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002576 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 }
2578 return old;
2579}
2580
Mathias Agopian8b33f032012-07-24 20:43:54 -07002581void SurfaceFlinger::setTransactionState(
2582 const Vector<ComposerState>& state,
2583 const Vector<DisplayState>& displays,
2584 uint32_t flags)
2585{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002586 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002587 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002588 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002589
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002590 if (flags & eAnimation) {
2591 // For window updates that are part of an animation we must wait for
2592 // previous animation "frames" to be handled.
2593 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002594 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002595 if (CC_UNLIKELY(err != NO_ERROR)) {
2596 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002597 // caller after a few seconds.
2598 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2599 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002600 mAnimTransactionPending = false;
2601 break;
2602 }
2603 }
2604 }
2605
Mathias Agopiane57f2922012-08-09 16:29:12 -07002606 size_t count = displays.size();
2607 for (size_t i=0 ; i<count ; i++) {
2608 const DisplayState& s(displays[i]);
2609 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002610 }
2611
Mathias Agopiane57f2922012-08-09 16:29:12 -07002612 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002613 for (size_t i=0 ; i<count ; i++) {
2614 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002615 // Here we need to check that the interface we're given is indeed
2616 // one of our own. A malicious client could give us a NULL
2617 // IInterface, or one of its own or even one of our own but a
2618 // different type. All these situations would cause us to crash.
2619 //
2620 // NOTE: it would be better to use RTTI as we could directly check
2621 // that we have a Client*. however, RTTI is disabled in Android.
2622 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002623 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002624 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002625 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002626 sp<Client> client( static_cast<Client *>(s.client.get()) );
2627 transactionFlags |= setClientStateLocked(client, s.state);
2628 }
2629 }
2630 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002631 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002632
Robert Carr2a7dbb42016-05-24 11:41:28 -07002633 // If a synchronous transaction is explicitly requested without any changes,
2634 // force a transaction anyway. This can be used as a flush mechanism for
2635 // previous async transactions.
2636 if (transactionFlags == 0 && (flags & eSynchronous)) {
2637 transactionFlags = eTransactionNeeded;
2638 }
2639
Mathias Agopian386aa982011-11-07 21:58:03 -08002640 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002641 if (mInterceptor.isEnabled()) {
2642 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2643 }
Irvel468051e2016-06-13 16:44:44 -07002644
Mathias Agopian386aa982011-11-07 21:58:03 -08002645 // this triggers the transaction
2646 setTransactionFlags(transactionFlags);
2647
2648 // if this is a synchronous transaction, wait for it to take effect
2649 // before returning.
2650 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002651 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002652 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002653 if (flags & eAnimation) {
2654 mAnimTransactionPending = true;
2655 }
2656 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002657 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2658 if (CC_UNLIKELY(err != NO_ERROR)) {
2659 // just in case something goes wrong in SF, return to the
2660 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002661 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2662 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002663 break;
2664 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667}
2668
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2670{
Jesse Hall9a143922012-10-04 16:29:19 -07002671 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2672 if (dpyIdx < 0)
2673 return 0;
2674
Mathias Agopiane57f2922012-08-09 16:29:12 -07002675 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002676 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002677 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002678 const uint32_t what = s.what;
2679 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002680 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681 disp.surface = s.surface;
2682 flags |= eDisplayTransactionNeeded;
2683 }
2684 }
2685 if (what & DisplayState::eLayerStackChanged) {
2686 if (disp.layerStack != s.layerStack) {
2687 disp.layerStack = s.layerStack;
2688 flags |= eDisplayTransactionNeeded;
2689 }
2690 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002691 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002692 if (disp.orientation != s.orientation) {
2693 disp.orientation = s.orientation;
2694 flags |= eDisplayTransactionNeeded;
2695 }
2696 if (disp.frame != s.frame) {
2697 disp.frame = s.frame;
2698 flags |= eDisplayTransactionNeeded;
2699 }
2700 if (disp.viewport != s.viewport) {
2701 disp.viewport = s.viewport;
2702 flags |= eDisplayTransactionNeeded;
2703 }
2704 }
Michael Lentine47e45402014-07-18 15:34:25 -07002705 if (what & DisplayState::eDisplaySizeChanged) {
2706 if (disp.width != s.width) {
2707 disp.width = s.width;
2708 flags |= eDisplayTransactionNeeded;
2709 }
2710 if (disp.height != s.height) {
2711 disp.height = s.height;
2712 flags |= eDisplayTransactionNeeded;
2713 }
2714 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 }
2716 return flags;
2717}
2718
2719uint32_t SurfaceFlinger::setClientStateLocked(
2720 const sp<Client>& client,
2721 const layer_state_t& s)
2722{
2723 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002724 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002725 if (layer != 0) {
2726 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002727 bool geometryAppliesWithResize =
2728 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002730 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002732 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002733 }
2734 if (what & layer_state_t::eLayerChanged) {
2735 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 const auto& p = layer->getParent();
2737 if (p == nullptr) {
2738 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2739 if (layer->setLayer(s.z) && idx >= 0) {
2740 mCurrentState.layersSortedByZ.removeAt(idx);
2741 mCurrentState.layersSortedByZ.add(layer);
2742 // we need traversal (state changed)
2743 // AND transaction (list changed)
2744 flags |= eTransactionNeeded|eTraversalNeeded;
2745 }
2746 } else {
2747 if (p->setChildLayer(layer, s.z)) {
2748 flags |= eTransactionNeeded|eTraversalNeeded;
2749 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002750 }
2751 }
2752 if (what & layer_state_t::eSizeChanged) {
2753 if (layer->setSize(s.w, s.h)) {
2754 flags |= eTraversalNeeded;
2755 }
2756 }
2757 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759 flags |= eTraversalNeeded;
2760 }
2761 if (what & layer_state_t::eMatrixChanged) {
2762 if (layer->setMatrix(s.matrix))
2763 flags |= eTraversalNeeded;
2764 }
2765 if (what & layer_state_t::eTransparentRegionChanged) {
2766 if (layer->setTransparentRegionHint(s.transparentRegion))
2767 flags |= eTraversalNeeded;
2768 }
Dan Stoza23116082015-06-18 14:58:39 -07002769 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002770 if (layer->setFlags(s.flags, s.mask))
2771 flags |= eTraversalNeeded;
2772 }
2773 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002774 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 flags |= eTraversalNeeded;
2776 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002777 if (what & layer_state_t::eFinalCropChanged) {
2778 if (layer->setFinalCrop(s.finalCrop))
2779 flags |= eTraversalNeeded;
2780 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002781 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 // We only allow setting layer stacks for top level layers,
2784 // everything else inherits layer stack from its parent.
2785 if (layer->hasParent()) {
2786 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2787 layer->getName().string());
2788 } else if (idx < 0) {
2789 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2790 "that also does not appear in the top level layer list. Something"
2791 " has gone wrong.", layer->getName().string());
2792 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793 mCurrentState.layersSortedByZ.removeAt(idx);
2794 mCurrentState.layersSortedByZ.add(layer);
2795 // we need traversal (state changed)
2796 // AND transaction (list changed)
2797 flags |= eTransactionNeeded|eTraversalNeeded;
2798 }
2799 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002800 if (what & layer_state_t::eDeferTransaction) {
2801 layer->deferTransactionUntil(s.handle, s.frameNumber);
2802 // We don't trigger a traversal here because if no other state is
2803 // changed, we don't want this to cause any more work
2804 }
Robert Carr1db73f62016-12-21 12:58:51 -08002805 if (what & layer_state_t::eReparentChildren) {
2806 if (layer->reparentChildren(s.reparentHandle)) {
2807 flags |= eTransactionNeeded|eTraversalNeeded;
2808 }
2809 }
Robert Carrc3574f72016-03-24 12:19:32 -07002810 if (what & layer_state_t::eOverrideScalingModeChanged) {
2811 layer->setOverrideScalingMode(s.overrideScalingMode);
2812 // 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 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002815 }
2816 return flags;
2817}
2818
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002819status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002820 const String8& name,
2821 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002822 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002823 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2824 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002826 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002827 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002828 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002829 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002830 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002831
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002832 status_t result = NO_ERROR;
2833
2834 sp<Layer> layer;
2835
Mathias Agopian3165cc22012-08-08 19:42:09 -07002836 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2837 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002838 result = createNormalLayer(client,
2839 name, w, h, flags, format,
2840 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002842 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002843 result = createDimLayer(client,
2844 name, w, h, flags,
2845 handle, gbp, &layer);
2846 break;
2847 default:
2848 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 break;
2850 }
2851
Dan Stoza7d89d062015-04-30 13:29:25 -07002852 if (result != NO_ERROR) {
2853 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002855
Albert Chaulk479c60c2017-01-27 14:21:34 -05002856 layer->setInfo(windowType, ownerUid);
2857
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002859 if (result != NO_ERROR) {
2860 return result;
2861 }
Irvelffc9efc2016-07-27 15:16:37 -07002862 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002863
2864 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002865 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866}
2867
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002868status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2869 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2870 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871{
2872 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002873 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 case PIXEL_FORMAT_TRANSPARENT:
2875 case PIXEL_FORMAT_TRANSLUCENT:
2876 format = PIXEL_FORMAT_RGBA_8888;
2877 break;
2878 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002879 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 break;
2881 }
2882
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002883 *outLayer = new Layer(this, client, name, w, h, flags);
2884 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2885 if (err == NO_ERROR) {
2886 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002887 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002889
2890 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2891 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002894status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2895 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2896 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002898 *outLayer = new LayerDim(this, client, name, w, h, flags);
2899 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002900 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002901 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002902}
2903
Mathias Agopianac9fa422013-02-11 16:40:36 -08002904status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905{
Mathias Agopian67106042013-03-14 19:18:13 -07002906 // called by the window manager when it wants to remove a Layer
2907 status_t err = NO_ERROR;
2908 sp<Layer> l(client->getLayerUser(handle));
2909 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002910 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002911 err = removeLayer(l);
2912 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2913 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002914 }
2915 return err;
2916}
2917
Mathias Agopian13127d82013-03-05 17:47:11 -08002918status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002919{
Mathias Agopian67106042013-03-14 19:18:13 -07002920 // called by ~LayerCleaner() when all references to the IBinder (handle)
2921 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002922 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923}
2924
Mathias Agopianb60314a2012-04-10 22:09:54 -07002925// ---------------------------------------------------------------------------
2926
Andy McFadden13a082e2012-08-24 10:16:42 -07002927void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002928 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002929 Vector<ComposerState> state;
2930 Vector<DisplayState> displays;
2931 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002932 d.what = DisplayState::eDisplayProjectionChanged |
2933 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002934 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002935 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002936 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002937 d.frame.makeInvalid();
2938 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002939 d.width = 0;
2940 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002941 displays.add(d);
2942 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002943 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2946 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002947 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002948
2949 {
2950 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2951 mCompositorTiming.interval = period;
2952 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002953}
2954
2955void SurfaceFlinger::initializeDisplays() {
2956 class MessageScreenInitialized : public MessageBase {
2957 SurfaceFlinger* flinger;
2958 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002959 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002960 virtual bool handler() {
2961 flinger->onInitializeDisplays();
2962 return true;
2963 }
2964 };
2965 sp<MessageBase> msg = new MessageScreenInitialized(this);
2966 postMessageAsync(msg); // we may be called from main thread, use async message
2967}
2968
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002969void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2970 int mode) {
2971 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2972 this);
2973 int32_t type = hw->getDisplayType();
2974 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002975
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976 if (mode == currentMode) {
2977 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002978 return;
2979 }
2980
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002981 hw->setPowerMode(mode);
2982 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2983 ALOGW("Trying to set power mode for virtual display");
2984 return;
2985 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002986
Irvelffc9efc2016-07-27 15:16:37 -07002987 if (mInterceptor.isEnabled()) {
2988 Mutex::Autolock _l(mStateLock);
2989 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2990 if (idx < 0) {
2991 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2992 return;
2993 }
2994 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2995 }
2996
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002998 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002999 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003000 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3001 // FIXME: eventthread only knows about the main display right now
3002 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003003 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003004 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003007 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003008 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003009
3010 struct sched_param param = {0};
3011 param.sched_priority = 1;
3012 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3013 ALOGW("Couldn't set SCHED_FIFO on display on");
3014 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003016 // Turn off the display
3017 struct sched_param param = {0};
3018 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3019 ALOGW("Couldn't set SCHED_OTHER on display off");
3020 }
3021
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003022 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003023 disableHardwareVsync(true); // also cancels any in-progress resync
3024
Mathias Agopiancde87a32012-09-13 14:09:01 -07003025 // FIXME: eventthread only knows about the main display right now
3026 mEventThread->onScreenReleased();
3027 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003028
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 getHwComposer().setPowerMode(type, mode);
3030 mVisibleRegionsDirty = true;
3031 // from this point on, SF will stop drawing on this display
3032 } else {
3033 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003034 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003035}
3036
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003037void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3038 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003039 SurfaceFlinger& mFlinger;
3040 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003042 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 MessageSetPowerMode(SurfaceFlinger& flinger,
3044 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3045 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003046 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003047 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003048 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003049 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003050 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003051 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003052 ALOGW("Attempt to set power mode = %d for virtual display",
3053 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003054 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003055 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003056 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003057 return true;
3058 }
3059 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003060 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003061 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003062}
3063
3064// ---------------------------------------------------------------------------
3065
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3067{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003069
Mathias Agopianbd115332013-04-18 16:41:04 -07003070 IPCThreadState* ipc = IPCThreadState::self();
3071 const int pid = ipc->getCallingPid();
3072 const int uid = ipc->getCallingUid();
3073 if ((uid != AID_SHELL) &&
3074 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003075 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003076 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003078 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003079 // (this would indicate SF is stuck, but we want to be able to
3080 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003081 status_t err = mStateLock.timedLock(s2ns(1));
3082 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003083 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003084 result.appendFormat(
3085 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3086 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003087 }
3088
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003089 bool dumpAll = true;
3090 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003091 size_t numArgs = args.size();
3092 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003093 if ((index < numArgs) &&
3094 (args[index] == String16("--list"))) {
3095 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003096 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003097 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003098 }
3099
3100 if ((index < numArgs) &&
3101 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003102 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003104 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003105 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003106
3107 if ((index < numArgs) &&
3108 (args[index] == String16("--latency-clear"))) {
3109 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003111 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003113
3114 if ((index < numArgs) &&
3115 (args[index] == String16("--dispsync"))) {
3116 index++;
3117 mPrimaryDispSync.dump(result);
3118 dumpAll = false;
3119 }
Dan Stozab90cf072015-03-05 11:05:59 -08003120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--static-screen"))) {
3123 index++;
3124 dumpStaticScreenStats(result);
3125 dumpAll = false;
3126 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003127
3128 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003129 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003130 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003131 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003132 dumpAll = false;
3133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003136 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003137 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003138 }
3139
Mathias Agopian9795c422009-08-26 16:36:26 -07003140 if (locked) {
3141 mStateLock.unlock();
3142 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
3144 write(fd, result.string(), result.size());
3145 return NO_ERROR;
3146}
3147
Dan Stozac7014012014-02-14 15:03:43 -08003148void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3149 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003150{
Robert Carr2047fae2016-11-28 14:09:09 -08003151 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003152 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003153 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003154}
3155
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003156void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003157 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003158{
3159 String8 name;
3160 if (index < args.size()) {
3161 name = String8(args[index]);
3162 index++;
3163 }
3164
Dan Stoza9e56aa02015-11-02 13:00:03 -08003165 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3166 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003167 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003168
3169 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003170 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003171 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003172 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003173 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003174 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003175 }
Robert Carr2047fae2016-11-28 14:09:09 -08003176 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003177 }
3178}
3179
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003180void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003181 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003182{
3183 String8 name;
3184 if (index < args.size()) {
3185 name = String8(args[index]);
3186 index++;
3187 }
3188
Robert Carr2047fae2016-11-28 14:09:09 -08003189 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003190 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003191 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003192 }
Robert Carr2047fae2016-11-28 14:09:09 -08003193 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003194
Svetoslavd85084b2014-03-20 10:28:31 -07003195 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003196}
3197
Jamie Gennis6547ff42013-07-16 20:12:42 -07003198// This should only be called from the main thread. Otherwise it would need
3199// the lock and should use mCurrentState rather than mDrawingState.
3200void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003202 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003203 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003204
3205 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3206}
3207
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003208void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003209{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003210 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003211#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003212 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003213#endif
3214#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003215 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003216#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217 if (isLayerTripleBufferingDisabled())
3218 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003220}
3221
Dan Stozab90cf072015-03-05 11:05:59 -08003222void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3223{
3224 result.appendFormat("Static screen stats:\n");
3225 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3226 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3227 float percent = 100.0f *
3228 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3229 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3230 b + 1, bucketTimeSec, percent);
3231 }
3232 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3233 float percent = 100.0f *
3234 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3235 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3236 NUM_BUCKETS - 1, bucketTimeSec, percent);
3237}
3238
Dan Stozae77c7662016-05-13 11:37:28 -07003239void SurfaceFlinger::recordBufferingStats(const char* layerName,
3240 std::vector<OccupancyTracker::Segment>&& history) {
3241 Mutex::Autolock lock(mBufferingStatsMutex);
3242 auto& stats = mBufferingStats[layerName];
3243 for (const auto& segment : history) {
3244 if (!segment.usedThirdBuffer) {
3245 stats.twoBufferTime += segment.totalTime;
3246 }
3247 if (segment.occupancyAverage < 1.0f) {
3248 stats.doubleBufferedTime += segment.totalTime;
3249 } else if (segment.occupancyAverage < 2.0f) {
3250 stats.tripleBufferedTime += segment.totalTime;
3251 }
3252 ++stats.numSegments;
3253 stats.totalTime += segment.totalTime;
3254 }
3255}
3256
Brian Andersond6927fb2016-07-23 23:37:30 -07003257void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3258 result.appendFormat("Layer frame timestamps:\n");
3259
3260 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3261 const size_t count = currentLayers.size();
3262 for (size_t i=0 ; i<count ; i++) {
3263 currentLayers[i]->dumpFrameEvents(result);
3264 }
3265}
3266
Dan Stozae77c7662016-05-13 11:37:28 -07003267void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3268 result.append("Buffering stats:\n");
3269 result.append(" [Layer name] <Active time> <Two buffer> "
3270 "<Double buffered> <Triple buffered>\n");
3271 Mutex::Autolock lock(mBufferingStatsMutex);
3272 typedef std::tuple<std::string, float, float, float> BufferTuple;
3273 std::map<float, BufferTuple, std::greater<float>> sorted;
3274 for (const auto& statsPair : mBufferingStats) {
3275 const char* name = statsPair.first.c_str();
3276 const BufferingStats& stats = statsPair.second;
3277 if (stats.numSegments == 0) {
3278 continue;
3279 }
3280 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3281 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3282 stats.totalTime;
3283 float doubleBufferRatio = static_cast<float>(
3284 stats.doubleBufferedTime) / stats.totalTime;
3285 float tripleBufferRatio = static_cast<float>(
3286 stats.tripleBufferedTime) / stats.totalTime;
3287 sorted.insert({activeTime, {name, twoBufferRatio,
3288 doubleBufferRatio, tripleBufferRatio}});
3289 }
3290 for (const auto& sortedPair : sorted) {
3291 float activeTime = sortedPair.first;
3292 const BufferTuple& values = sortedPair.second;
3293 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3294 std::get<0>(values).c_str(), activeTime,
3295 std::get<1>(values), std::get<2>(values),
3296 std::get<3>(values));
3297 }
3298 result.append("\n");
3299}
3300
3301
Mathias Agopian74d211a2013-04-22 16:55:35 +02003302void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3303 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003304{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003305 bool colorize = false;
3306 if (index < args.size()
3307 && (args[index] == String16("--color"))) {
3308 colorize = true;
3309 index++;
3310 }
3311
3312 Colorizer colorizer(colorize);
3313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314 // figure out if we're stuck somewhere
3315 const nsecs_t now = systemTime();
3316 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3317 const nsecs_t inTransaction(mDebugInTransaction);
3318 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3319 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3320
3321 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003322 * Dump library configuration.
3323 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003324
3325 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003326 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003327 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003328 appendSfConfigString(result);
3329 appendUiConfigString(result);
3330 appendGuiConfigString(result);
3331 result.append("\n");
3332
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003333 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003334 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003335 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003336 result.append(SyncFeatures::getInstance().toString());
3337 result.append("\n");
3338
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3340
Andy McFadden41d67d72014-04-25 16:58:34 -07003341 colorizer.bold(result);
3342 result.append("DispSync configuration: ");
3343 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003344 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3345 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3347 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003348 result.append("\n");
3349
Dan Stozab90cf072015-03-05 11:05:59 -08003350 // Dump static screen stats
3351 result.append("\n");
3352 dumpStaticScreenStats(result);
3353 result.append("\n");
3354
Dan Stozae77c7662016-05-13 11:37:28 -07003355 dumpBufferingStats(result);
3356
Andy McFadden4803b742012-09-24 19:07:20 -07003357 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003358 * Dump the visible layer list
3359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003363 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003365 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003366
3367 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003368 * Dump Display state
3369 */
3370
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003371 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003372 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003373 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003374 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3375 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003376 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003377 }
3378
3379 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003380 * Dump SurfaceFlinger global state
3381 */
3382
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003386
Mathias Agopian888c8222012-08-04 21:10:38 -07003387 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003388 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003389
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003390 colorizer.bold(result);
3391 result.appendFormat("EGL implementation : %s\n",
3392 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3393 colorizer.reset(result);
3394 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003395 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003396
Mathias Agopian875d8e12013-06-07 15:35:48 -07003397 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003398
Mathias Agopian42977342012-08-05 00:40:46 -07003399 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3401 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003402 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403 " last eglSwapBuffers() time: %f us\n"
3404 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003405 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003406 " refresh-rate : %f fps\n"
3407 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003408 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003409 " gpu_to_cpu_unsupported : %d\n"
3410 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411 mLastSwapBufferTime/1000.0,
3412 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003413 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 1e9 / activeConfig->getVsyncPeriod(),
3415 activeConfig->getDpiX(),
3416 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003417 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421
Mathias Agopian74d211a2013-04-22 16:55:35 +02003422 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424
3425 /*
3426 * VSYNC state
3427 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003428 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003429 result.append("\n");
3430
3431 /*
3432 * HWC layer minidump
3433 */
3434 for (size_t d = 0; d < mDisplays.size(); d++) {
3435 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3436 int32_t hwcId = displayDevice->getHwcDisplayId();
3437 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3438 continue;
3439 }
3440
3441 result.appendFormat("Display %d HWC layers:\n", hwcId);
3442 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003444 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 });
Dan Stozae22aec72016-08-01 13:20:59 -07003446 result.append("\n");
3447 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448
3449 /*
3450 * Dump HWComposer state
3451 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003452 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003454 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003455 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003456 result.appendFormat(" h/w composer %s\n",
3457 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003458 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459
3460 /*
3461 * Dump gralloc state
3462 */
3463 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3464 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465}
3466
Mathias Agopian13127d82013-03-05 17:47:11 -08003467const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003468SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003469 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003470 wp<IBinder> dpy;
3471 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3472 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3473 dpy = mDisplays.keyAt(i);
3474 break;
3475 }
3476 }
3477 if (dpy == NULL) {
3478 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3479 // Just use the primary display so we have something to return
3480 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3481 }
3482 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003483}
3484
Keun young Park63f165f2012-08-31 10:53:36 -07003485bool SurfaceFlinger::startDdmConnection()
3486{
3487 void* libddmconnection_dso =
3488 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3489 if (!libddmconnection_dso) {
3490 return false;
3491 }
3492 void (*DdmConnection_start)(const char* name);
3493 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003494 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003495 if (!DdmConnection_start) {
3496 dlclose(libddmconnection_dso);
3497 return false;
3498 }
3499 (*DdmConnection_start)(getServiceName());
3500 return true;
3501}
3502
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003503status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 switch (code) {
3505 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003506 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003508 case CLEAR_ANIMATION_FRAME_STATS:
3509 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003511 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 {
3513 // codes that require permission check
3514 IPCThreadState* ipc = IPCThreadState::self();
3515 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003516 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003517 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003518 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003519 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003520 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003522 break;
3523 }
Robert Carr1db73f62016-12-21 12:58:51 -08003524 /*
3525 * Calling setTransactionState is safe, because you need to have been
3526 * granted a reference to Client* and Handle* to do anything with it.
3527 *
3528 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3529 */
3530 case SET_TRANSACTION_STATE:
3531 case CREATE_SCOPED_CONNECTION:
3532 {
3533 return OK;
3534 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003535 case CAPTURE_SCREEN:
3536 {
3537 // codes that require permission check
3538 IPCThreadState* ipc = IPCThreadState::self();
3539 const int pid = ipc->getCallingPid();
3540 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003541 if ((uid != AID_GRAPHICS) &&
3542 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003543 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003544 return PERMISSION_DENIED;
3545 }
3546 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
3548 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003549 return OK;
3550}
3551
3552status_t SurfaceFlinger::onTransact(
3553 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3554{
3555 status_t credentialCheck = CheckTransactCodeCredentials(code);
3556 if (credentialCheck != OK) {
3557 return credentialCheck;
3558 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3561 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003562 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003563 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003564 IPCThreadState* ipc = IPCThreadState::self();
3565 const int pid = ipc->getCallingPid();
3566 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003567 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003568 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569 return PERMISSION_DENIED;
3570 }
3571 int n;
3572 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003573 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003574 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 return NO_ERROR;
3576 case 1002: // SHOW_UPDATES
3577 n = data.readInt32();
3578 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003579 invalidateHwcGeometry();
3580 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003583 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003584 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003586 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 setTransactionFlags(
3588 eTransactionNeeded|
3589 eDisplayTransactionNeeded|
3590 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003591 return NO_ERROR;
3592 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003593 case 1006:{ // send empty update
3594 signalRefresh();
3595 return NO_ERROR;
3596 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003597 case 1008: // toggle use of hw composer
3598 n = data.readInt32();
3599 mDebugDisableHWC = n ? 1 : 0;
3600 invalidateHwcGeometry();
3601 repaintEverything();
3602 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003603 case 1009: // toggle use of transform hint
3604 n = data.readInt32();
3605 mDebugDisableTransformHint = n ? 1 : 0;
3606 invalidateHwcGeometry();
3607 repaintEverything();
3608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003610 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611 reply->writeInt32(0);
3612 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003613 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003614 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 return NO_ERROR;
3616 case 1013: {
3617 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003618 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3619 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003620 return NO_ERROR;
3621 }
3622 case 1014: {
3623 // daltonize
3624 n = data.readInt32();
3625 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003626 case 1:
3627 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3628 break;
3629 case 2:
3630 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3631 break;
3632 case 3:
3633 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3634 break;
3635 default:
3636 mDaltonizer.setType(ColorBlindnessType::None);
3637 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003638 }
3639 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003640 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003641 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003642 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003643 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003644 invalidateHwcGeometry();
3645 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003646 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003648 case 1015: {
3649 // apply a color matrix
3650 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003651 if (n) {
3652 // color matrix is sent as mat3 matrix followed by vec3
3653 // offset, then packed into a mat4 where the last row is
3654 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003655 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003656 for (size_t j = 0; j < 4; j++) {
3657 mColorMatrix[i][j] = data.readFloat();
3658 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003659 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003660 } else {
3661 mColorMatrix = mat4();
3662 }
3663 invalidateHwcGeometry();
3664 repaintEverything();
3665 return NO_ERROR;
3666 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003667 // This is an experimental interface
3668 // Needs to be shifted to proper binder interface when we productize
3669 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003670 n = data.readInt32();
3671 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003672 return NO_ERROR;
3673 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003674 case 1017: {
3675 n = data.readInt32();
3676 mForceFullDamage = static_cast<bool>(n);
3677 return NO_ERROR;
3678 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003679 case 1018: { // Modify Choreographer's phase offset
3680 n = data.readInt32();
3681 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3682 return NO_ERROR;
3683 }
3684 case 1019: { // Modify SurfaceFlinger's phase offset
3685 n = data.readInt32();
3686 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3687 return NO_ERROR;
3688 }
Irvel468051e2016-06-13 16:44:44 -07003689 case 1020: { // Layer updates interceptor
3690 n = data.readInt32();
3691 if (n) {
3692 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003693 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003694 }
3695 else{
3696 ALOGV("Interceptor disabled");
3697 mInterceptor.disable();
3698 }
3699 return NO_ERROR;
3700 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003701 case 1021: { // Disable HWC virtual displays
3702 n = data.readInt32();
3703 mUseHwcVirtualDisplays = !n;
3704 return NO_ERROR;
3705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 }
3707 }
3708 return err;
3709}
3710
Mathias Agopian53331da2011-08-22 21:44:41 -07003711void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003712 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003713 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003714}
3715
Mathias Agopian59119e62010-10-11 12:37:43 -07003716// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003717// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003718// ---------------------------------------------------------------------------
3719
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003720/* The code below is here to handle b/8734824
3721 *
3722 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003723 * from the surfaceflinger thread to the calling binder thread, where they
3724 * are executed. This allows the calling thread in the calling process to be
3725 * reused and not depend on having "enough" binder threads to handle the
3726 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003727 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003728class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003729 /* Parts of GraphicProducerWrapper are run on two different threads,
3730 * communicating by sending messages via Looper but also by shared member
3731 * data. Coherence maintenance is subtle and in places implicit (ugh).
3732 *
3733 * Don't rely on Looper's sendMessage/handleMessage providing
3734 * release/acquire semantics for any data not actually in the Message.
3735 * Data going from surfaceflinger to binder threads needs to be
3736 * synchronized explicitly.
3737 *
3738 * Barrier open/wait do provide release/acquire semantics. This provides
3739 * implicit synchronization for data coming back from binder to
3740 * surfaceflinger threads.
3741 */
3742
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003743 sp<IGraphicBufferProducer> impl;
3744 sp<Looper> looper;
3745 status_t result;
3746 bool exitPending;
3747 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003748 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003749 uint32_t code;
3750 Parcel const* data;
3751 Parcel* reply;
3752
3753 enum {
3754 MSG_API_CALL,
3755 MSG_EXIT
3756 };
3757
3758 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003759 * Called on surfaceflinger thread. This is called by our "fake"
3760 * BpGraphicBufferProducer. We package the data and reply Parcel and
3761 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003762 */
3763 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003764 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003765 this->code = code;
3766 this->data = &data;
3767 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003768 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003769 // if we've exited, we run the message synchronously right here.
3770 // note (JH): as far as I can tell from looking at the code, this
3771 // never actually happens. if it does, i'm not sure if it happens
3772 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003773 handleMessage(Message(MSG_API_CALL));
3774 } else {
3775 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003776 // Prevent stores to this->{code, data, reply} from being
3777 // reordered later than the construction of Message.
3778 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003779 looper->sendMessage(this, Message(MSG_API_CALL));
3780 barrier.wait();
3781 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003782 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 }
3784
3785 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003786 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 * call the real BpGraphicBufferProducer.
3788 */
3789 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003790 int what = message.what;
3791 // Prevent reads below from happening before the read from Message
3792 atomic_thread_fence(memory_order_acquire);
3793 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003794 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003796 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 exitRequested = true;
3798 }
3799 }
3800
3801public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003802 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003803 : impl(impl),
3804 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003805 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003806 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003807 exitRequested(false),
3808 code(0),
3809 data(NULL),
3810 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003811 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812
Jesse Hallb154c422014-07-13 12:47:02 -07003813 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 status_t waitForResponse() {
3815 do {
3816 looper->pollOnce(-1);
3817 } while (!exitRequested);
3818 return result;
3819 }
3820
Jesse Hallb154c422014-07-13 12:47:02 -07003821 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003823 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003825 // Ensure this->result is visible to the binder thread before it
3826 // handles the message.
3827 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 looper->sendMessage(this, Message(MSG_EXIT));
3829 }
3830};
3831
3832
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003833status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3834 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003835 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003836 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003837 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003838
3839 if (CC_UNLIKELY(display == 0))
3840 return BAD_VALUE;
3841
3842 if (CC_UNLIKELY(producer == 0))
3843 return BAD_VALUE;
3844
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003845 // if we have secure windows on this display, never allow the screen capture
3846 // unless the producer interface is local (i.e.: we can take a screenshot for
3847 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003848 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003849
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003850 // Convert to surfaceflinger's internal rotation type.
3851 Transform::orientation_flags rotationFlags;
3852 switch (rotation) {
3853 case ISurfaceComposer::eRotateNone:
3854 rotationFlags = Transform::ROT_0;
3855 break;
3856 case ISurfaceComposer::eRotate90:
3857 rotationFlags = Transform::ROT_90;
3858 break;
3859 case ISurfaceComposer::eRotate180:
3860 rotationFlags = Transform::ROT_180;
3861 break;
3862 case ISurfaceComposer::eRotate270:
3863 rotationFlags = Transform::ROT_270;
3864 break;
3865 default:
3866 rotationFlags = Transform::ROT_0;
3867 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3868 break;
3869 }
3870
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871 class MessageCaptureScreen : public MessageBase {
3872 SurfaceFlinger* flinger;
3873 sp<IBinder> display;
3874 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003875 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003876 uint32_t reqWidth, reqHeight;
3877 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003878 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003879 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003880 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003881 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003882 public:
3883 MessageCaptureScreen(SurfaceFlinger* flinger,
3884 const sp<IBinder>& display,
3885 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003886 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003887 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003888 bool useIdentityTransform,
3889 Transform::orientation_flags rotation,
3890 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003891 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003892 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003893 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003894 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003895 rotation(rotation), result(PERMISSION_DENIED),
3896 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 {
3898 }
3899 status_t getResult() const {
3900 return result;
3901 }
3902 virtual bool handler() {
3903 Mutex::Autolock _l(flinger->mStateLock);
3904 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003905 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003906 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003907 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003908 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 return true;
3910 }
3911 };
3912
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003913 // this creates a "fake" BBinder which will serve as a "fake" remote
3914 // binder to receive the marshaled calls and forward them to the
3915 // real remote (a BpGraphicBufferProducer)
3916 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3917
3918 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3919 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003920 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003921 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003922 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003923 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003924
3925 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 }
3929 return res;
3930}
3931
Mathias Agopian180f10d2013-04-10 22:55:41 -07003932
3933void SurfaceFlinger::renderScreenImplLocked(
3934 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003935 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003936 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003937 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003938{
3939 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003940 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003941
3942 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003943 const int32_t hw_w = hw->getWidth();
3944 const int32_t hw_h = hw->getHeight();
3945 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003946 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003947
Dan Stozac1879002014-05-22 15:59:05 -07003948 // if a default or invalid sourceCrop is passed in, set reasonable values
3949 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3950 !sourceCrop.isValid()) {
3951 sourceCrop.setLeftTop(Point(0, 0));
3952 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3953 }
3954
3955 // ensure that sourceCrop is inside screen
3956 if (sourceCrop.left < 0) {
3957 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3958 }
Dan Stozabe31f442014-06-11 11:20:54 -07003959 if (sourceCrop.right > hw_w) {
3960 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003961 }
3962 if (sourceCrop.top < 0) {
3963 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3964 }
Dan Stozabe31f442014-06-11 11:20:54 -07003965 if (sourceCrop.bottom > hw_h) {
3966 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003967 }
3968
Mathias Agopian180f10d2013-04-10 22:55:41 -07003969 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003970 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003971
3972 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003973 engine.setViewportAndProjection(
3974 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003975 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976
3977 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003978 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979
Robert Carr1f0a16a2016-10-24 16:27:39 -07003980 // We loop through the first level of layers without traversing,
3981 // as we need to interpret min/max layer Z in the top level Z space.
3982 for (const auto& layer : mDrawingState.layersSortedByZ) {
3983 if (layer->getLayerStack() != hw->getLayerStack()) {
3984 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003985 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003986 const Layer::State& state(layer->getDrawingState());
3987 if (state.z < minLayerZ || state.z > maxLayerZ) {
3988 continue;
3989 }
3990 layer->traverseInZOrder([&](Layer* layer) {
3991 if (!layer->isVisible()) {
3992 return;
3993 }
3994 if (filtering) layer->setFiltering(true);
3995 layer->draw(hw, useIdentityTransform);
3996 if (filtering) layer->setFiltering(false);
3997 });
3998 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003999
Mathias Agopian931bda12013-08-28 18:11:46 -07004000 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001}
4002
4003
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004004status_t SurfaceFlinger::captureScreenImplLocked(
4005 const sp<const DisplayDevice>& hw,
4006 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004007 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004008 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004009 bool useIdentityTransform, Transform::orientation_flags rotation,
4010 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004011{
4012 ATRACE_CALL();
4013
Mathias Agopian180f10d2013-04-10 22:55:41 -07004014 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004015 uint32_t hw_w = hw->getWidth();
4016 uint32_t hw_h = hw->getHeight();
4017
4018 if (rotation & Transform::ROT_90) {
4019 std::swap(hw_w, hw_h);
4020 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4023 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4024 reqWidth, reqHeight, hw_w, hw_h);
4025 return BAD_VALUE;
4026 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004027
Mathias Agopian180f10d2013-04-10 22:55:41 -07004028 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4029 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4030
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004031 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004032 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004033 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004034 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4035 (state.z < minLayerZ || state.z > maxLayerZ)) {
4036 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004037 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004038 layer->traverseInZOrder([&](Layer *layer) {
4039 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4040 layer->isSecure());
4041 });
4042 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004043
4044 if (!isLocalScreenshot && secureLayerIsVisible) {
4045 ALOGW("FB is protected: PERMISSION_DENIED");
4046 return PERMISSION_DENIED;
4047 }
4048
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004049 // create a surface (because we're a producer, and we need to
4050 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004051 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004052
4053 // Put the screenshot Surface into async mode so that
4054 // Layer::headFenceHasSignaled will always return true and we'll latch the
4055 // first buffer regardless of whether or not its acquire fence has
4056 // signaled. This is needed to avoid a race condition in the rotation
4057 // animation. See b/30209608
4058 sur->setAsyncMode(true);
4059
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004060 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004061
Michael Lentine5a16a622015-05-21 13:48:24 -07004062 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4063 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004064 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4065 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004066
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004067 int err = 0;
4068 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004069 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4071 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004072
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004073 if (err == NO_ERROR) {
4074 ANativeWindowBuffer* buffer;
4075 /* TODO: Once we have the sync framework everywhere this can use
4076 * server-side waits on the fence that dequeueBuffer returns.
4077 */
4078 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4079 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004080 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 // create an EGLImage from the buffer so we can later
4082 // turn it into a texture
4083 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4084 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4085 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004086 // this binds the given EGLImage as a framebuffer for the
4087 // duration of this scope.
4088 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4089 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004090 // this will in fact render into our dequeued buffer
4091 // via an FBO, which means we didn't have to create
4092 // an EGLSurface and therefore we're not
4093 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004094 renderScreenImplLocked(
4095 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4096 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004097
Riley Andrews86639902014-08-15 12:27:24 -07004098 // Attempt to create a sync khr object that can produce a sync point. If that
4099 // isn't available, create a non-dupable sync object in the fallback path and
4100 // wait on it directly.
4101 EGLSyncKHR sync;
4102 if (!DEBUG_SCREENSHOTS) {
4103 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004104 // native fence fd will not be populated until flush() is done.
4105 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004106 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004107 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004108 }
Riley Andrews86639902014-08-15 12:27:24 -07004109 if (sync != EGL_NO_SYNC_KHR) {
4110 // get the sync fd
4111 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4112 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4113 ALOGW("captureScreen: failed to dup sync khr object");
4114 syncFd = -1;
4115 }
4116 eglDestroySyncKHR(mEGLDisplay, sync);
4117 } else {
4118 // fallback path
4119 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4120 if (sync != EGL_NO_SYNC_KHR) {
4121 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4122 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4123 EGLint eglErr = eglGetError();
4124 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4125 ALOGW("captureScreen: fence wait timed out");
4126 } else {
4127 ALOGW_IF(eglErr != EGL_SUCCESS,
4128 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4129 }
4130 eglDestroySyncKHR(mEGLDisplay, sync);
4131 } else {
4132 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4133 }
4134 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004135 if (DEBUG_SCREENSHOTS) {
4136 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4137 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4138 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4139 hw, minLayerZ, maxLayerZ);
4140 delete [] pixels;
4141 }
4142
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004143 } else {
4144 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4145 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004146 window->cancelBuffer(window, buffer, syncFd);
4147 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004148 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004149 // destroy our image
4150 eglDestroyImageKHR(mEGLDisplay, image);
4151 } else {
4152 result = BAD_VALUE;
4153 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004154 if (buffer) {
4155 // queueBuffer takes ownership of syncFd
4156 result = window->queueBuffer(window, buffer, syncFd);
4157 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004158 }
4159 } else {
4160 result = BAD_VALUE;
4161 }
4162 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4163 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004164
Mathias Agopian74c40c02010-09-29 13:02:36 -07004165 return result;
4166}
4167
Mathias Agopiand5556842013-09-19 17:08:37 -07004168void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004169 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004170 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004171 for (size_t y=0 ; y<h ; y++) {
4172 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4173 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004174 if (p[x] != 0xFF000000) return;
4175 }
4176 }
4177 ALOGE("*** we just took a black screenshot ***\n"
4178 "requested minz=%d, maxz=%d, layerStack=%d",
4179 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004180
Robert Carr2047fae2016-11-28 14:09:09 -08004181 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004182 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004183 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004184 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4185 state.z <= maxLayerZ) {
4186 layer->traverseInZOrder([&](Layer* layer) {
4187 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4188 layer->isVisible() ? '+' : '-',
4189 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004190 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 i++;
4192 });
4193 }
4194 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 }
4196}
4197
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004198// ---------------------------------------------------------------------------
4199
Robert Carr2047fae2016-11-28 14:09:09 -08004200void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4201 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004202}
4203
Robert Carr2047fae2016-11-28 14:09:09 -08004204void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4205 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004206}
4207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004209
4210
4211#if defined(__gl_h_)
4212#error "don't include gl/gl.h in this file"
4213#endif
4214
4215#if defined(__gl2_h_)
4216#error "don't include gl2/gl2.h in this file"
4217#endif