blob: 70bd7be45767754cbeb23934b92eaeb465f8b70a [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
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
87
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#define DISPLAY_COUNT 1
89
Mathias Agopianfee2b462013-07-03 12:34:01 -070090/*
91 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
92 * black pixels.
93 */
94#define DEBUG_SCREENSHOTS false
95
Mathias Agopianca088332013-03-28 17:44:13 -070096EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070099
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100using namespace android::hardware::configstore::V1_0;
101
102static sp<ISurfaceFlingerConfigs> getConfigs() {
103 static sp<ISurfaceFlingerConfigs> configs
104 = ISurfaceFlingerConfigs::getService();
105 return configs;
106}
107
108static int64_t getVsyncEventPhaseOffsetNs() {
109 int64_t ret = 1000000; // default value
110 getConfigs()->vsyncEventPhaseOffsetNs([&](OptionalInt64 value) {
111 if (value.specified) ret = value.value;
112 });
113 return ret;
114}
115
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700116// This is the phase offset in nanoseconds of the software vsync event
117// relative to the vsync event reported by HWComposer. The software vsync
118// event is when SurfaceFlinger and Choreographer-based applications run each
119// frame.
120//
121// This phase offset allows adjustment of the minimum latency from application
122// wake-up (by Choregographer) time to the time at which the resulting window
123// image is displayed. This value may be either positive (after the HW vsync)
124// or negative (before the HW vsync). Setting it to 0 will result in a
125// minimum latency of two vsync periods because the app and SurfaceFlinger
126// will run just after the HW vsync. Setting it to a positive number will
127// result in the minimum latency being:
128//
129// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
130//
131// Note that reducing this latency makes it more likely for the applications
132// to not have their window content image ready in time. When this happens
133// the latency will end up being an additional vsync period, and animations
134// will hiccup. Therefore, this latency should be tuned somewhat
135// conservatively (or at least with awareness of the trade-off being made).
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136static int64_t vsyncPhaseOffsetNs = getVsyncEventPhaseOffsetNs();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700137
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700138// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800139static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141// ---------------------------------------------------------------------------
142
Mathias Agopian99b49842011-06-27 16:05:52 -0700143const String16 sHardwareTest("android.permission.HARDWARE_TEST");
144const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
145const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
146const String16 sDump("android.permission.DUMP");
147
148// ---------------------------------------------------------------------------
149
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700151 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700153 mTransactionPending(false),
154 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700155 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700156 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700157 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700158 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800160 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800162 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800163 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700165 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700166 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700167 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700168 mDebugInSwapBuffers(0),
169 mLastSwapBufferTime(0),
170 mDebugInTransaction(0),
171 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700172 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700173 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700174 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000175 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700176 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700177 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800178 mHasColorMatrix(false),
179 mHasPoweredOff(false),
180 mFrameBuckets(),
181 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700182 mLastSwapTime(0),
183 mNumLayers(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184{
Steve Blocka19954a2012-01-04 20:05:49 +0000185 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186
187 // debugging stuff...
188 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700189
Mathias Agopianb4b17302013-03-20 18:36:41 -0700190 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700191 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193 property_get("debug.sf.showupdates", value, "0");
194 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700195
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196 property_get("debug.sf.ddms", value, "0");
197 mDebugDDMS = atoi(value);
198 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700199 if (!startDdmConnection()) {
200 // start failed, and DDMS debugging not enabled
201 mDebugDDMS = 0;
202 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700203 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700204 ALOGI_IF(mDebugRegion, "showupdates enabled");
205 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700206
207 property_get("debug.sf.disable_backpressure", value, "0");
208 mPropagateBackpressure = !atoi(value);
209 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700210
211 property_get("debug.sf.disable_hwc_vds", value, "0");
212 mUseHwcVirtualDisplays = !atoi(value);
213 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800214
215 property_get("ro.sf.disable_triple_buffer", value, "0");
216 mLayerTripleBufferingDisabled = !atoi(value);
217 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218}
219
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220void SurfaceFlinger::onFirstRef()
221{
222 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800223}
224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225SurfaceFlinger::~SurfaceFlinger()
226{
Mathias Agopiana4912602012-07-12 14:25:33 -0700227 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
228 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
229 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230}
231
Dan Stozac7014012014-02-14 15:03:43 -0800232void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233{
234 // the window manager died on us. prepare its eulogy.
235
Andy McFadden13a082e2012-08-24 10:16:42 -0700236 // restore initial conditions (default device unblank, etc)
237 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238
239 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700240 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241}
242
Robert Carr1db73f62016-12-21 12:58:51 -0800243static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700244 status_t err = client->initCheck();
245 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800246 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 }
Robert Carr1db73f62016-12-21 12:58:51 -0800248 return nullptr;
249}
250
251sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
252 return initClient(new Client(this));
253}
254
255sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
256 const sp<IGraphicBufferProducer>& gbp) {
257 if (authenticateSurfaceTexture(gbp) == false) {
258 return nullptr;
259 }
260 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
261 if (layer == nullptr) {
262 return nullptr;
263 }
264
265 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266}
267
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700268sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
269 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700270{
271 class DisplayToken : public BBinder {
272 sp<SurfaceFlinger> flinger;
273 virtual ~DisplayToken() {
274 // no more references, this display must be terminated
275 Mutex::Autolock _l(flinger->mStateLock);
276 flinger->mCurrentState.displays.removeItem(this);
277 flinger->setTransactionFlags(eDisplayTransactionNeeded);
278 }
279 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700280 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281 : flinger(flinger) {
282 }
283 };
284
285 sp<BBinder> token = new DisplayToken(this);
286
287 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700288 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700289 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700291 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700292 return token;
293}
294
Jesse Hall6c913be2013-08-08 12:15:49 -0700295void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
296 Mutex::Autolock _l(mStateLock);
297
298 ssize_t idx = mCurrentState.displays.indexOfKey(display);
299 if (idx < 0) {
300 ALOGW("destroyDisplay: invalid display token");
301 return;
302 }
303
304 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
305 if (!info.isVirtualDisplay()) {
306 ALOGE("destroyDisplay called for non-virtual display");
307 return;
308 }
Irvelffc9efc2016-07-27 15:16:37 -0700309 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700310 mCurrentState.displays.removeItemsAt(idx);
311 setTransactionFlags(eDisplayTransactionNeeded);
312}
313
Jesse Hall692c7232012-11-08 15:41:56 -0800314void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800315 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800316 ALOGW_IF(mBuiltinDisplays[type],
317 "Overwriting display token for display type %d", type);
318 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800319 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700320 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800321 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700322 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800323}
324
Mathias Agopiane57f2922012-08-09 16:29:12 -0700325sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700326 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700327 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
328 return NULL;
329 }
Jesse Hall692c7232012-11-08 15:41:56 -0800330 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331}
332
Jamie Gennis9a78c902011-01-12 18:30:40 -0800333sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
334{
335 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
336 return gba;
337}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339void SurfaceFlinger::bootFinished()
340{
Wei Wangb254fa32017-01-31 17:43:23 -0800341 if (mStartBootAnimThread->join() != NO_ERROR) {
342 ALOGE("Join StartBootAnimThread failed!");
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 const nsecs_t now = systemTime();
345 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000346 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700347 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700348
349 // wait patiently for the window manager death
350 const String16 name("window");
351 sp<IBinder> window(defaultServiceManager()->getService(name));
352 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700353 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700354 }
355
356 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700357 // formerly we would just kill the process, but we now ask it to exit so it
358 // can choose where to stop the animation.
359 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700360
361 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
362 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
363 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364}
365
Mathias Agopian3f844832013-08-07 21:24:32 -0700366void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700367 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700368 RenderEngine& engine;
369 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700370 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700371 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
372 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700373 }
374 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376 return true;
377 }
378 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700379 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380}
381
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700382class DispSyncSource : public VSyncSource, private DispSync::Callback {
383public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700384 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000385 const char* name) :
386 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700387 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700388 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000389 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
390 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700391 mDispSync(dispSync),
392 mCallbackMutex(),
393 mCallback(),
394 mVsyncMutex(),
395 mPhaseOffset(phaseOffset),
396 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700397
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398 virtual ~DispSyncSource() {}
399
400 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700401 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700402 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error registering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700409 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 } else {
411 status_t err = mDispSync->removeEventListener(
412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error unregistering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700417 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 }
421
422 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 mCallback = callback;
425 }
426
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700427 virtual void setPhaseOffset(nsecs_t phaseOffset) {
428 Mutex::Autolock lock(mVsyncMutex);
429
430 // Normalize phaseOffset to [0, period)
431 auto period = mDispSync->getPeriod();
432 phaseOffset %= period;
433 if (phaseOffset < 0) {
434 // If we're here, then phaseOffset is in (-period, 0). After this
435 // operation, it will be in (0, period)
436 phaseOffset += period;
437 }
438 mPhaseOffset = phaseOffset;
439
440 // If we're not enabled, we don't need to mess with the listeners
441 if (!mEnabled) {
442 return;
443 }
444
445 // Remove the listener with the old offset
446 status_t err = mDispSync->removeEventListener(
447 static_cast<DispSync::Callback*>(this));
448 if (err != NO_ERROR) {
449 ALOGE("error unregistering vsync callback: %s (%d)",
450 strerror(-err), err);
451 }
452
453 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000454 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error registering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
460 }
461
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462private:
463 virtual void onDispSyncEvent(nsecs_t when) {
464 sp<VSyncSource::Callback> callback;
465 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 callback = mCallback;
468
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700469 if (mTraceVsync) {
470 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700471 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700472 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 }
474
475 if (callback != NULL) {
476 callback->onVSyncEvent(when);
477 }
478 }
479
Tim Murray4a4e4a22016-04-19 16:29:23 +0000480 const char* const mName;
481
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 int mValue;
483
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 const String8 mVsyncOnLabel;
486 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700487
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489
490 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700492
493 Mutex mVsyncMutex; // Protects the following
494 nsecs_t mPhaseOffset;
495 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496};
497
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700498class InjectVSyncSource : public VSyncSource {
499public:
500 InjectVSyncSource() {}
501
502 virtual ~InjectVSyncSource() {}
503
504 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
505 std::lock_guard<std::mutex> lock(mCallbackMutex);
506 mCallback = callback;
507 }
508
509 virtual void onInjectSyncEvent(nsecs_t when) {
510 std::lock_guard<std::mutex> lock(mCallbackMutex);
511 mCallback->onVSyncEvent(when);
512 }
513
514 virtual void setVSyncEnabled(bool) {}
515 virtual void setPhaseOffset(nsecs_t) {}
516
517private:
518 std::mutex mCallbackMutex; // Protects the following
519 sp<VSyncSource::Callback> mCallback;
520};
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700523 ALOGI( "SurfaceFlinger's main thread ready to run. "
524 "Initializing graphics H/W...");
525
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900526 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
527
Dan Stoza9e56aa02015-11-02 13:00:03 -0800528 { // Autolock scope
529 Mutex::Autolock _l(mStateLock);
530
531 // initialize EGL for the default display
532 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
533 eglInitialize(mEGLDisplay, NULL, NULL);
534
535 // start the EventThread
536 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
537 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700538 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800539 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
540 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700541 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 mEventQueue.setEventThread(mSFEventThread);
543
Tim Murrayacff43d2016-07-29 13:57:24 -0700544 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700545 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700546 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700547 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
548 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
549 }
550
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 // Get a RenderEngine for the given display / config (can't fail)
552 mRenderEngine = RenderEngine::create(mEGLDisplay,
553 HAL_PIXEL_FORMAT_RGBA_8888);
554 }
555
556 // Drop the state lock while we initialize the hardware composer. We drop
557 // the lock because on creation, it will call back into SurfaceFlinger to
558 // initialize the primary display.
559 mHwc = new HWComposer(this);
560 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
561
Jesse Hall692c7232012-11-08 15:41:56 -0800562 Mutex::Autolock _l(mStateLock);
563
Mathias Agopian875d8e12013-06-07 15:35:48 -0700564 // retrieve the EGL context that was selected/created
565 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700566
Mathias Agopianda27af92012-09-13 18:17:13 -0700567 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
568 "couldn't create EGLContext");
569
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 // make the GLContext current so that we can create textures when creating
571 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700572 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
573
Jamie Gennisd1700752013-10-14 12:22:52 -0700574 mEventControlThread = new EventControlThread(this);
575 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
576
Mathias Agopian92a979a2012-08-02 18:32:23 -0700577 // initialize our drawing state
578 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700579
Andy McFadden13a082e2012-08-24 10:16:42 -0700580 // set initial conditions (e.g. unblank default device)
581 initializeDisplays();
582
Dan Stoza4e637772016-07-28 13:31:51 -0700583 mRenderEngine->primeCache();
584
Wei Wangb254fa32017-01-31 17:43:23 -0800585 mStartBootAnimThread = new StartBootAnimThread();
586 if (mStartBootAnimThread->Start() != NO_ERROR) {
587 ALOGE("Run StartBootAnimThread failed!");
588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700591}
592
Mathias Agopiana67e4182012-06-19 17:26:12 -0700593void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800594 // Start boot animation service by setting a property mailbox
595 // if property setting thread is already running, Start() will be just a NOP
596 mStartBootAnimThread->Start();
597 // Wait until property was set
598 if (mStartBootAnimThread->join() != NO_ERROR) {
599 ALOGE("Join StartBootAnimThread failed!");
600 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700601}
602
Mathias Agopian875d8e12013-06-07 15:35:48 -0700603size_t SurfaceFlinger::getMaxTextureSize() const {
604 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700605}
606
Mathias Agopian875d8e12013-06-07 15:35:48 -0700607size_t SurfaceFlinger::getMaxViewportDims() const {
608 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700609}
610
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800611// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800612
Jamie Gennis582270d2011-08-17 18:19:00 -0700613bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800614 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800615 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800616 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700617 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800618}
619
Brian Anderson069b3652016-07-22 10:32:47 -0700620status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700621 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700622 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700623 FrameEvent::REQUESTED_PRESENT,
624 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700625 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700626 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700627 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700628 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700629 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700630 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700631 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700632 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700633 };
634 return NO_ERROR;
635}
636
Dan Stoza7f7da322014-05-02 15:26:25 -0700637status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
638 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700639 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700640 return BAD_VALUE;
641 }
642
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500643 if (!display.get())
644 return NAME_NOT_FOUND;
645
Jesse Hall692c7232012-11-08 15:41:56 -0800646 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700647 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800648 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700649 type = i;
650 break;
651 }
652 }
653
654 if (type < 0) {
655 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700656 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700657
Mathias Agopian8b736f12012-08-13 17:54:26 -0700658 // TODO: Not sure if display density should handled by SF any longer
659 class Density {
660 static int getDensityFromProperty(char const* propName) {
661 char property[PROPERTY_VALUE_MAX];
662 int density = 0;
663 if (property_get(propName, property, NULL) > 0) {
664 density = atoi(property);
665 }
666 return density;
667 }
668 public:
669 static int getEmuDensity() {
670 return getDensityFromProperty("qemu.sf.lcd_density"); }
671 static int getBuildDensity() {
672 return getDensityFromProperty("ro.sf.lcd_density"); }
673 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700674
Dan Stoza7f7da322014-05-02 15:26:25 -0700675 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700676
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700678 DisplayInfo info = DisplayInfo();
679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 float xdpi = hwConfig->getDpiX();
681 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700682
683 if (type == DisplayDevice::DISPLAY_PRIMARY) {
684 // The density of the device is provided by a build property
685 float density = Density::getBuildDensity() / 160.0f;
686 if (density == 0) {
687 // the build doesn't provide a density -- this is wrong!
688 // use xdpi instead
689 ALOGE("ro.sf.lcd_density must be defined as a build property");
690 density = xdpi / 160.0f;
691 }
692 if (Density::getEmuDensity()) {
693 // if "qemu.sf.lcd_density" is specified, it overrides everything
694 xdpi = ydpi = density = Density::getEmuDensity();
695 density /= 160.0f;
696 }
697 info.density = density;
698
699 // TODO: this needs to go away (currently needed only by webkit)
700 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
701 info.orientation = hw->getOrientation();
702 } else {
703 // TODO: where should this value come from?
704 static const int TV_DENSITY = 213;
705 info.density = TV_DENSITY / 160.0f;
706 info.orientation = 0;
707 }
708
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 info.w = hwConfig->getWidth();
710 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700711 info.xdpi = xdpi;
712 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900714 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800715
Andy McFadden91b2ca82014-06-13 14:04:23 -0700716 // This is how far in advance a buffer must be queued for
717 // presentation at a given time. If you want a buffer to appear
718 // on the screen at time N, you must submit the buffer before
719 // (N - presentationDeadline).
720 //
721 // Normally it's one full refresh period (to give SF a chance to
722 // latch the buffer), but this can be reduced by configuring a
723 // DispSync offset. Any additional delays introduced by the hardware
724 // composer or panel must be accounted for here.
725 //
726 // We add an additional 1ms to allow for processing time and
727 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 info.presentationDeadline = hwConfig->getVsyncPeriod() -
729 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700730
731 // All non-virtual displays are currently considered secure.
732 info.secure = true;
733
Michael Wright28f24d02016-07-12 13:30:53 -0700734 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700735 }
736
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 return NO_ERROR;
738}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700739
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800740status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700741 DisplayStatInfo* stats) {
742 if (stats == NULL) {
743 return BAD_VALUE;
744 }
745
746 // FIXME for now we always return stats for the primary display
747 memset(stats, 0, sizeof(*stats));
748 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
749 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
750 return NO_ERROR;
751}
752
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700753int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800754 if (display == NULL) {
755 ALOGE("%s : display is NULL", __func__);
756 return BAD_VALUE;
757 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700758 sp<DisplayDevice> device(getDisplayDevice(display));
759 if (device != NULL) {
760 return device->getActiveConfig();
761 }
762 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700763}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700764
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700765void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
766 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
767 this);
768 int32_t type = hw->getDisplayType();
769 int currentMode = hw->getActiveConfig();
770
771 if (mode == currentMode) {
772 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
773 return;
774 }
775
776 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
777 ALOGW("Trying to set config for virtual display");
778 return;
779 }
780
781 hw->setActiveConfig(mode);
782 getHwComposer().setActiveConfig(type, mode);
783}
784
785status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
786 class MessageSetActiveConfig: public MessageBase {
787 SurfaceFlinger& mFlinger;
788 sp<IBinder> mDisplay;
789 int mMode;
790 public:
791 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
792 int mode) :
793 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
794 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700795 Vector<DisplayInfo> configs;
796 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700797 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700798 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700799 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700800 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700801 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700802 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
803 if (hw == NULL) {
804 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700805 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700806 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
807 ALOGW("Attempt to set active config = %d for virtual display",
808 mMode);
809 } else {
810 mFlinger.setActiveConfigInternal(hw, mMode);
811 }
812 return true;
813 }
814 };
815 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
816 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700817 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818}
Michael Wright28f24d02016-07-12 13:30:53 -0700819status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
820 Vector<android_color_mode_t>* outColorModes) {
821 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
822 return BAD_VALUE;
823 }
824
825 if (!display.get()) {
826 return NAME_NOT_FOUND;
827 }
828
829 int32_t type = NAME_NOT_FOUND;
830 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
831 if (display == mBuiltinDisplays[i]) {
832 type = i;
833 break;
834 }
835 }
836
837 if (type < 0) {
838 return type;
839 }
840
841 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
842 outColorModes->clear();
843 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
844
845 return NO_ERROR;
846}
847
848android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
849 sp<DisplayDevice> device(getDisplayDevice(display));
850 if (device != nullptr) {
851 return device->getActiveColorMode();
852 }
853 return static_cast<android_color_mode_t>(BAD_VALUE);
854}
855
856void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
857 android_color_mode_t mode) {
858 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
859 this);
860 int32_t type = hw->getDisplayType();
861 android_color_mode_t currentMode = hw->getActiveColorMode();
862
863 if (mode == currentMode) {
864 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
865 return;
866 }
867
868 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
869 ALOGW("Trying to set config for virtual display");
870 return;
871 }
872
873 hw->setActiveColorMode(mode);
874 getHwComposer().setActiveColorMode(type, mode);
875}
876
877
878status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
879 android_color_mode_t colorMode) {
880 class MessageSetActiveColorMode: public MessageBase {
881 SurfaceFlinger& mFlinger;
882 sp<IBinder> mDisplay;
883 android_color_mode_t mMode;
884 public:
885 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
886 android_color_mode_t mode) :
887 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
888 virtual bool handler() {
889 Vector<android_color_mode_t> modes;
890 mFlinger.getDisplayColorModes(mDisplay, &modes);
891 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
892 if (mMode < 0 || !exists) {
893 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
894 mDisplay.get());
895 return true;
896 }
897 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
898 if (hw == nullptr) {
899 ALOGE("Attempt to set active color mode = %d for null display %p",
900 mMode, mDisplay.get());
901 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
902 ALOGW("Attempt to set active color mode= %d for virtual display",
903 mMode);
904 } else {
905 mFlinger.setActiveColorModeInternal(hw, mMode);
906 }
907 return true;
908 }
909 };
910 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
911 postMessageSync(msg);
912 return NO_ERROR;
913}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700914
Svetoslavd85084b2014-03-20 10:28:31 -0700915status_t SurfaceFlinger::clearAnimationFrameStats() {
916 Mutex::Autolock _l(mStateLock);
917 mAnimFrameTracker.clearStats();
918 return NO_ERROR;
919}
920
921status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
922 Mutex::Autolock _l(mStateLock);
923 mAnimFrameTracker.getStats(outStats);
924 return NO_ERROR;
925}
926
Dan Stozac4f471e2016-03-24 09:31:08 -0700927status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
928 HdrCapabilities* outCapabilities) const {
929 Mutex::Autolock _l(mStateLock);
930
931 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
932 if (displayDevice == nullptr) {
933 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
934 return BAD_VALUE;
935 }
936
937 std::unique_ptr<HdrCapabilities> capabilities =
938 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
939 if (capabilities) {
940 std::swap(*outCapabilities, *capabilities);
941 } else {
942 return BAD_VALUE;
943 }
944
945 return NO_ERROR;
946}
947
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700948status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
949 if (enable == mInjectVSyncs) {
950 return NO_ERROR;
951 }
952
953 if (enable) {
954 mInjectVSyncs = enable;
955 ALOGV("VSync Injections enabled");
956 if (mVSyncInjector.get() == nullptr) {
957 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700958 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700959 }
960 mEventQueue.setEventThread(mInjectorEventThread);
961 } else {
962 mInjectVSyncs = enable;
963 ALOGV("VSync Injections disabled");
964 mEventQueue.setEventThread(mSFEventThread);
965 mVSyncInjector.clear();
966 }
967 return NO_ERROR;
968}
969
970status_t SurfaceFlinger::injectVSync(nsecs_t when) {
971 if (!mInjectVSyncs) {
972 ALOGE("VSync Injections not enabled");
973 return BAD_VALUE;
974 }
975 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
976 ALOGV("Injecting VSync inside SurfaceFlinger");
977 mVSyncInjector->onInjectSyncEvent(when);
978 }
979 return NO_ERROR;
980}
981
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800982// ----------------------------------------------------------------------------
983
984sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800985 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700986}
987
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800988// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800989
990void SurfaceFlinger::waitForEvent() {
991 mEventQueue.waitMessage();
992}
993
994void SurfaceFlinger::signalTransaction() {
995 mEventQueue.invalidate();
996}
997
998void SurfaceFlinger::signalLayerUpdate() {
999 mEventQueue.invalidate();
1000}
1001
1002void SurfaceFlinger::signalRefresh() {
1003 mEventQueue.refresh();
1004}
1005
1006status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001007 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001008 return mEventQueue.postMessage(msg, reltime);
1009}
1010
1011status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001012 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001013 status_t res = mEventQueue.postMessage(msg, reltime);
1014 if (res == NO_ERROR) {
1015 msg->wait();
1016 }
1017 return res;
1018}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001020void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001021 do {
1022 waitForEvent();
1023 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024}
1025
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001026void SurfaceFlinger::enableHardwareVsync() {
1027 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001028 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001030 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1031 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001032 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001033 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001034}
1035
Jesse Hall948fe0c2013-10-14 12:56:09 -07001036void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001037 Mutex::Autolock _l(mHWVsyncLock);
1038
Jesse Hall948fe0c2013-10-14 12:56:09 -07001039 if (makeAvailable) {
1040 mHWVsyncAvailable = true;
1041 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001042 // Hardware vsync is not currently available, so abort the resync
1043 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001044 return;
1045 }
1046
Dan Stoza9e56aa02015-11-02 13:00:03 -08001047 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1048 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049
1050 mPrimaryDispSync.reset();
1051 mPrimaryDispSync.setPeriod(period);
1052
1053 if (!mPrimaryHWVsyncEnabled) {
1054 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1056 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057 mPrimaryHWVsyncEnabled = true;
1058 }
1059}
1060
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001062 Mutex::Autolock _l(mHWVsyncLock);
1063 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001064 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1065 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001066 mPrimaryDispSync.endResync();
1067 mPrimaryHWVsyncEnabled = false;
1068 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069 if (makeUnavailable) {
1070 mHWVsyncAvailable = false;
1071 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072}
1073
Tim Murray4a4e4a22016-04-19 16:29:23 +00001074void SurfaceFlinger::resyncWithRateLimit() {
1075 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1076 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001077 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001078 }
1079}
1080
Dan Stoza9e56aa02015-11-02 13:00:03 -08001081void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001082 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083
Jamie Gennisd1700752013-10-14 12:22:52 -07001084 { // Scope for the lock
1085 Mutex::Autolock _l(mHWVsyncLock);
1086 if (type == 0 && mPrimaryHWVsyncEnabled) {
1087 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001089 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001090
1091 if (needsHwVsync) {
1092 enableHardwareVsync();
1093 } else {
1094 disableHardwareVsync(false);
1095 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001096}
1097
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001098void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1099 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1100 *compositorTiming = mCompositorTiming;
1101}
1102
Dan Stoza9e56aa02015-11-02 13:00:03 -08001103void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1104 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1105 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1106 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001107
Dan Stoza9e56aa02015-11-02 13:00:03 -08001108 // All non-virtual displays are currently considered secure.
1109 bool isSecure = true;
1110
1111 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1112 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1113 wp<IBinder> token = mBuiltinDisplays[type];
1114
1115 sp<IGraphicBufferProducer> producer;
1116 sp<IGraphicBufferConsumer> consumer;
1117 BufferQueue::createBufferQueue(&producer, &consumer,
1118 new GraphicBufferAlloc());
1119
1120 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1121 DisplayDevice::DISPLAY_PRIMARY, consumer);
1122 sp<DisplayDevice> hw = new DisplayDevice(this,
1123 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1124 producer, mRenderEngine->getEGLConfig());
1125 mDisplays.add(token, hw);
1126 } else {
1127 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001128 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001129 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001130 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001131 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001132 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1133 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001134 }
1135 setTransactionFlags(eDisplayTransactionNeeded);
1136
Andy McFadden9e9689c2012-10-10 18:17:51 -07001137 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001138 }
Mathias Agopian86303202012-07-24 22:46:10 -07001139}
1140
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001142 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001143 getHwComposer().setVsyncEnabled(disp,
1144 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001145}
1146
Mathias Agopian4fec8732012-06-29 14:12:52 -07001147void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001148 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001150 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001151 bool frameMissed = !mHadClientComposition &&
1152 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001153 (mPreviousPresentFence->getSignalTime() ==
1154 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001155 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001156 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001157 signalLayerUpdate();
1158 break;
1159 }
1160
Dan Stoza6b9454d2014-11-07 16:00:59 -08001161 bool refreshNeeded = handleMessageTransaction();
1162 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001163 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001164 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001165 // Signal a refresh if a transaction modified the window state,
1166 // a new buffer was latched, or if HWC has requested a full
1167 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001168 signalRefresh();
1169 }
1170 break;
1171 }
1172 case MessageQueue::REFRESH: {
1173 handleMessageRefresh();
1174 break;
1175 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176 }
1177}
1178
Dan Stoza6b9454d2014-11-07 16:00:59 -08001179bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001180 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001181 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001182 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001183 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001184 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001185 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001186}
1187
Dan Stoza6b9454d2014-11-07 16:00:59 -08001188bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001189 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001190 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001191}
1192
1193void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001194 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001195
Pablo Ceballos40845df2016-01-25 17:41:15 -08001196 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001197
Brian Andersond6927fb2016-07-23 23:37:30 -07001198 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001199 rebuildLayerStacks();
1200 setUpHWComposer();
1201 doDebugFlashRegions();
1202 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001203 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001204
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001205 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001206
1207 mHadClientComposition = false;
1208 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1209 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1210 mHadClientComposition = mHadClientComposition ||
1211 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1212 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001213
Dan Stoza9e56aa02015-11-02 13:00:03 -08001214 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001215}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001216
Mathias Agopiancd60f992012-08-16 16:28:27 -07001217void SurfaceFlinger::doDebugFlashRegions()
1218{
1219 // is debugging enabled
1220 if (CC_LIKELY(!mDebugRegion))
1221 return;
1222
1223 const bool repaintEverything = mRepaintEverything;
1224 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1225 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001226 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001227 // transform the dirty region into this screen's coordinate space
1228 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1229 if (!dirtyRegion.isEmpty()) {
1230 // redraw the whole screen
1231 doComposeSurfaces(hw, Region(hw->bounds()));
1232
1233 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001234 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001235 RenderEngine& engine(getRenderEngine());
1236 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1237
Mathias Agopianda27af92012-09-13 18:17:13 -07001238 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001239 }
1240 }
1241 }
1242
1243 postFramebuffer();
1244
1245 if (mDebugRegion > 1) {
1246 usleep(mDebugRegion * 1000);
1247 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001248
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001250 auto& displayDevice = mDisplays[displayId];
1251 if (!displayDevice->isDisplayOn()) {
1252 continue;
1253 }
1254
1255 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001256 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1257 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001258 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001259}
1260
Brian Andersond6927fb2016-07-23 23:37:30 -07001261void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001262{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001263 ATRACE_CALL();
1264 ALOGV("preComposition");
1265
Mathias Agopiancd60f992012-08-16 16:28:27 -07001266 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001267 mDrawingState.traverseInZOrder([&](Layer* layer) {
1268 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001269 needExtraInvalidate = true;
1270 }
Robert Carr2047fae2016-11-28 14:09:09 -08001271 });
1272
Mathias Agopiancd60f992012-08-16 16:28:27 -07001273 if (needExtraInvalidate) {
1274 signalLayerUpdate();
1275 }
1276}
1277
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278void SurfaceFlinger::updateCompositorTiming(
1279 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1280 std::shared_ptr<FenceTime>& presentFenceTime) {
1281 // Update queue of past composite+present times and determine the
1282 // most recently known composite to present latency.
1283 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1284 nsecs_t compositeToPresentLatency = -1;
1285 while (!mCompositePresentTimes.empty()) {
1286 CompositePresentTime& cpt = mCompositePresentTimes.front();
1287 // Cached values should have been updated before calling this method,
1288 // which helps avoid duplicate syscalls.
1289 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1290 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1291 break;
1292 }
1293 compositeToPresentLatency = displayTime - cpt.composite;
1294 mCompositePresentTimes.pop();
1295 }
1296
1297 // Don't let mCompositePresentTimes grow unbounded, just in case.
1298 while (mCompositePresentTimes.size() > 16) {
1299 mCompositePresentTimes.pop();
1300 }
1301
1302 // Integer division and modulo round toward 0 not -inf, so we need to
1303 // treat negative and positive offsets differently.
1304 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1305 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1306 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1307
1308 // Snap the latency to a value that removes scheduling jitter from the
1309 // composition and present times, which often have >1ms of jitter.
1310 // Reducing jitter is important if an app attempts to extrapolate
1311 // something (such as user input) to an accurate diasplay time.
1312 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1313 // with (presentLatency % interval).
1314 nsecs_t snappedCompositeToPresentLatency = -1;
1315 if (compositeToPresentLatency >= 0) {
1316 nsecs_t bias = vsyncInterval / 2;
1317 int64_t extraVsyncs =
1318 (compositeToPresentLatency - idealLatency + bias) /
1319 vsyncInterval;
1320 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1321 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1322 }
1323
1324 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1325 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1326 mCompositorTiming.interval = vsyncInterval;
1327 if (snappedCompositeToPresentLatency >= 0) {
1328 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1329 }
1330}
1331
1332void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 ATRACE_CALL();
1335 ALOGV("postComposition");
1336
Brian Anderson3546a3f2016-07-14 11:51:14 -07001337 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001338 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001339 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001340 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001341 }
1342
Brian Andersond6927fb2016-07-23 23:37:30 -07001343 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001344
1345 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1346 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1347 glCompositionDoneFenceTime =
1348 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1349 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1350 } else {
1351 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1352 }
1353 mGlCompositionDoneTimeline.updateSignalTimes();
1354
1355 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1356 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1357 mDisplayTimeline.push(displayFenceTime);
1358 mDisplayTimeline.updateSignalTimes();
1359
1360 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1361 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1362 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1363 presentFenceTime = &displayFenceTime;
1364 } else {
1365 retireFenceTime = &displayFenceTime;
1366 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001367
1368 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1369 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1370
1371 // We use the refreshStartTime which might be sampled a little later than
1372 // when we started doing work for this frame, but that should be okay
1373 // since updateCompositorTiming has snapping logic.
1374 updateCompositorTiming(
1375 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1376
Robert Carr2047fae2016-11-28 14:09:09 -08001377 mDrawingState.traverseInZOrder([&](Layer* layer) {
1378 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001379 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001380 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001381 recordBufferingStats(layer->getName().string(),
1382 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001383 }
Robert Carr2047fae2016-11-28 14:09:09 -08001384 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001385
Brian Anderson3d4039d2016-09-23 16:31:30 -07001386 if (displayFence->isValid()) {
1387 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001388 enableHardwareVsync();
1389 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001390 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001391 }
1392 }
1393
Andy McFadden5167ec62014-05-22 13:08:43 -07001394 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001395 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 enableHardwareVsync();
1397 }
1398 }
1399
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001400 if (mAnimCompositionPending) {
1401 mAnimCompositionPending = false;
1402
Brian Anderson3d4039d2016-09-23 16:31:30 -07001403 if (displayFenceTime->isValid()) {
1404 mAnimFrameTracker.setActualPresentFence(
1405 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001406 } else {
1407 // The HWC doesn't support present fences, so use the refresh
1408 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001409 nsecs_t presentTime =
1410 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001411 mAnimFrameTracker.setActualPresentTime(presentTime);
1412 }
1413 mAnimFrameTracker.advanceFrame();
1414 }
Dan Stozab90cf072015-03-05 11:05:59 -08001415
1416 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1417 return;
1418 }
1419
1420 nsecs_t currentTime = systemTime();
1421 if (mHasPoweredOff) {
1422 mHasPoweredOff = false;
1423 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001424 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001426 if (numPeriods < NUM_BUCKETS - 1) {
1427 mFrameBuckets[numPeriods] += elapsedTime;
1428 } else {
1429 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1430 }
1431 mTotalTime += elapsedTime;
1432 }
1433 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001434}
1435
1436void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001437 ATRACE_CALL();
1438 ALOGV("rebuildLayerStacks");
1439
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001441 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001443 mVisibleRegionsDirty = false;
1444 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001445
Mathias Agopian92a979a2012-08-02 18:32:23 -07001446 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001447 Region opaqueRegion;
1448 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001449 Vector<sp<Layer>> layersSortedByZ;
1450 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1451 const Transform& tr(displayDevice->getTransform());
1452 const Rect bounds(displayDevice->getBounds());
1453 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001454 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 displayDevice->getLayerStack(), dirtyRegion,
1456 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001457
Robert Carr2047fae2016-11-28 14:09:09 -08001458 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001459 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001460 Region drawRegion(tr.transform(
1461 layer->visibleNonTransparentRegion));
1462 drawRegion.andSelf(bounds);
1463 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001464 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 } else {
1466 // Clear out the HWC layer if this layer was
1467 // previously visible, but no longer is
1468 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1469 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001470 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001471 }
Robert Carr2047fae2016-11-28 14:09:09 -08001472 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001474 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1475 displayDevice->undefinedRegion.set(bounds);
1476 displayDevice->undefinedRegion.subtractSelf(
1477 tr.transform(opaqueRegion));
1478 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001479 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001480 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001481}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001482
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 ATRACE_CALL();
1485 ALOGV("setUpHWComposer");
1486
Jesse Hall028dc8f2013-08-20 16:35:32 -07001487 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001488 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1489 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1490 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1491
1492 // If nothing has changed (!dirty), don't recompose.
1493 // If something changed, but we don't currently have any visible layers,
1494 // and didn't when we last did a composition, then skip it this time.
1495 // The second rule does two things:
1496 // - When all layers are removed from a display, we'll emit one black
1497 // frame, then nothing more until we get new layers.
1498 // - When a display is created with a private layer stack, we won't
1499 // emit any black frames until a layer is added to the layer stack.
1500 bool mustRecompose = dirty && !(empty && wasEmpty);
1501
1502 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1503 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1504 mustRecompose ? "doing" : "skipping",
1505 dirty ? "+" : "-",
1506 empty ? "+" : "-",
1507 wasEmpty ? "+" : "-");
1508
Dan Stoza71433162014-02-04 16:22:36 -08001509 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001510
1511 if (mustRecompose) {
1512 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1513 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001514 }
1515
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 // build the h/w work list
1517 if (CC_UNLIKELY(mGeometryInvalid)) {
1518 mGeometryInvalid = false;
1519 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1520 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1521 const auto hwcId = displayDevice->getHwcDisplayId();
1522 if (hwcId >= 0) {
1523 const Vector<sp<Layer>>& currentLayers(
1524 displayDevice->getVisibleLayersSortedByZ());
1525 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001526 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001527 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001528 if (!layer->hasHwcLayer(hwcId)) {
1529 auto hwcLayer = mHwc->createLayer(hwcId);
1530 if (hwcLayer) {
1531 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1532 } else {
1533 layer->forceClientComposition(hwcId);
1534 foundLayerWithoutHwc = true;
1535 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001536 }
1537 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001538
Robert Carrae060832016-11-28 10:51:00 -08001539 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001540 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001542 }
1543 }
1544 }
1545 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 }
Riley Andrews03414a12014-07-01 14:22:59 -07001547
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001548
1549 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1550
Dan Stoza9e56aa02015-11-02 13:00:03 -08001551 // Set the per-frame data
1552 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1553 auto& displayDevice = mDisplays[displayId];
1554 const auto hwcId = displayDevice->getHwcDisplayId();
1555 if (hwcId < 0) {
1556 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001557 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001558 if (colorMatrix != mPreviousColorMatrix) {
1559 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1560 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1561 "display %zd: %d", displayId, result);
1562 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001563 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1564 layer->setPerFrameData(displayDevice);
1565 }
1566 }
1567
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001568 mPreviousColorMatrix = colorMatrix;
1569
Dan Stoza9e56aa02015-11-02 13:00:03 -08001570 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001571 auto& displayDevice = mDisplays[displayId];
1572 if (!displayDevice->isDisplayOn()) {
1573 continue;
1574 }
1575
1576 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1578 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001581
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582void SurfaceFlinger::doComposition() {
1583 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001584 ALOGV("doComposition");
1585
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001586 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001587 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001588 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001589 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 // transform the dirty region into this screen's coordinate space
1591 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001592
1593 // repaint the framebuffer (if needed)
1594 doDisplayComposition(hw, dirtyRegion);
1595
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596 hw->dirtyRegion.clear();
1597 hw->flip(hw->swapRegion);
1598 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001599 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001600 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001601 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001602}
1603
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001604void SurfaceFlinger::postFramebuffer()
1605{
Mathias Agopian841cde52012-03-01 15:44:37 -08001606 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001607 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001608
Mathias Agopiana44b0412011-10-16 18:46:35 -07001609 const nsecs_t now = systemTime();
1610 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001611
Dan Stoza9e56aa02015-11-02 13:00:03 -08001612 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1613 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001614 if (!displayDevice->isDisplayOn()) {
1615 continue;
1616 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001617 const auto hwcId = displayDevice->getHwcDisplayId();
1618 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001619 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001620 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001621 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001622 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001623 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1624 sp<Fence> releaseFence = Fence::NO_FENCE;
1625 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1626 releaseFence = displayDevice->getClientTargetAcquireFence();
1627 } else {
1628 auto hwcLayer = layer->getHwcLayer(hwcId);
1629 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001630 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 layer->onLayerDisplayed(releaseFence);
1632 }
1633 if (hwcId >= 0) {
1634 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001635 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001636 }
1637
Mathias Agopiana44b0412011-10-16 18:46:35 -07001638 mLastSwapBufferTime = systemTime() - now;
1639 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001640
1641 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1642 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1643 logFrameStats();
1644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645}
1646
Mathias Agopian87baae12012-07-31 12:38:26 -07001647void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001648{
Mathias Agopian841cde52012-03-01 15:44:37 -08001649 ATRACE_CALL();
1650
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001651 // here we keep a copy of the drawing state (that is the state that's
1652 // going to be overwritten by handleTransactionLocked()) outside of
1653 // mStateLock so that the side-effects of the State assignment
1654 // don't happen with mStateLock held (which can cause deadlocks).
1655 State drawingState(mDrawingState);
1656
Mathias Agopianca4d3602011-05-19 15:38:14 -07001657 Mutex::Autolock _l(mStateLock);
1658 const nsecs_t now = systemTime();
1659 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001660
Mathias Agopianca4d3602011-05-19 15:38:14 -07001661 // Here we're guaranteed that some transaction flags are set
1662 // so we can call handleTransactionLocked() unconditionally.
1663 // We call getTransactionFlags(), which will also clear the flags,
1664 // with mStateLock held to guarantee that mCurrentState won't change
1665 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001666
Mathias Agopiane57f2922012-08-09 16:29:12 -07001667 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001668 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001669
Mathias Agopianca4d3602011-05-19 15:38:14 -07001670 mLastTransactionTime = systemTime() - now;
1671 mDebugInTransaction = 0;
1672 invalidateHwcGeometry();
1673 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001674}
1675
Mathias Agopian87baae12012-07-31 12:38:26 -07001676void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001677{
Dan Stoza7dde5992015-05-22 09:51:44 -07001678 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001679 mCurrentState.traverseInZOrder([](Layer* layer) {
1680 layer->notifyAvailableFrames();
1681 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001682
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001683 /*
1684 * Traversal of the children
1685 * (perform the transaction for each of them if needed)
1686 */
1687
Mathias Agopian3559b072012-08-15 13:46:03 -07001688 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001689 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001690 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001691 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001692
1693 const uint32_t flags = layer->doTransaction(0);
1694 if (flags & Layer::eVisibleRegion)
1695 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001696 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001697 }
1698
1699 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001700 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001701 */
1702
Mathias Agopiane57f2922012-08-09 16:29:12 -07001703 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001704 // here we take advantage of Vector's copy-on-write semantics to
1705 // improve performance by skipping the transaction entirely when
1706 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001707 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1708 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001709 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001710 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001711 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001712 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001713
1714 // find the displays that were removed
1715 // (ie: in drawing state but not in current state)
1716 // also handle displays that changed
1717 // (ie: displays that are in both lists)
1718 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001719 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1720 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001721 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001722 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001723 // Call makeCurrent() on the primary display so we can
1724 // be sure that nothing associated with this display
1725 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001726 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001727 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001728 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1729 if (hw != NULL)
1730 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001731 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001732 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001733 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001734 } else {
1735 ALOGW("trying to remove the main display");
1736 }
1737 } else {
1738 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001739 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001740 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001741 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1742 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001743 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001744 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001745 // recreating the DisplayDevice, so we just remove it
1746 // from the drawing state, so that it get re-added
1747 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001748 sp<DisplayDevice> hw(getDisplayDevice(display));
1749 if (hw != NULL)
1750 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001751 mDisplays.removeItem(display);
1752 mDrawingState.displays.removeItemsAt(i);
1753 dc--; i--;
1754 // at this point we must loop to the next item
1755 continue;
1756 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001757
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001758 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001759 if (disp != NULL) {
1760 if (state.layerStack != draw[i].layerStack) {
1761 disp->setLayerStack(state.layerStack);
1762 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001763 if ((state.orientation != draw[i].orientation)
1764 || (state.viewport != draw[i].viewport)
1765 || (state.frame != draw[i].frame))
1766 {
1767 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001768 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001769 }
Michael Lentine47e45402014-07-18 15:34:25 -07001770 if (state.width != draw[i].width || state.height != draw[i].height) {
1771 disp->setDisplaySize(state.width, state.height);
1772 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001773 }
1774 }
1775 }
1776
1777 // find displays that were added
1778 // (ie: in current state but not in drawing state)
1779 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001780 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001781 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001782
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001783 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001784 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001785 sp<IGraphicBufferProducer> bqProducer;
1786 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001787 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1788 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001789
Dan Stoza9e56aa02015-11-02 13:00:03 -08001790 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001791 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001792 // Virtual displays without a surface are dormant:
1793 // they have external state (layer stack, projection,
1794 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001795 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001796
Dan Stoza8cf150a2016-08-02 10:27:31 -07001797 if (mUseHwcVirtualDisplays) {
1798 int width = 0;
1799 int status = state.surface->query(
1800 NATIVE_WINDOW_WIDTH, &width);
1801 ALOGE_IF(status != NO_ERROR,
1802 "Unable to query width (%d)", status);
1803 int height = 0;
1804 status = state.surface->query(
1805 NATIVE_WINDOW_HEIGHT, &height);
1806 ALOGE_IF(status != NO_ERROR,
1807 "Unable to query height (%d)", status);
1808 int intFormat = 0;
1809 status = state.surface->query(
1810 NATIVE_WINDOW_FORMAT, &intFormat);
1811 ALOGE_IF(status != NO_ERROR,
1812 "Unable to query format (%d)", status);
1813 auto format = static_cast<android_pixel_format_t>(
1814 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001815
Dan Stoza8cf150a2016-08-02 10:27:31 -07001816 mHwc->allocateVirtualDisplay(width, height, &format,
1817 &hwcId);
1818 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819
Dan Stoza5cf424b2016-05-20 14:02:39 -07001820 // TODO: Plumb requested format back up to consumer
1821
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 sp<VirtualDisplaySurface> vds =
1823 new VirtualDisplaySurface(*mHwc,
1824 hwcId, state.surface, bqProducer,
1825 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001826
1827 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001828 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001829 }
1830 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001831 ALOGE_IF(state.surface!=NULL,
1832 "adding a supported display, but rendering "
1833 "surface is provided (%p), ignoring it",
1834 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001835 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1836 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1837 dispSurface = new FramebufferSurface(*mHwc,
1838 DisplayDevice::DISPLAY_EXTERNAL,
1839 bqConsumer);
1840 producer = bqProducer;
1841 } else {
1842 ALOGE("Attempted to add non-external non-virtual"
1843 " display");
1844 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001845 }
1846
1847 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001848 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001849 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001850 state.type, hwcId, state.isSecure, display,
1851 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001852 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001853 hw->setLayerStack(state.layerStack);
1854 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001855 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001856 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001857 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001859 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001860 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001861 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001862 }
1863 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001864 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001865 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866
Mathias Agopian84300952012-11-21 16:02:13 -08001867 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1868 // The transform hint might have changed for some layers
1869 // (either because a display has changed, or because a layer
1870 // as changed).
1871 //
1872 // Walk through all the layers in currentLayers,
1873 // and update their transform hint.
1874 //
1875 // If a layer is visible only on a single display, then that
1876 // display is used to calculate the hint, otherwise we use the
1877 // default display.
1878 //
1879 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1880 // the hint is set before we acquire a buffer from the surface texture.
1881 //
1882 // NOTE: layer transactions have taken place already, so we use their
1883 // drawing state. However, SurfaceFlinger's own transaction has not
1884 // happened yet, so we must use the current state layer list
1885 // (soon to become the drawing state list).
1886 //
1887 sp<const DisplayDevice> disp;
1888 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001889 bool first = true;
1890 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001891 // NOTE: we rely on the fact that layers are sorted by
1892 // layerStack first (so we don't have to traverse the list
1893 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001894 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001895 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001896 currentlayerStack = layerStack;
1897 // figure out if this layerstack is mirrored
1898 // (more than one display) if so, pick the default display,
1899 // if not, pick the only display it's on.
1900 disp.clear();
1901 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1902 sp<const DisplayDevice> hw(mDisplays[dpy]);
1903 if (hw->getLayerStack() == currentlayerStack) {
1904 if (disp == NULL) {
1905 disp = hw;
1906 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001907 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001908 break;
1909 }
1910 }
1911 }
1912 }
Chet Haase91d25932013-04-11 15:24:55 -07001913 if (disp == NULL) {
1914 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1915 // redraw after transform hint changes. See bug 8508397.
1916
1917 // could be null when this layer is using a layerStack
1918 // that is not visible on any display. Also can occur at
1919 // screen off/on times.
1920 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001921 }
Chet Haase91d25932013-04-11 15:24:55 -07001922 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001923
1924 first = false;
1925 });
Mathias Agopian84300952012-11-21 16:02:13 -08001926 }
1927
1928
Mathias Agopian3559b072012-08-15 13:46:03 -07001929 /*
1930 * Perform our own transaction if needed
1931 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001932
1933 if (mLayersAdded) {
1934 mLayersAdded = false;
1935 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001936 mVisibleRegionsDirty = true;
1937 }
1938
1939 // some layers might have been removed, so
1940 // we need to update the regions they're exposing.
1941 if (mLayersRemoved) {
1942 mLayersRemoved = false;
1943 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001944 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001945 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001946 // this layer is not visible anymore
1947 // TODO: we could traverse the tree from front to back and
1948 // compute the actual visible region
1949 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001950 Region visibleReg;
1951 visibleReg.set(layer->computeScreenBounds());
1952 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001953 }
Robert Carr2047fae2016-11-28 14:09:09 -08001954 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001955 }
1956
1957 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001958
1959 updateCursorAsync();
1960}
1961
1962void SurfaceFlinger::updateCursorAsync()
1963{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1965 auto& displayDevice = mDisplays[displayId];
1966 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001967 continue;
1968 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969
1970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1971 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001972 }
1973 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001974}
1975
1976void SurfaceFlinger::commitTransaction()
1977{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001978 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001979 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001980 for (const auto& l : mLayersPendingRemoval) {
1981 recordBufferingStats(l->getName().string(),
1982 l->getOccupancyHistory(true));
1983 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001984 }
1985 mLayersPendingRemoval.clear();
1986 }
1987
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001988 // If this transaction is part of a window animation then the next frame
1989 // we composite should be considered an animation as well.
1990 mAnimCompositionPending = mAnimTransactionPending;
1991
Mathias Agopian4fec8732012-06-29 14:12:52 -07001992 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001993 mDrawingState.traverseInZOrder([](Layer* layer) {
1994 layer->commitChildList();
1995 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001996 mTransactionPending = false;
1997 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001998 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999}
2000
Robert Carr2047fae2016-11-28 14:09:09 -08002001void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002002 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003{
Mathias Agopian841cde52012-03-01 15:44:37 -08002004 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007 Region aboveOpaqueLayers;
2008 Region aboveCoveredLayers;
2009 Region dirty;
2010
Mathias Agopian87baae12012-07-31 12:38:26 -07002011 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012
Robert Carr2047fae2016-11-28 14:09:09 -08002013 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002014 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002015 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016
Jesse Hall01e29052013-02-19 16:13:35 -08002017 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002018 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002019 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002020
Mathias Agopianab028732010-03-16 16:41:46 -07002021 /*
2022 * opaqueRegion: area of a surface that is fully opaque.
2023 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002024 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002025
2026 /*
2027 * visibleRegion: area of a surface that is visible on screen
2028 * and not fully transparent. This is essentially the layer's
2029 * footprint minus the opaque regions above it.
2030 * Areas covered by a translucent surface are considered visible.
2031 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002032 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002033
2034 /*
2035 * coveredRegion: area of a surface that is covered by all
2036 * visible regions above it (which includes the translucent areas).
2037 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002039
Jesse Halla8026d22012-09-25 13:25:04 -07002040 /*
2041 * transparentRegion: area of a surface that is hinted to be completely
2042 * transparent. This is only used to tell when the layer has no visible
2043 * non-transparent regions and can be removed from the layer list. It
2044 * does not affect the visibleRegion of this layer or any layers
2045 * beneath it. The hint may not be correct if apps don't respect the
2046 * SurfaceView restrictions (which, sadly, some don't).
2047 */
2048 Region transparentRegion;
2049
Mathias Agopianab028732010-03-16 16:41:46 -07002050
2051 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002052 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002053 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002054 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002056 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002057 if (!visibleRegion.isEmpty()) {
2058 // Remove the transparent area from the visible region
2059 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002060 if (tr.preserveRects()) {
2061 // transform the transparent region
2062 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002063 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002064 // transformation too complex, can't do the
2065 // transparent region optimization.
2066 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002067 }
Mathias Agopianab028732010-03-16 16:41:46 -07002068 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069
Mathias Agopianab028732010-03-16 16:41:46 -07002070 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002071 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002073 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2074 // the opaque region is the layer's footprint
2075 opaqueRegion = visibleRegion;
2076 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002077 }
2078 }
2079
Mathias Agopianab028732010-03-16 16:41:46 -07002080 // Clip the covered region to the visible region
2081 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2082
2083 // Update aboveCoveredLayers for next (lower) layer
2084 aboveCoveredLayers.orSelf(visibleRegion);
2085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086 // subtract the opaque region covered by the layers above us
2087 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088
2089 // compute this layer's dirty region
2090 if (layer->contentDirty) {
2091 // we need to invalidate the whole region
2092 dirty = visibleRegion;
2093 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 layer->contentDirty = false;
2096 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002097 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002098 * the exposed region consists of two components:
2099 * 1) what's VISIBLE now and was COVERED before
2100 * 2) what's EXPOSED now less what was EXPOSED before
2101 *
2102 * note that (1) is conservative, we start with the whole
2103 * visible region but only keep what used to be covered by
2104 * something -- which mean it may have been exposed.
2105 *
2106 * (2) handles areas that were not covered by anything but got
2107 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002108 */
Mathias Agopianab028732010-03-16 16:41:46 -07002109 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002110 const Region oldVisibleRegion = layer->visibleRegion;
2111 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002112 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2113 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114 }
2115 dirty.subtractSelf(aboveOpaqueLayers);
2116
2117 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002118 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119
Mathias Agopianab028732010-03-16 16:41:46 -07002120 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002122
Jesse Halla8026d22012-09-25 13:25:04 -07002123 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124 layer->setVisibleRegion(visibleRegion);
2125 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002126 layer->setVisibleNonTransparentRegion(
2127 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002128 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129
Mathias Agopian87baae12012-07-31 12:38:26 -07002130 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131}
2132
Mathias Agopian87baae12012-07-31 12:38:26 -07002133void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2134 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002135 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002136 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2137 if (hw->getLayerStack() == layerStack) {
2138 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002139 }
2140 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002141}
2142
Dan Stoza6b9454d2014-11-07 16:00:59 -08002143bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 ALOGV("handlePageFlip");
2146
Brian Andersond6927fb2016-07-23 23:37:30 -07002147 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148
Mathias Agopian4fec8732012-06-29 14:12:52 -07002149 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002150 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002151
2152 // Store the set of layers that need updates. This set must not change as
2153 // buffers are being latched, as this could result in a deadlock.
2154 // Example: Two producers share the same command stream and:
2155 // 1.) Layer 0 is latched
2156 // 2.) Layer 0 gets a new frame
2157 // 2.) Layer 1 gets a new frame
2158 // 3.) Layer 1 is latched.
2159 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2160 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002161 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002162 if (layer->hasQueuedFrame()) {
2163 frameQueued = true;
2164 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002165 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002166 } else {
2167 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002168 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002169 } else {
2170 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002171 }
Robert Carr2047fae2016-11-28 14:09:09 -08002172 });
2173
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002175 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002176 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002178 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002179
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002180 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002181
2182 // If we will need to wake up at some time in the future to deal with a
2183 // queued frame that shouldn't be displayed during this vsync period, wake
2184 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002186 signalLayerUpdate();
2187 }
2188
2189 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191}
2192
Mathias Agopianad456f92011-01-13 17:53:01 -08002193void SurfaceFlinger::invalidateHwcGeometry()
2194{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002196}
2197
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002198
Fabien Sanglard830b8472016-11-30 16:35:58 -08002199void SurfaceFlinger::doDisplayComposition(
2200 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002201 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202{
Dan Stoza71433162014-02-04 16:22:36 -08002203 // We only need to actually compose the display if:
2204 // 1) It is being handled by hardware composer, which may need this to
2205 // keep its virtual display state machine in sync, or
2206 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002207 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002208 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002210 return;
2211 }
2212
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 ALOGV("doDisplayComposition");
2214
Mathias Agopian87baae12012-07-31 12:38:26 -07002215 Region dirtyRegion(inDirtyRegion);
2216
Mathias Agopianb8a55602009-06-26 19:06:36 -07002217 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002218 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219
Fabien Sanglard830b8472016-11-30 16:35:58 -08002220 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002221 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002222 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2223 // takes a rectangle, we must make sure to update that whole
2224 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002225 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002226 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002227 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002228 // We need to redraw the rectangle that will be updated
2229 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002230 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002231 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002232 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002233 } else {
2234 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002235 dirtyRegion.set(displayDevice->bounds());
2236 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 }
2238 }
2239
Fabien Sanglard830b8472016-11-30 16:35:58 -08002240 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002242 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002243 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002244
2245 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002246 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247}
2248
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249bool SurfaceFlinger::doComposeSurfaces(
2250 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002251{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002253
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002255
2256 mat4 oldColorMatrix;
2257 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2258 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2259 if (applyColorMatrix) {
2260 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2261 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2262 }
2263
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2265 if (hasClientComposition) {
2266 ALOGV("hasClientComposition");
2267
2268 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002269 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002271 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2272 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2273 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2274 }
2275 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002276 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002277
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002278 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2280 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002281 // when using overlays, we assume a fully transparent framebuffer
2282 // NOTE: we could reduce how much we need to clear, for instance
2283 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002284 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002285 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002286 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002287 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002288 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002290
2291 // we remove the scissor part
2292 // we're left with the letterbox region
2293 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002295
2296 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002297 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002298
2299 // but limit it to the dirty region
2300 region.andSelf(dirty);
2301
Mathias Agopianb9494d52012-04-18 02:28:45 -07002302 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002303 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002304 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002306 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002307 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002308
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002310 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002311 // scissor on the main display. It should never be needed
2312 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002313 const Rect& bounds(displayDevice->getBounds());
2314 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002315 if (scissor != bounds) {
2316 // scissor doesn't match the screen's dimensions, so we
2317 // need to clear everything outside of it and enable
2318 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002319
Mathias Agopianf45c5102012-10-24 16:29:17 -07002320 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002321 const uint32_t height = displayDevice->getHeight();
2322 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002323 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002324 }
2325 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002326 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002327
Mathias Agopian85d751c2012-08-29 16:59:24 -07002328 /*
2329 * and then, render the layers targeted at the framebuffer
2330 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002331
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 ALOGV("Rendering client layers");
2333 const Transform& displayTransform = displayDevice->getTransform();
2334 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002335 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002336 bool firstLayer = true;
2337 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2338 const Region clip(dirty.intersect(
2339 displayTransform.transform(layer->visibleRegion)));
2340 ALOGV("Layer: %s", layer->getName().string());
2341 ALOGV(" Composition type: %s",
2342 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002343 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 switch (layer->getCompositionType(hwcId)) {
2345 case HWC2::Composition::Cursor:
2346 case HWC2::Composition::Device:
2347 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002348 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002349 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2350 layer->isOpaque(state) && (state.alpha == 1.0f)
2351 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002352 // never clear the very first layer since we're
2353 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002354 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002355 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002356 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002357 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358 case HWC2::Composition::Client: {
2359 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002360 break;
2361 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002362 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002363 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002364 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002365 } else {
2366 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002367 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002369 }
2370 } else {
2371 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002372 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002373 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002375 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002377 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002378 }
2379 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002380
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002381 if (applyColorMatrix) {
2382 getRenderEngine().setupColorTransform(oldColorMatrix);
2383 }
2384
Mathias Agopianf45c5102012-10-24 16:29:17 -07002385 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002386 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002387 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388}
2389
Fabien Sanglard830b8472016-11-30 16:35:58 -08002390void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2391 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002392 RenderEngine& engine(getRenderEngine());
2393 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394}
2395
Dan Stoza7d89d062015-04-30 13:29:25 -07002396status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002397 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002398 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002399 const sp<Layer>& lbc,
2400 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002401{
Dan Stoza7d89d062015-04-30 13:29:25 -07002402 // add this layer to the current state list
2403 {
2404 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002405 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002406 return NO_MEMORY;
2407 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002408 if (parent == nullptr) {
2409 mCurrentState.layersSortedByZ.add(lbc);
2410 } else {
2411 parent->addChild(lbc);
2412 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002413 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002414 mLayersAdded = true;
2415 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002416 }
2417
Mathias Agopian96f08192010-06-02 23:28:45 -07002418 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002419 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002420
Dan Stoza7d89d062015-04-30 13:29:25 -07002421 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002422}
2423
Dan Stoza22851c32016-08-09 13:21:03 -07002424status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002426 sp<Layer> layer = weakLayer.promote();
2427 if (layer == nullptr) {
2428 // The layer has already been removed, carry on
2429 return NO_ERROR;
2430 }
2431
Robert Carr1f0a16a2016-10-24 16:27:39 -07002432 const auto& p = layer->getParent();
2433 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2434 mCurrentState.layersSortedByZ.remove(layer);
2435
2436 if (index < 0) {
2437 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2438 layer->getName().string(),
2439 (p != nullptr) ? p->getName().string() : "no-parent");
2440 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002441 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442
2443 mLayersPendingRemoval.add(layer);
2444 mLayersRemoved = true;
2445 mNumLayers--;
2446 setTransactionFlags(eTransactionNeeded);
2447 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448}
2449
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002450uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002451 return android_atomic_release_load(&mTransactionFlags);
2452}
2453
Mathias Agopian3f844832013-08-07 21:24:32 -07002454uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2456}
2457
Mathias Agopian3f844832013-08-07 21:24:32 -07002458uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2460 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002461 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 }
2463 return old;
2464}
2465
Mathias Agopian8b33f032012-07-24 20:43:54 -07002466void SurfaceFlinger::setTransactionState(
2467 const Vector<ComposerState>& state,
2468 const Vector<DisplayState>& displays,
2469 uint32_t flags)
2470{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002471 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002472 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002473 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002474
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002475 if (flags & eAnimation) {
2476 // For window updates that are part of an animation we must wait for
2477 // previous animation "frames" to be handled.
2478 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002479 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002480 if (CC_UNLIKELY(err != NO_ERROR)) {
2481 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002482 // caller after a few seconds.
2483 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2484 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002485 mAnimTransactionPending = false;
2486 break;
2487 }
2488 }
2489 }
2490
Mathias Agopiane57f2922012-08-09 16:29:12 -07002491 size_t count = displays.size();
2492 for (size_t i=0 ; i<count ; i++) {
2493 const DisplayState& s(displays[i]);
2494 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002495 }
2496
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002498 for (size_t i=0 ; i<count ; i++) {
2499 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002500 // Here we need to check that the interface we're given is indeed
2501 // one of our own. A malicious client could give us a NULL
2502 // IInterface, or one of its own or even one of our own but a
2503 // different type. All these situations would cause us to crash.
2504 //
2505 // NOTE: it would be better to use RTTI as we could directly check
2506 // that we have a Client*. however, RTTI is disabled in Android.
2507 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002508 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002509 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002510 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002511 sp<Client> client( static_cast<Client *>(s.client.get()) );
2512 transactionFlags |= setClientStateLocked(client, s.state);
2513 }
2514 }
2515 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002516 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002517
Robert Carr2a7dbb42016-05-24 11:41:28 -07002518 // If a synchronous transaction is explicitly requested without any changes,
2519 // force a transaction anyway. This can be used as a flush mechanism for
2520 // previous async transactions.
2521 if (transactionFlags == 0 && (flags & eSynchronous)) {
2522 transactionFlags = eTransactionNeeded;
2523 }
2524
Mathias Agopian386aa982011-11-07 21:58:03 -08002525 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002526 if (mInterceptor.isEnabled()) {
2527 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2528 }
Irvel468051e2016-06-13 16:44:44 -07002529
Mathias Agopian386aa982011-11-07 21:58:03 -08002530 // this triggers the transaction
2531 setTransactionFlags(transactionFlags);
2532
2533 // if this is a synchronous transaction, wait for it to take effect
2534 // before returning.
2535 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002536 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002537 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002538 if (flags & eAnimation) {
2539 mAnimTransactionPending = true;
2540 }
2541 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002542 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2543 if (CC_UNLIKELY(err != NO_ERROR)) {
2544 // just in case something goes wrong in SF, return to the
2545 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002546 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2547 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002548 break;
2549 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 }
2552}
2553
Mathias Agopiane57f2922012-08-09 16:29:12 -07002554uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2555{
Jesse Hall9a143922012-10-04 16:29:19 -07002556 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2557 if (dpyIdx < 0)
2558 return 0;
2559
Mathias Agopiane57f2922012-08-09 16:29:12 -07002560 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002561 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002562 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002563 const uint32_t what = s.what;
2564 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002565 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 disp.surface = s.surface;
2567 flags |= eDisplayTransactionNeeded;
2568 }
2569 }
2570 if (what & DisplayState::eLayerStackChanged) {
2571 if (disp.layerStack != s.layerStack) {
2572 disp.layerStack = s.layerStack;
2573 flags |= eDisplayTransactionNeeded;
2574 }
2575 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002576 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002577 if (disp.orientation != s.orientation) {
2578 disp.orientation = s.orientation;
2579 flags |= eDisplayTransactionNeeded;
2580 }
2581 if (disp.frame != s.frame) {
2582 disp.frame = s.frame;
2583 flags |= eDisplayTransactionNeeded;
2584 }
2585 if (disp.viewport != s.viewport) {
2586 disp.viewport = s.viewport;
2587 flags |= eDisplayTransactionNeeded;
2588 }
2589 }
Michael Lentine47e45402014-07-18 15:34:25 -07002590 if (what & DisplayState::eDisplaySizeChanged) {
2591 if (disp.width != s.width) {
2592 disp.width = s.width;
2593 flags |= eDisplayTransactionNeeded;
2594 }
2595 if (disp.height != s.height) {
2596 disp.height = s.height;
2597 flags |= eDisplayTransactionNeeded;
2598 }
2599 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002600 }
2601 return flags;
2602}
2603
2604uint32_t SurfaceFlinger::setClientStateLocked(
2605 const sp<Client>& client,
2606 const layer_state_t& s)
2607{
2608 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002609 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002610 if (layer != 0) {
2611 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002612 bool geometryAppliesWithResize =
2613 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002614 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002615 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002616 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002617 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002618 }
2619 if (what & layer_state_t::eLayerChanged) {
2620 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621 const auto& p = layer->getParent();
2622 if (p == nullptr) {
2623 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2624 if (layer->setLayer(s.z) && idx >= 0) {
2625 mCurrentState.layersSortedByZ.removeAt(idx);
2626 mCurrentState.layersSortedByZ.add(layer);
2627 // we need traversal (state changed)
2628 // AND transaction (list changed)
2629 flags |= eTransactionNeeded|eTraversalNeeded;
2630 }
2631 } else {
2632 if (p->setChildLayer(layer, s.z)) {
2633 flags |= eTransactionNeeded|eTraversalNeeded;
2634 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002635 }
2636 }
2637 if (what & layer_state_t::eSizeChanged) {
2638 if (layer->setSize(s.w, s.h)) {
2639 flags |= eTraversalNeeded;
2640 }
2641 }
2642 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002644 flags |= eTraversalNeeded;
2645 }
2646 if (what & layer_state_t::eMatrixChanged) {
2647 if (layer->setMatrix(s.matrix))
2648 flags |= eTraversalNeeded;
2649 }
2650 if (what & layer_state_t::eTransparentRegionChanged) {
2651 if (layer->setTransparentRegionHint(s.transparentRegion))
2652 flags |= eTraversalNeeded;
2653 }
Dan Stoza23116082015-06-18 14:58:39 -07002654 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002655 if (layer->setFlags(s.flags, s.mask))
2656 flags |= eTraversalNeeded;
2657 }
2658 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002659 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002660 flags |= eTraversalNeeded;
2661 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002662 if (what & layer_state_t::eFinalCropChanged) {
2663 if (layer->setFinalCrop(s.finalCrop))
2664 flags |= eTraversalNeeded;
2665 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002666 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002667 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002668 // We only allow setting layer stacks for top level layers,
2669 // everything else inherits layer stack from its parent.
2670 if (layer->hasParent()) {
2671 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2672 layer->getName().string());
2673 } else if (idx < 0) {
2674 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2675 "that also does not appear in the top level layer list. Something"
2676 " has gone wrong.", layer->getName().string());
2677 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002678 mCurrentState.layersSortedByZ.removeAt(idx);
2679 mCurrentState.layersSortedByZ.add(layer);
2680 // we need traversal (state changed)
2681 // AND transaction (list changed)
2682 flags |= eTransactionNeeded|eTraversalNeeded;
2683 }
2684 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002685 if (what & layer_state_t::eDeferTransaction) {
2686 layer->deferTransactionUntil(s.handle, s.frameNumber);
2687 // We don't trigger a traversal here because if no other state is
2688 // changed, we don't want this to cause any more work
2689 }
Robert Carr1db73f62016-12-21 12:58:51 -08002690 if (what & layer_state_t::eReparentChildren) {
2691 if (layer->reparentChildren(s.reparentHandle)) {
2692 flags |= eTransactionNeeded|eTraversalNeeded;
2693 }
2694 }
Robert Carrc3574f72016-03-24 12:19:32 -07002695 if (what & layer_state_t::eOverrideScalingModeChanged) {
2696 layer->setOverrideScalingMode(s.overrideScalingMode);
2697 // We don't trigger a traversal here because if no other state is
2698 // changed, we don't want this to cause any more work
2699 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002700 }
2701 return flags;
2702}
2703
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002704status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002705 const String8& name,
2706 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002707 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002708 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2709 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002711 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002712 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002713 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002714 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002715 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002716
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002717 status_t result = NO_ERROR;
2718
2719 sp<Layer> layer;
2720
Mathias Agopian3165cc22012-08-08 19:42:09 -07002721 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2722 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002723 result = createNormalLayer(client,
2724 name, w, h, flags, format,
2725 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002727 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002728 result = createDimLayer(client,
2729 name, w, h, flags,
2730 handle, gbp, &layer);
2731 break;
2732 default:
2733 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 break;
2735 }
2736
Dan Stoza7d89d062015-04-30 13:29:25 -07002737 if (result != NO_ERROR) {
2738 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002740
Albert Chaulk479c60c2017-01-27 14:21:34 -05002741 layer->setInfo(windowType, ownerUid);
2742
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002744 if (result != NO_ERROR) {
2745 return result;
2746 }
Irvelffc9efc2016-07-27 15:16:37 -07002747 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002748
2749 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002750 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751}
2752
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002753status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2754 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2755 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756{
2757 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002758 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 case PIXEL_FORMAT_TRANSPARENT:
2760 case PIXEL_FORMAT_TRANSLUCENT:
2761 format = PIXEL_FORMAT_RGBA_8888;
2762 break;
2763 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002764 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 break;
2766 }
2767
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002768 *outLayer = new Layer(this, client, name, w, h, flags);
2769 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2770 if (err == NO_ERROR) {
2771 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002772 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002774
2775 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2776 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777}
2778
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002779status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2780 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2781 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002783 *outLayer = new LayerDim(this, client, name, w, h, flags);
2784 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002785 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002786 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002787}
2788
Mathias Agopianac9fa422013-02-11 16:40:36 -08002789status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790{
Mathias Agopian67106042013-03-14 19:18:13 -07002791 // called by the window manager when it wants to remove a Layer
2792 status_t err = NO_ERROR;
2793 sp<Layer> l(client->getLayerUser(handle));
2794 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002795 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002796 err = removeLayer(l);
2797 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2798 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002799 }
2800 return err;
2801}
2802
Mathias Agopian13127d82013-03-05 17:47:11 -08002803status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002804{
Mathias Agopian67106042013-03-14 19:18:13 -07002805 // called by ~LayerCleaner() when all references to the IBinder (handle)
2806 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002807 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808}
2809
Mathias Agopianb60314a2012-04-10 22:09:54 -07002810// ---------------------------------------------------------------------------
2811
Andy McFadden13a082e2012-08-24 10:16:42 -07002812void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002813 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002814 Vector<ComposerState> state;
2815 Vector<DisplayState> displays;
2816 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002817 d.what = DisplayState::eDisplayProjectionChanged |
2818 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002819 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002820 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002821 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002822 d.frame.makeInvalid();
2823 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002824 d.width = 0;
2825 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002826 displays.add(d);
2827 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002828 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002829
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2831 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002832 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002833
2834 {
2835 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2836 mCompositorTiming.interval = period;
2837 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002838}
2839
2840void SurfaceFlinger::initializeDisplays() {
2841 class MessageScreenInitialized : public MessageBase {
2842 SurfaceFlinger* flinger;
2843 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002844 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002845 virtual bool handler() {
2846 flinger->onInitializeDisplays();
2847 return true;
2848 }
2849 };
2850 sp<MessageBase> msg = new MessageScreenInitialized(this);
2851 postMessageAsync(msg); // we may be called from main thread, use async message
2852}
2853
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002854void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2855 int mode) {
2856 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2857 this);
2858 int32_t type = hw->getDisplayType();
2859 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002860
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002861 if (mode == currentMode) {
2862 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002863 return;
2864 }
2865
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002866 hw->setPowerMode(mode);
2867 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2868 ALOGW("Trying to set power mode for virtual display");
2869 return;
2870 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002871
Irvelffc9efc2016-07-27 15:16:37 -07002872 if (mInterceptor.isEnabled()) {
2873 Mutex::Autolock _l(mStateLock);
2874 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2875 if (idx < 0) {
2876 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2877 return;
2878 }
2879 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2880 }
2881
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002882 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002883 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002884 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002885 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2886 // FIXME: eventthread only knows about the main display right now
2887 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002888 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002889 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002891 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002892 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002893 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002894
2895 struct sched_param param = {0};
2896 param.sched_priority = 1;
2897 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2898 ALOGW("Couldn't set SCHED_FIFO on display on");
2899 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002900 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002901 // Turn off the display
2902 struct sched_param param = {0};
2903 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2904 ALOGW("Couldn't set SCHED_OTHER on display off");
2905 }
2906
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002907 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002908 disableHardwareVsync(true); // also cancels any in-progress resync
2909
Mathias Agopiancde87a32012-09-13 14:09:01 -07002910 // FIXME: eventthread only knows about the main display right now
2911 mEventThread->onScreenReleased();
2912 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002913
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002914 getHwComposer().setPowerMode(type, mode);
2915 mVisibleRegionsDirty = true;
2916 // from this point on, SF will stop drawing on this display
2917 } else {
2918 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002919 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002920}
2921
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002922void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2923 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002924 SurfaceFlinger& mFlinger;
2925 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002926 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002927 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002928 MessageSetPowerMode(SurfaceFlinger& flinger,
2929 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2930 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002931 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002933 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002934 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002935 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002937 ALOGW("Attempt to set power mode = %d for virtual display",
2938 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002939 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002940 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002941 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002942 return true;
2943 }
2944 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002945 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002946 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002947}
2948
2949// ---------------------------------------------------------------------------
2950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2952{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002954
Mathias Agopianbd115332013-04-18 16:41:04 -07002955 IPCThreadState* ipc = IPCThreadState::self();
2956 const int pid = ipc->getCallingPid();
2957 const int uid = ipc->getCallingUid();
2958 if ((uid != AID_SHELL) &&
2959 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002960 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002961 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002963 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002964 // (this would indicate SF is stuck, but we want to be able to
2965 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002966 status_t err = mStateLock.timedLock(s2ns(1));
2967 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002968 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002969 result.appendFormat(
2970 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2971 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002972 }
2973
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002974 bool dumpAll = true;
2975 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002976 size_t numArgs = args.size();
2977 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002978 if ((index < numArgs) &&
2979 (args[index] == String16("--list"))) {
2980 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002981 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002982 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002983 }
2984
2985 if ((index < numArgs) &&
2986 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002987 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002988 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002989 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002990 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002991
2992 if ((index < numArgs) &&
2993 (args[index] == String16("--latency-clear"))) {
2994 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002995 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002996 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002997 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002998
2999 if ((index < numArgs) &&
3000 (args[index] == String16("--dispsync"))) {
3001 index++;
3002 mPrimaryDispSync.dump(result);
3003 dumpAll = false;
3004 }
Dan Stozab90cf072015-03-05 11:05:59 -08003005
3006 if ((index < numArgs) &&
3007 (args[index] == String16("--static-screen"))) {
3008 index++;
3009 dumpStaticScreenStats(result);
3010 dumpAll = false;
3011 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003012
3013 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003014 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003015 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003016 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003017 dumpAll = false;
3018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003020
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003021 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003022 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003023 }
3024
Mathias Agopian9795c422009-08-26 16:36:26 -07003025 if (locked) {
3026 mStateLock.unlock();
3027 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028 }
3029 write(fd, result.string(), result.size());
3030 return NO_ERROR;
3031}
3032
Dan Stozac7014012014-02-14 15:03:43 -08003033void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3034 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003035{
Robert Carr2047fae2016-11-28 14:09:09 -08003036 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003037 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003038 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003039}
3040
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003041void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003042 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003043{
3044 String8 name;
3045 if (index < args.size()) {
3046 name = String8(args[index]);
3047 index++;
3048 }
3049
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3051 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003052 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003053
3054 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003055 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003056 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003057 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003058 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003059 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003060 }
Robert Carr2047fae2016-11-28 14:09:09 -08003061 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003062 }
3063}
3064
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003065void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003066 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003067{
3068 String8 name;
3069 if (index < args.size()) {
3070 name = String8(args[index]);
3071 index++;
3072 }
3073
Robert Carr2047fae2016-11-28 14:09:09 -08003074 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003075 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003076 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003077 }
Robert Carr2047fae2016-11-28 14:09:09 -08003078 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003079
Svetoslavd85084b2014-03-20 10:28:31 -07003080 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003081}
3082
Jamie Gennis6547ff42013-07-16 20:12:42 -07003083// This should only be called from the main thread. Otherwise it would need
3084// the lock and should use mCurrentState rather than mDrawingState.
3085void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003086 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003087 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003088 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003089
3090 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3091}
3092
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003093void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003094{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003095 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003096#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003097 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003098#endif
3099#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003100 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003101#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003102 if (isLayerTripleBufferingDisabled())
3103 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003104 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003105}
3106
Dan Stozab90cf072015-03-05 11:05:59 -08003107void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3108{
3109 result.appendFormat("Static screen stats:\n");
3110 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3111 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3112 float percent = 100.0f *
3113 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3114 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3115 b + 1, bucketTimeSec, percent);
3116 }
3117 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3118 float percent = 100.0f *
3119 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3120 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3121 NUM_BUCKETS - 1, bucketTimeSec, percent);
3122}
3123
Dan Stozae77c7662016-05-13 11:37:28 -07003124void SurfaceFlinger::recordBufferingStats(const char* layerName,
3125 std::vector<OccupancyTracker::Segment>&& history) {
3126 Mutex::Autolock lock(mBufferingStatsMutex);
3127 auto& stats = mBufferingStats[layerName];
3128 for (const auto& segment : history) {
3129 if (!segment.usedThirdBuffer) {
3130 stats.twoBufferTime += segment.totalTime;
3131 }
3132 if (segment.occupancyAverage < 1.0f) {
3133 stats.doubleBufferedTime += segment.totalTime;
3134 } else if (segment.occupancyAverage < 2.0f) {
3135 stats.tripleBufferedTime += segment.totalTime;
3136 }
3137 ++stats.numSegments;
3138 stats.totalTime += segment.totalTime;
3139 }
3140}
3141
Brian Andersond6927fb2016-07-23 23:37:30 -07003142void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3143 result.appendFormat("Layer frame timestamps:\n");
3144
3145 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3146 const size_t count = currentLayers.size();
3147 for (size_t i=0 ; i<count ; i++) {
3148 currentLayers[i]->dumpFrameEvents(result);
3149 }
3150}
3151
Dan Stozae77c7662016-05-13 11:37:28 -07003152void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3153 result.append("Buffering stats:\n");
3154 result.append(" [Layer name] <Active time> <Two buffer> "
3155 "<Double buffered> <Triple buffered>\n");
3156 Mutex::Autolock lock(mBufferingStatsMutex);
3157 typedef std::tuple<std::string, float, float, float> BufferTuple;
3158 std::map<float, BufferTuple, std::greater<float>> sorted;
3159 for (const auto& statsPair : mBufferingStats) {
3160 const char* name = statsPair.first.c_str();
3161 const BufferingStats& stats = statsPair.second;
3162 if (stats.numSegments == 0) {
3163 continue;
3164 }
3165 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3166 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3167 stats.totalTime;
3168 float doubleBufferRatio = static_cast<float>(
3169 stats.doubleBufferedTime) / stats.totalTime;
3170 float tripleBufferRatio = static_cast<float>(
3171 stats.tripleBufferedTime) / stats.totalTime;
3172 sorted.insert({activeTime, {name, twoBufferRatio,
3173 doubleBufferRatio, tripleBufferRatio}});
3174 }
3175 for (const auto& sortedPair : sorted) {
3176 float activeTime = sortedPair.first;
3177 const BufferTuple& values = sortedPair.second;
3178 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3179 std::get<0>(values).c_str(), activeTime,
3180 std::get<1>(values), std::get<2>(values),
3181 std::get<3>(values));
3182 }
3183 result.append("\n");
3184}
3185
3186
Mathias Agopian74d211a2013-04-22 16:55:35 +02003187void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3188 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003189{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003190 bool colorize = false;
3191 if (index < args.size()
3192 && (args[index] == String16("--color"))) {
3193 colorize = true;
3194 index++;
3195 }
3196
3197 Colorizer colorizer(colorize);
3198
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003199 // figure out if we're stuck somewhere
3200 const nsecs_t now = systemTime();
3201 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3202 const nsecs_t inTransaction(mDebugInTransaction);
3203 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3204 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3205
3206 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003207 * Dump library configuration.
3208 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003209
3210 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003211 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003212 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003213 appendSfConfigString(result);
3214 appendUiConfigString(result);
3215 appendGuiConfigString(result);
3216 result.append("\n");
3217
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003218 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003219 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003220 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003221 result.append(SyncFeatures::getInstance().toString());
3222 result.append("\n");
3223
Dan Stoza9e56aa02015-11-02 13:00:03 -08003224 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3225
Andy McFadden41d67d72014-04-25 16:58:34 -07003226 colorizer.bold(result);
3227 result.append("DispSync configuration: ");
3228 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003229 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3230 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003231 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3232 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003233 result.append("\n");
3234
Dan Stozab90cf072015-03-05 11:05:59 -08003235 // Dump static screen stats
3236 result.append("\n");
3237 dumpStaticScreenStats(result);
3238 result.append("\n");
3239
Dan Stozae77c7662016-05-13 11:37:28 -07003240 dumpBufferingStats(result);
3241
Andy McFadden4803b742012-09-24 19:07:20 -07003242 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003243 * Dump the visible layer list
3244 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003245 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003247 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003248 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003249 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003250 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003251
3252 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003253 * Dump Display state
3254 */
3255
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003256 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003257 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003258 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003259 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3260 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003261 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003262 }
3263
3264 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003265 * Dump SurfaceFlinger global state
3266 */
3267
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003268 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003269 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003270 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003271
Mathias Agopian888c8222012-08-04 21:10:38 -07003272 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003273 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003274
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003275 colorizer.bold(result);
3276 result.appendFormat("EGL implementation : %s\n",
3277 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3278 colorizer.reset(result);
3279 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003280 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003281
Mathias Agopian875d8e12013-06-07 15:35:48 -07003282 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003283
Mathias Agopian42977342012-08-05 00:40:46 -07003284 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003285 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3286 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003287 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003288 " last eglSwapBuffers() time: %f us\n"
3289 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003290 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003291 " refresh-rate : %f fps\n"
3292 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003293 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003294 " gpu_to_cpu_unsupported : %d\n"
3295 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003296 mLastSwapBufferTime/1000.0,
3297 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003298 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003299 1e9 / activeConfig->getVsyncPeriod(),
3300 activeConfig->getDpiX(),
3301 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003302 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003303
Mathias Agopian74d211a2013-04-22 16:55:35 +02003304 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003305 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003306
Mathias Agopian74d211a2013-04-22 16:55:35 +02003307 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003308 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003309
3310 /*
3311 * VSYNC state
3312 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003313 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003314 result.append("\n");
3315
3316 /*
3317 * HWC layer minidump
3318 */
3319 for (size_t d = 0; d < mDisplays.size(); d++) {
3320 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3321 int32_t hwcId = displayDevice->getHwcDisplayId();
3322 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3323 continue;
3324 }
3325
3326 result.appendFormat("Display %d HWC layers:\n", hwcId);
3327 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003328 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003329 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003330 });
Dan Stozae22aec72016-08-01 13:20:59 -07003331 result.append("\n");
3332 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003333
3334 /*
3335 * Dump HWComposer state
3336 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003337 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003338 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003339 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003340 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003341 result.appendFormat(" h/w composer %s\n",
3342 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003343 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003344
3345 /*
3346 * Dump gralloc state
3347 */
3348 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3349 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003350}
3351
Mathias Agopian13127d82013-03-05 17:47:11 -08003352const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003353SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003354 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003355 wp<IBinder> dpy;
3356 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3357 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3358 dpy = mDisplays.keyAt(i);
3359 break;
3360 }
3361 }
3362 if (dpy == NULL) {
3363 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3364 // Just use the primary display so we have something to return
3365 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3366 }
3367 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003368}
3369
Keun young Park63f165f2012-08-31 10:53:36 -07003370bool SurfaceFlinger::startDdmConnection()
3371{
3372 void* libddmconnection_dso =
3373 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3374 if (!libddmconnection_dso) {
3375 return false;
3376 }
3377 void (*DdmConnection_start)(const char* name);
3378 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003379 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003380 if (!DdmConnection_start) {
3381 dlclose(libddmconnection_dso);
3382 return false;
3383 }
3384 (*DdmConnection_start)(getServiceName());
3385 return true;
3386}
3387
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003388status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003389 switch (code) {
3390 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003391 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003392 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003393 case CLEAR_ANIMATION_FRAME_STATS:
3394 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003395 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003396 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003397 {
3398 // codes that require permission check
3399 IPCThreadState* ipc = IPCThreadState::self();
3400 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003401 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003402 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003403 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003404 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003405 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003407 break;
3408 }
Robert Carr1db73f62016-12-21 12:58:51 -08003409 /*
3410 * Calling setTransactionState is safe, because you need to have been
3411 * granted a reference to Client* and Handle* to do anything with it.
3412 *
3413 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3414 */
3415 case SET_TRANSACTION_STATE:
3416 case CREATE_SCOPED_CONNECTION:
3417 {
3418 return OK;
3419 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003420 case CAPTURE_SCREEN:
3421 {
3422 // codes that require permission check
3423 IPCThreadState* ipc = IPCThreadState::self();
3424 const int pid = ipc->getCallingPid();
3425 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003426 if ((uid != AID_GRAPHICS) &&
3427 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003428 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003429 return PERMISSION_DENIED;
3430 }
3431 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003432 }
3433 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003434 return OK;
3435}
3436
3437status_t SurfaceFlinger::onTransact(
3438 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3439{
3440 status_t credentialCheck = CheckTransactCodeCredentials(code);
3441 if (credentialCheck != OK) {
3442 return credentialCheck;
3443 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003445 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3446 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003447 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003448 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003449 IPCThreadState* ipc = IPCThreadState::self();
3450 const int pid = ipc->getCallingPid();
3451 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003452 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003453 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454 return PERMISSION_DENIED;
3455 }
3456 int n;
3457 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003458 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003459 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460 return NO_ERROR;
3461 case 1002: // SHOW_UPDATES
3462 n = data.readInt32();
3463 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003464 invalidateHwcGeometry();
3465 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003467 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003468 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003469 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003471 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003472 setTransactionFlags(
3473 eTransactionNeeded|
3474 eDisplayTransactionNeeded|
3475 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003476 return NO_ERROR;
3477 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003478 case 1006:{ // send empty update
3479 signalRefresh();
3480 return NO_ERROR;
3481 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003482 case 1008: // toggle use of hw composer
3483 n = data.readInt32();
3484 mDebugDisableHWC = n ? 1 : 0;
3485 invalidateHwcGeometry();
3486 repaintEverything();
3487 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003488 case 1009: // toggle use of transform hint
3489 n = data.readInt32();
3490 mDebugDisableTransformHint = n ? 1 : 0;
3491 invalidateHwcGeometry();
3492 repaintEverything();
3493 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003495 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 reply->writeInt32(0);
3497 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003498 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003499 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 return NO_ERROR;
3501 case 1013: {
3502 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003503 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3504 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003505 return NO_ERROR;
3506 }
3507 case 1014: {
3508 // daltonize
3509 n = data.readInt32();
3510 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003511 case 1:
3512 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3513 break;
3514 case 2:
3515 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3516 break;
3517 case 3:
3518 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3519 break;
3520 default:
3521 mDaltonizer.setType(ColorBlindnessType::None);
3522 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003523 }
3524 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003525 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003526 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003527 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003528 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003529 invalidateHwcGeometry();
3530 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003531 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003533 case 1015: {
3534 // apply a color matrix
3535 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003536 if (n) {
3537 // color matrix is sent as mat3 matrix followed by vec3
3538 // offset, then packed into a mat4 where the last row is
3539 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003540 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003541 for (size_t j = 0; j < 4; j++) {
3542 mColorMatrix[i][j] = data.readFloat();
3543 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003544 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003545 } else {
3546 mColorMatrix = mat4();
3547 }
3548 invalidateHwcGeometry();
3549 repaintEverything();
3550 return NO_ERROR;
3551 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003552 // This is an experimental interface
3553 // Needs to be shifted to proper binder interface when we productize
3554 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003555 n = data.readInt32();
3556 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003557 return NO_ERROR;
3558 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003559 case 1017: {
3560 n = data.readInt32();
3561 mForceFullDamage = static_cast<bool>(n);
3562 return NO_ERROR;
3563 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003564 case 1018: { // Modify Choreographer's phase offset
3565 n = data.readInt32();
3566 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3567 return NO_ERROR;
3568 }
3569 case 1019: { // Modify SurfaceFlinger's phase offset
3570 n = data.readInt32();
3571 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3572 return NO_ERROR;
3573 }
Irvel468051e2016-06-13 16:44:44 -07003574 case 1020: { // Layer updates interceptor
3575 n = data.readInt32();
3576 if (n) {
3577 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003578 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003579 }
3580 else{
3581 ALOGV("Interceptor disabled");
3582 mInterceptor.disable();
3583 }
3584 return NO_ERROR;
3585 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003586 case 1021: { // Disable HWC virtual displays
3587 n = data.readInt32();
3588 mUseHwcVirtualDisplays = !n;
3589 return NO_ERROR;
3590 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 }
3592 }
3593 return err;
3594}
3595
Mathias Agopian53331da2011-08-22 21:44:41 -07003596void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003597 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003598 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003599}
3600
Mathias Agopian59119e62010-10-11 12:37:43 -07003601// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003602// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003603// ---------------------------------------------------------------------------
3604
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003605/* The code below is here to handle b/8734824
3606 *
3607 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003608 * from the surfaceflinger thread to the calling binder thread, where they
3609 * are executed. This allows the calling thread in the calling process to be
3610 * reused and not depend on having "enough" binder threads to handle the
3611 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003612 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003613class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003614 /* Parts of GraphicProducerWrapper are run on two different threads,
3615 * communicating by sending messages via Looper but also by shared member
3616 * data. Coherence maintenance is subtle and in places implicit (ugh).
3617 *
3618 * Don't rely on Looper's sendMessage/handleMessage providing
3619 * release/acquire semantics for any data not actually in the Message.
3620 * Data going from surfaceflinger to binder threads needs to be
3621 * synchronized explicitly.
3622 *
3623 * Barrier open/wait do provide release/acquire semantics. This provides
3624 * implicit synchronization for data coming back from binder to
3625 * surfaceflinger threads.
3626 */
3627
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003628 sp<IGraphicBufferProducer> impl;
3629 sp<Looper> looper;
3630 status_t result;
3631 bool exitPending;
3632 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003633 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003634 uint32_t code;
3635 Parcel const* data;
3636 Parcel* reply;
3637
3638 enum {
3639 MSG_API_CALL,
3640 MSG_EXIT
3641 };
3642
3643 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003644 * Called on surfaceflinger thread. This is called by our "fake"
3645 * BpGraphicBufferProducer. We package the data and reply Parcel and
3646 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003647 */
3648 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003649 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003650 this->code = code;
3651 this->data = &data;
3652 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003653 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003654 // if we've exited, we run the message synchronously right here.
3655 // note (JH): as far as I can tell from looking at the code, this
3656 // never actually happens. if it does, i'm not sure if it happens
3657 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003658 handleMessage(Message(MSG_API_CALL));
3659 } else {
3660 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003661 // Prevent stores to this->{code, data, reply} from being
3662 // reordered later than the construction of Message.
3663 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003664 looper->sendMessage(this, Message(MSG_API_CALL));
3665 barrier.wait();
3666 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003667 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003668 }
3669
3670 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003671 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003672 * call the real BpGraphicBufferProducer.
3673 */
3674 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003675 int what = message.what;
3676 // Prevent reads below from happening before the read from Message
3677 atomic_thread_fence(memory_order_acquire);
3678 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003679 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003680 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003681 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003682 exitRequested = true;
3683 }
3684 }
3685
3686public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003687 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003688 : impl(impl),
3689 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003690 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003691 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003692 exitRequested(false),
3693 code(0),
3694 data(NULL),
3695 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003696 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003697
Jesse Hallb154c422014-07-13 12:47:02 -07003698 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003699 status_t waitForResponse() {
3700 do {
3701 looper->pollOnce(-1);
3702 } while (!exitRequested);
3703 return result;
3704 }
3705
Jesse Hallb154c422014-07-13 12:47:02 -07003706 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003707 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003708 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003709 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003710 // Ensure this->result is visible to the binder thread before it
3711 // handles the message.
3712 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003713 looper->sendMessage(this, Message(MSG_EXIT));
3714 }
3715};
3716
3717
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003718status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3719 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003720 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003721 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003722 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003723
3724 if (CC_UNLIKELY(display == 0))
3725 return BAD_VALUE;
3726
3727 if (CC_UNLIKELY(producer == 0))
3728 return BAD_VALUE;
3729
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003730 // if we have secure windows on this display, never allow the screen capture
3731 // unless the producer interface is local (i.e.: we can take a screenshot for
3732 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003733 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003734
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003735 // Convert to surfaceflinger's internal rotation type.
3736 Transform::orientation_flags rotationFlags;
3737 switch (rotation) {
3738 case ISurfaceComposer::eRotateNone:
3739 rotationFlags = Transform::ROT_0;
3740 break;
3741 case ISurfaceComposer::eRotate90:
3742 rotationFlags = Transform::ROT_90;
3743 break;
3744 case ISurfaceComposer::eRotate180:
3745 rotationFlags = Transform::ROT_180;
3746 break;
3747 case ISurfaceComposer::eRotate270:
3748 rotationFlags = Transform::ROT_270;
3749 break;
3750 default:
3751 rotationFlags = Transform::ROT_0;
3752 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3753 break;
3754 }
3755
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003756 class MessageCaptureScreen : public MessageBase {
3757 SurfaceFlinger* flinger;
3758 sp<IBinder> display;
3759 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003760 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003761 uint32_t reqWidth, reqHeight;
3762 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003763 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003764 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003765 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003766 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003767 public:
3768 MessageCaptureScreen(SurfaceFlinger* flinger,
3769 const sp<IBinder>& display,
3770 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003771 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003772 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003773 bool useIdentityTransform,
3774 Transform::orientation_flags rotation,
3775 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003776 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003777 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003778 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003779 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003780 rotation(rotation), result(PERMISSION_DENIED),
3781 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003782 {
3783 }
3784 status_t getResult() const {
3785 return result;
3786 }
3787 virtual bool handler() {
3788 Mutex::Autolock _l(flinger->mStateLock);
3789 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003790 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003791 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003792 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003793 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003794 return true;
3795 }
3796 };
3797
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 // this creates a "fake" BBinder which will serve as a "fake" remote
3799 // binder to receive the marshaled calls and forward them to the
3800 // real remote (a BpGraphicBufferProducer)
3801 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3802
3803 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3804 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003805 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003806 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003807 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003808 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003809
3810 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003811 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003813 }
3814 return res;
3815}
3816
Mathias Agopian180f10d2013-04-10 22:55:41 -07003817
3818void SurfaceFlinger::renderScreenImplLocked(
3819 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003820 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003821 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003822 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003823{
3824 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003825 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003826
3827 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003828 const int32_t hw_w = hw->getWidth();
3829 const int32_t hw_h = hw->getHeight();
3830 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003831 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003832
Dan Stozac1879002014-05-22 15:59:05 -07003833 // if a default or invalid sourceCrop is passed in, set reasonable values
3834 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3835 !sourceCrop.isValid()) {
3836 sourceCrop.setLeftTop(Point(0, 0));
3837 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3838 }
3839
3840 // ensure that sourceCrop is inside screen
3841 if (sourceCrop.left < 0) {
3842 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3843 }
Dan Stozabe31f442014-06-11 11:20:54 -07003844 if (sourceCrop.right > hw_w) {
3845 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003846 }
3847 if (sourceCrop.top < 0) {
3848 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3849 }
Dan Stozabe31f442014-06-11 11:20:54 -07003850 if (sourceCrop.bottom > hw_h) {
3851 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003852 }
3853
Mathias Agopian180f10d2013-04-10 22:55:41 -07003854 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003855 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003856
3857 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003858 engine.setViewportAndProjection(
3859 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003860 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003861
3862 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003863 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003864
Robert Carr1f0a16a2016-10-24 16:27:39 -07003865 // We loop through the first level of layers without traversing,
3866 // as we need to interpret min/max layer Z in the top level Z space.
3867 for (const auto& layer : mDrawingState.layersSortedByZ) {
3868 if (layer->getLayerStack() != hw->getLayerStack()) {
3869 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003870 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003871 const Layer::State& state(layer->getDrawingState());
3872 if (state.z < minLayerZ || state.z > maxLayerZ) {
3873 continue;
3874 }
3875 layer->traverseInZOrder([&](Layer* layer) {
3876 if (!layer->isVisible()) {
3877 return;
3878 }
3879 if (filtering) layer->setFiltering(true);
3880 layer->draw(hw, useIdentityTransform);
3881 if (filtering) layer->setFiltering(false);
3882 });
3883 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003884
Mathias Agopian931bda12013-08-28 18:11:46 -07003885 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003886}
3887
3888
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003889status_t SurfaceFlinger::captureScreenImplLocked(
3890 const sp<const DisplayDevice>& hw,
3891 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003892 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003893 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003894 bool useIdentityTransform, Transform::orientation_flags rotation,
3895 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003896{
3897 ATRACE_CALL();
3898
Mathias Agopian180f10d2013-04-10 22:55:41 -07003899 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003900 uint32_t hw_w = hw->getWidth();
3901 uint32_t hw_h = hw->getHeight();
3902
3903 if (rotation & Transform::ROT_90) {
3904 std::swap(hw_w, hw_h);
3905 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003906
Mathias Agopian180f10d2013-04-10 22:55:41 -07003907 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3908 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3909 reqWidth, reqHeight, hw_w, hw_h);
3910 return BAD_VALUE;
3911 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003912
Mathias Agopian180f10d2013-04-10 22:55:41 -07003913 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3914 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3915
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003916 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003917 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003918 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003919 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3920 (state.z < minLayerZ || state.z > maxLayerZ)) {
3921 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003922 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003923 layer->traverseInZOrder([&](Layer *layer) {
3924 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3925 layer->isSecure());
3926 });
3927 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003928
3929 if (!isLocalScreenshot && secureLayerIsVisible) {
3930 ALOGW("FB is protected: PERMISSION_DENIED");
3931 return PERMISSION_DENIED;
3932 }
3933
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003934 // create a surface (because we're a producer, and we need to
3935 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003936 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003937
3938 // Put the screenshot Surface into async mode so that
3939 // Layer::headFenceHasSignaled will always return true and we'll latch the
3940 // first buffer regardless of whether or not its acquire fence has
3941 // signaled. This is needed to avoid a race condition in the rotation
3942 // animation. See b/30209608
3943 sur->setAsyncMode(true);
3944
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003945 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003946
Michael Lentine5a16a622015-05-21 13:48:24 -07003947 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3948 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003949 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3950 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003951
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003952 int err = 0;
3953 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003954 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003955 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3956 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003957
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003958 if (err == NO_ERROR) {
3959 ANativeWindowBuffer* buffer;
3960 /* TODO: Once we have the sync framework everywhere this can use
3961 * server-side waits on the fence that dequeueBuffer returns.
3962 */
3963 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3964 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003965 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003966 // create an EGLImage from the buffer so we can later
3967 // turn it into a texture
3968 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3969 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3970 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003971 // this binds the given EGLImage as a framebuffer for the
3972 // duration of this scope.
3973 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3974 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003975 // this will in fact render into our dequeued buffer
3976 // via an FBO, which means we didn't have to create
3977 // an EGLSurface and therefore we're not
3978 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003979 renderScreenImplLocked(
3980 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3981 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003982
Riley Andrews86639902014-08-15 12:27:24 -07003983 // Attempt to create a sync khr object that can produce a sync point. If that
3984 // isn't available, create a non-dupable sync object in the fallback path and
3985 // wait on it directly.
3986 EGLSyncKHR sync;
3987 if (!DEBUG_SCREENSHOTS) {
3988 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003989 // native fence fd will not be populated until flush() is done.
3990 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003991 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003992 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003993 }
Riley Andrews86639902014-08-15 12:27:24 -07003994 if (sync != EGL_NO_SYNC_KHR) {
3995 // get the sync fd
3996 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3997 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3998 ALOGW("captureScreen: failed to dup sync khr object");
3999 syncFd = -1;
4000 }
4001 eglDestroySyncKHR(mEGLDisplay, sync);
4002 } else {
4003 // fallback path
4004 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4005 if (sync != EGL_NO_SYNC_KHR) {
4006 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4007 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4008 EGLint eglErr = eglGetError();
4009 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4010 ALOGW("captureScreen: fence wait timed out");
4011 } else {
4012 ALOGW_IF(eglErr != EGL_SUCCESS,
4013 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4014 }
4015 eglDestroySyncKHR(mEGLDisplay, sync);
4016 } else {
4017 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4018 }
4019 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004020 if (DEBUG_SCREENSHOTS) {
4021 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4022 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4023 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4024 hw, minLayerZ, maxLayerZ);
4025 delete [] pixels;
4026 }
4027
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004028 } else {
4029 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4030 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004031 window->cancelBuffer(window, buffer, syncFd);
4032 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004033 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004034 // destroy our image
4035 eglDestroyImageKHR(mEGLDisplay, image);
4036 } else {
4037 result = BAD_VALUE;
4038 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004039 if (buffer) {
4040 // queueBuffer takes ownership of syncFd
4041 result = window->queueBuffer(window, buffer, syncFd);
4042 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004043 }
4044 } else {
4045 result = BAD_VALUE;
4046 }
4047 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4048 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004049
Mathias Agopian74c40c02010-09-29 13:02:36 -07004050 return result;
4051}
4052
Mathias Agopiand5556842013-09-19 17:08:37 -07004053void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004054 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004055 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004056 for (size_t y=0 ; y<h ; y++) {
4057 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4058 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004059 if (p[x] != 0xFF000000) return;
4060 }
4061 }
4062 ALOGE("*** we just took a black screenshot ***\n"
4063 "requested minz=%d, maxz=%d, layerStack=%d",
4064 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004065
Robert Carr2047fae2016-11-28 14:09:09 -08004066 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004067 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004068 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004069 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4070 state.z <= maxLayerZ) {
4071 layer->traverseInZOrder([&](Layer* layer) {
4072 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4073 layer->isVisible() ? '+' : '-',
4074 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004075 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004076 i++;
4077 });
4078 }
4079 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004080 }
4081}
4082
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004083// ---------------------------------------------------------------------------
4084
Robert Carr2047fae2016-11-28 14:09:09 -08004085void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4086 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004087}
4088
Robert Carr2047fae2016-11-28 14:09:09 -08004089void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4090 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004091}
4092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004094
4095
4096#if defined(__gl_h_)
4097#error "don't include gl/gl.h in this file"
4098#endif
4099
4100#if defined(__gl2_h_)
4101#error "don't include gl2/gl2.h in this file"
4102#endif