blob: c9445e7b16b973e2d48e95e2d572a166896eacf3 [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.
139static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
140
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");
Fabien Sanglard4e06b002017-02-07 22:02:22 +0000216 mLayerTripleBufferingDisabled = !atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800217 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{
341 const nsecs_t now = systemTime();
342 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000343 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700344 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700345
346 // wait patiently for the window manager death
347 const String16 name("window");
348 sp<IBinder> window(defaultServiceManager()->getService(name));
349 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700350 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700351 }
352
353 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700354 // formerly we would just kill the process, but we now ask it to exit so it
355 // can choose where to stop the animation.
356 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700357
358 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
359 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
360 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361}
362
Mathias Agopian3f844832013-08-07 21:24:32 -0700363void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700364 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700365 RenderEngine& engine;
366 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700367 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700368 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
369 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700370 }
371 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700372 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700373 return true;
374 }
375 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700376 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700377}
378
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379class DispSyncSource : public VSyncSource, private DispSync::Callback {
380public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700381 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000382 const char* name) :
383 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700384 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700385 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000386 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
387 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700388 mDispSync(dispSync),
389 mCallbackMutex(),
390 mCallback(),
391 mVsyncMutex(),
392 mPhaseOffset(phaseOffset),
393 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700394
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700395 virtual ~DispSyncSource() {}
396
397 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700399 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000400 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401 static_cast<DispSync::Callback*>(this));
402 if (err != NO_ERROR) {
403 ALOGE("error registering vsync callback: %s (%d)",
404 strerror(-err), err);
405 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700406 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700407 } else {
408 status_t err = mDispSync->removeEventListener(
409 static_cast<DispSync::Callback*>(this));
410 if (err != NO_ERROR) {
411 ALOGE("error unregistering vsync callback: %s (%d)",
412 strerror(-err), err);
413 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700414 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700416 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 }
418
419 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 mCallback = callback;
422 }
423
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700424 virtual void setPhaseOffset(nsecs_t phaseOffset) {
425 Mutex::Autolock lock(mVsyncMutex);
426
427 // Normalize phaseOffset to [0, period)
428 auto period = mDispSync->getPeriod();
429 phaseOffset %= period;
430 if (phaseOffset < 0) {
431 // If we're here, then phaseOffset is in (-period, 0). After this
432 // operation, it will be in (0, period)
433 phaseOffset += period;
434 }
435 mPhaseOffset = phaseOffset;
436
437 // If we're not enabled, we don't need to mess with the listeners
438 if (!mEnabled) {
439 return;
440 }
441
442 // Remove the listener with the old offset
443 status_t err = mDispSync->removeEventListener(
444 static_cast<DispSync::Callback*>(this));
445 if (err != NO_ERROR) {
446 ALOGE("error unregistering vsync callback: %s (%d)",
447 strerror(-err), err);
448 }
449
450 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000451 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700452 static_cast<DispSync::Callback*>(this));
453 if (err != NO_ERROR) {
454 ALOGE("error registering vsync callback: %s (%d)",
455 strerror(-err), err);
456 }
457 }
458
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459private:
460 virtual void onDispSyncEvent(nsecs_t when) {
461 sp<VSyncSource::Callback> callback;
462 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 callback = mCallback;
465
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466 if (mTraceVsync) {
467 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700468 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700469 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 }
471
472 if (callback != NULL) {
473 callback->onVSyncEvent(when);
474 }
475 }
476
Tim Murray4a4e4a22016-04-19 16:29:23 +0000477 const char* const mName;
478
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 int mValue;
480
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700481 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700482 const String8 mVsyncOnLabel;
483 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700486
487 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489
490 Mutex mVsyncMutex; // Protects the following
491 nsecs_t mPhaseOffset;
492 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493};
494
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700495class InjectVSyncSource : public VSyncSource {
496public:
497 InjectVSyncSource() {}
498
499 virtual ~InjectVSyncSource() {}
500
501 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
502 std::lock_guard<std::mutex> lock(mCallbackMutex);
503 mCallback = callback;
504 }
505
506 virtual void onInjectSyncEvent(nsecs_t when) {
507 std::lock_guard<std::mutex> lock(mCallbackMutex);
508 mCallback->onVSyncEvent(when);
509 }
510
511 virtual void setVSyncEnabled(bool) {}
512 virtual void setPhaseOffset(nsecs_t) {}
513
514private:
515 std::mutex mCallbackMutex; // Protects the following
516 sp<VSyncSource::Callback> mCallback;
517};
518
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700520 ALOGI( "SurfaceFlinger's main thread ready to run. "
521 "Initializing graphics H/W...");
522
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900523 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
524
Dan Stoza9e56aa02015-11-02 13:00:03 -0800525 { // Autolock scope
526 Mutex::Autolock _l(mStateLock);
527
528 // initialize EGL for the default display
529 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
530 eglInitialize(mEGLDisplay, NULL, NULL);
531
532 // start the EventThread
533 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
534 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700535 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800536 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
537 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700538 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800539 mEventQueue.setEventThread(mSFEventThread);
540
Tim Murrayacff43d2016-07-29 13:57:24 -0700541 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700542 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700543 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700544 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
545 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
546 }
547
Dan Stoza9e56aa02015-11-02 13:00:03 -0800548 // Get a RenderEngine for the given display / config (can't fail)
549 mRenderEngine = RenderEngine::create(mEGLDisplay,
550 HAL_PIXEL_FORMAT_RGBA_8888);
551 }
552
553 // Drop the state lock while we initialize the hardware composer. We drop
554 // the lock because on creation, it will call back into SurfaceFlinger to
555 // initialize the primary display.
556 mHwc = new HWComposer(this);
557 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
558
Jesse Hall692c7232012-11-08 15:41:56 -0800559 Mutex::Autolock _l(mStateLock);
560
Mathias Agopian875d8e12013-06-07 15:35:48 -0700561 // retrieve the EGL context that was selected/created
562 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700563
Mathias Agopianda27af92012-09-13 18:17:13 -0700564 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
565 "couldn't create EGLContext");
566
Dan Stoza9e56aa02015-11-02 13:00:03 -0800567 // make the GLContext current so that we can create textures when creating
568 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700569 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
570
Jamie Gennisd1700752013-10-14 12:22:52 -0700571 mEventControlThread = new EventControlThread(this);
572 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
573
Mathias Agopian92a979a2012-08-02 18:32:23 -0700574 // initialize our drawing state
575 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700576
Andy McFadden13a082e2012-08-24 10:16:42 -0700577 // set initial conditions (e.g. unblank default device)
578 initializeDisplays();
579
Dan Stoza4e637772016-07-28 13:31:51 -0700580 mRenderEngine->primeCache();
581
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700582 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700583 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700586}
587
Mathias Agopiana67e4182012-06-19 17:26:12 -0700588void SurfaceFlinger::startBootAnim() {
589 // start boot animation
590 property_set("service.bootanim.exit", "0");
591 property_set("ctl.start", "bootanim");
592}
593
Mathias Agopian875d8e12013-06-07 15:35:48 -0700594size_t SurfaceFlinger::getMaxTextureSize() const {
595 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700596}
597
Mathias Agopian875d8e12013-06-07 15:35:48 -0700598size_t SurfaceFlinger::getMaxViewportDims() const {
599 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700600}
601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800602// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800603
Jamie Gennis582270d2011-08-17 18:19:00 -0700604bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800605 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800606 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800607 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700608 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800609}
610
Brian Anderson069b3652016-07-22 10:32:47 -0700611status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700612 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700613 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700614 FrameEvent::REQUESTED_PRESENT,
615 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700616 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700617 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700618 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700619 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700620 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700621 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700622 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700623 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700624 };
625 return NO_ERROR;
626}
627
Dan Stoza7f7da322014-05-02 15:26:25 -0700628status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
629 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700630 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700631 return BAD_VALUE;
632 }
633
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500634 if (!display.get())
635 return NAME_NOT_FOUND;
636
Jesse Hall692c7232012-11-08 15:41:56 -0800637 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700638 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800639 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700640 type = i;
641 break;
642 }
643 }
644
645 if (type < 0) {
646 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700647 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700648
Mathias Agopian8b736f12012-08-13 17:54:26 -0700649 // TODO: Not sure if display density should handled by SF any longer
650 class Density {
651 static int getDensityFromProperty(char const* propName) {
652 char property[PROPERTY_VALUE_MAX];
653 int density = 0;
654 if (property_get(propName, property, NULL) > 0) {
655 density = atoi(property);
656 }
657 return density;
658 }
659 public:
660 static int getEmuDensity() {
661 return getDensityFromProperty("qemu.sf.lcd_density"); }
662 static int getBuildDensity() {
663 return getDensityFromProperty("ro.sf.lcd_density"); }
664 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700665
Dan Stoza7f7da322014-05-02 15:26:25 -0700666 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700667
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700669 DisplayInfo info = DisplayInfo();
670
Dan Stoza9e56aa02015-11-02 13:00:03 -0800671 float xdpi = hwConfig->getDpiX();
672 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700673
674 if (type == DisplayDevice::DISPLAY_PRIMARY) {
675 // The density of the device is provided by a build property
676 float density = Density::getBuildDensity() / 160.0f;
677 if (density == 0) {
678 // the build doesn't provide a density -- this is wrong!
679 // use xdpi instead
680 ALOGE("ro.sf.lcd_density must be defined as a build property");
681 density = xdpi / 160.0f;
682 }
683 if (Density::getEmuDensity()) {
684 // if "qemu.sf.lcd_density" is specified, it overrides everything
685 xdpi = ydpi = density = Density::getEmuDensity();
686 density /= 160.0f;
687 }
688 info.density = density;
689
690 // TODO: this needs to go away (currently needed only by webkit)
691 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
692 info.orientation = hw->getOrientation();
693 } else {
694 // TODO: where should this value come from?
695 static const int TV_DENSITY = 213;
696 info.density = TV_DENSITY / 160.0f;
697 info.orientation = 0;
698 }
699
Dan Stoza9e56aa02015-11-02 13:00:03 -0800700 info.w = hwConfig->getWidth();
701 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700702 info.xdpi = xdpi;
703 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900705 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800706
Andy McFadden91b2ca82014-06-13 14:04:23 -0700707 // This is how far in advance a buffer must be queued for
708 // presentation at a given time. If you want a buffer to appear
709 // on the screen at time N, you must submit the buffer before
710 // (N - presentationDeadline).
711 //
712 // Normally it's one full refresh period (to give SF a chance to
713 // latch the buffer), but this can be reduced by configuring a
714 // DispSync offset. Any additional delays introduced by the hardware
715 // composer or panel must be accounted for here.
716 //
717 // We add an additional 1ms to allow for processing time and
718 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 info.presentationDeadline = hwConfig->getVsyncPeriod() -
720 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700721
722 // All non-virtual displays are currently considered secure.
723 info.secure = true;
724
Michael Wright28f24d02016-07-12 13:30:53 -0700725 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700726 }
727
Dan Stoza7f7da322014-05-02 15:26:25 -0700728 return NO_ERROR;
729}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700730
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800731status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700732 DisplayStatInfo* stats) {
733 if (stats == NULL) {
734 return BAD_VALUE;
735 }
736
737 // FIXME for now we always return stats for the primary display
738 memset(stats, 0, sizeof(*stats));
739 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
740 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
741 return NO_ERROR;
742}
743
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700744int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800745 if (display == NULL) {
746 ALOGE("%s : display is NULL", __func__);
747 return BAD_VALUE;
748 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700749 sp<DisplayDevice> device(getDisplayDevice(display));
750 if (device != NULL) {
751 return device->getActiveConfig();
752 }
753 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700754}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700755
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700756void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
757 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
758 this);
759 int32_t type = hw->getDisplayType();
760 int currentMode = hw->getActiveConfig();
761
762 if (mode == currentMode) {
763 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
764 return;
765 }
766
767 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
768 ALOGW("Trying to set config for virtual display");
769 return;
770 }
771
772 hw->setActiveConfig(mode);
773 getHwComposer().setActiveConfig(type, mode);
774}
775
776status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
777 class MessageSetActiveConfig: public MessageBase {
778 SurfaceFlinger& mFlinger;
779 sp<IBinder> mDisplay;
780 int mMode;
781 public:
782 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
783 int mode) :
784 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
785 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700786 Vector<DisplayInfo> configs;
787 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700788 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700789 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700790 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700791 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700792 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700793 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
794 if (hw == NULL) {
795 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700796 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700797 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
798 ALOGW("Attempt to set active config = %d for virtual display",
799 mMode);
800 } else {
801 mFlinger.setActiveConfigInternal(hw, mMode);
802 }
803 return true;
804 }
805 };
806 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
807 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700808 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700809}
Michael Wright28f24d02016-07-12 13:30:53 -0700810status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
811 Vector<android_color_mode_t>* outColorModes) {
812 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
813 return BAD_VALUE;
814 }
815
816 if (!display.get()) {
817 return NAME_NOT_FOUND;
818 }
819
820 int32_t type = NAME_NOT_FOUND;
821 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
822 if (display == mBuiltinDisplays[i]) {
823 type = i;
824 break;
825 }
826 }
827
828 if (type < 0) {
829 return type;
830 }
831
832 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
833 outColorModes->clear();
834 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
835
836 return NO_ERROR;
837}
838
839android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
840 sp<DisplayDevice> device(getDisplayDevice(display));
841 if (device != nullptr) {
842 return device->getActiveColorMode();
843 }
844 return static_cast<android_color_mode_t>(BAD_VALUE);
845}
846
847void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
848 android_color_mode_t mode) {
849 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
850 this);
851 int32_t type = hw->getDisplayType();
852 android_color_mode_t currentMode = hw->getActiveColorMode();
853
854 if (mode == currentMode) {
855 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
856 return;
857 }
858
859 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
860 ALOGW("Trying to set config for virtual display");
861 return;
862 }
863
864 hw->setActiveColorMode(mode);
865 getHwComposer().setActiveColorMode(type, mode);
866}
867
868
869status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
870 android_color_mode_t colorMode) {
871 class MessageSetActiveColorMode: public MessageBase {
872 SurfaceFlinger& mFlinger;
873 sp<IBinder> mDisplay;
874 android_color_mode_t mMode;
875 public:
876 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
877 android_color_mode_t mode) :
878 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
879 virtual bool handler() {
880 Vector<android_color_mode_t> modes;
881 mFlinger.getDisplayColorModes(mDisplay, &modes);
882 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
883 if (mMode < 0 || !exists) {
884 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
885 mDisplay.get());
886 return true;
887 }
888 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
889 if (hw == nullptr) {
890 ALOGE("Attempt to set active color mode = %d for null display %p",
891 mMode, mDisplay.get());
892 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
893 ALOGW("Attempt to set active color mode= %d for virtual display",
894 mMode);
895 } else {
896 mFlinger.setActiveColorModeInternal(hw, mMode);
897 }
898 return true;
899 }
900 };
901 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
902 postMessageSync(msg);
903 return NO_ERROR;
904}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700905
Svetoslavd85084b2014-03-20 10:28:31 -0700906status_t SurfaceFlinger::clearAnimationFrameStats() {
907 Mutex::Autolock _l(mStateLock);
908 mAnimFrameTracker.clearStats();
909 return NO_ERROR;
910}
911
912status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
913 Mutex::Autolock _l(mStateLock);
914 mAnimFrameTracker.getStats(outStats);
915 return NO_ERROR;
916}
917
Dan Stozac4f471e2016-03-24 09:31:08 -0700918status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
919 HdrCapabilities* outCapabilities) const {
920 Mutex::Autolock _l(mStateLock);
921
922 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
923 if (displayDevice == nullptr) {
924 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
925 return BAD_VALUE;
926 }
927
928 std::unique_ptr<HdrCapabilities> capabilities =
929 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
930 if (capabilities) {
931 std::swap(*outCapabilities, *capabilities);
932 } else {
933 return BAD_VALUE;
934 }
935
936 return NO_ERROR;
937}
938
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700939status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
940 if (enable == mInjectVSyncs) {
941 return NO_ERROR;
942 }
943
944 if (enable) {
945 mInjectVSyncs = enable;
946 ALOGV("VSync Injections enabled");
947 if (mVSyncInjector.get() == nullptr) {
948 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700949 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700950 }
951 mEventQueue.setEventThread(mInjectorEventThread);
952 } else {
953 mInjectVSyncs = enable;
954 ALOGV("VSync Injections disabled");
955 mEventQueue.setEventThread(mSFEventThread);
956 mVSyncInjector.clear();
957 }
958 return NO_ERROR;
959}
960
961status_t SurfaceFlinger::injectVSync(nsecs_t when) {
962 if (!mInjectVSyncs) {
963 ALOGE("VSync Injections not enabled");
964 return BAD_VALUE;
965 }
966 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
967 ALOGV("Injecting VSync inside SurfaceFlinger");
968 mVSyncInjector->onInjectSyncEvent(when);
969 }
970 return NO_ERROR;
971}
972
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800973// ----------------------------------------------------------------------------
974
975sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800976 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700977}
978
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800979// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800980
981void SurfaceFlinger::waitForEvent() {
982 mEventQueue.waitMessage();
983}
984
985void SurfaceFlinger::signalTransaction() {
986 mEventQueue.invalidate();
987}
988
989void SurfaceFlinger::signalLayerUpdate() {
990 mEventQueue.invalidate();
991}
992
993void SurfaceFlinger::signalRefresh() {
994 mEventQueue.refresh();
995}
996
997status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800998 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800999 return mEventQueue.postMessage(msg, reltime);
1000}
1001
1002status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001003 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001004 status_t res = mEventQueue.postMessage(msg, reltime);
1005 if (res == NO_ERROR) {
1006 msg->wait();
1007 }
1008 return res;
1009}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001010
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001011void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001012 do {
1013 waitForEvent();
1014 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015}
1016
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001017void SurfaceFlinger::enableHardwareVsync() {
1018 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001019 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001020 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001021 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1022 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001023 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001024 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001025}
1026
Jesse Hall948fe0c2013-10-14 12:56:09 -07001027void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001028 Mutex::Autolock _l(mHWVsyncLock);
1029
Jesse Hall948fe0c2013-10-14 12:56:09 -07001030 if (makeAvailable) {
1031 mHWVsyncAvailable = true;
1032 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001033 // Hardware vsync is not currently available, so abort the resync
1034 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001035 return;
1036 }
1037
Dan Stoza9e56aa02015-11-02 13:00:03 -08001038 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1039 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001040
1041 mPrimaryDispSync.reset();
1042 mPrimaryDispSync.setPeriod(period);
1043
1044 if (!mPrimaryHWVsyncEnabled) {
1045 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001046 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1047 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001048 mPrimaryHWVsyncEnabled = true;
1049 }
1050}
1051
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 Mutex::Autolock _l(mHWVsyncLock);
1054 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1056 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057 mPrimaryDispSync.endResync();
1058 mPrimaryHWVsyncEnabled = false;
1059 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060 if (makeUnavailable) {
1061 mHWVsyncAvailable = false;
1062 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001063}
1064
Tim Murray4a4e4a22016-04-19 16:29:23 +00001065void SurfaceFlinger::resyncWithRateLimit() {
1066 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1067 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001068 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001069 }
1070}
1071
Dan Stoza9e56aa02015-11-02 13:00:03 -08001072void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001073 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074
Jamie Gennisd1700752013-10-14 12:22:52 -07001075 { // Scope for the lock
1076 Mutex::Autolock _l(mHWVsyncLock);
1077 if (type == 0 && mPrimaryHWVsyncEnabled) {
1078 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001080 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001081
1082 if (needsHwVsync) {
1083 enableHardwareVsync();
1084 } else {
1085 disableHardwareVsync(false);
1086 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001087}
1088
Dan Stoza9e56aa02015-11-02 13:00:03 -08001089void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1090 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1091 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1092 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001093
Dan Stoza9e56aa02015-11-02 13:00:03 -08001094 // All non-virtual displays are currently considered secure.
1095 bool isSecure = true;
1096
1097 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1098 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1099 wp<IBinder> token = mBuiltinDisplays[type];
1100
1101 sp<IGraphicBufferProducer> producer;
1102 sp<IGraphicBufferConsumer> consumer;
1103 BufferQueue::createBufferQueue(&producer, &consumer,
1104 new GraphicBufferAlloc());
1105
1106 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1107 DisplayDevice::DISPLAY_PRIMARY, consumer);
1108 sp<DisplayDevice> hw = new DisplayDevice(this,
1109 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1110 producer, mRenderEngine->getEGLConfig());
1111 mDisplays.add(token, hw);
1112 } else {
1113 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001114 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001115 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001116 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001117 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001118 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1119 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001120 }
1121 setTransactionFlags(eDisplayTransactionNeeded);
1122
Andy McFadden9e9689c2012-10-10 18:17:51 -07001123 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001124 }
Mathias Agopian86303202012-07-24 22:46:10 -07001125}
1126
Dan Stoza9e56aa02015-11-02 13:00:03 -08001127void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001128 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001129 getHwComposer().setVsyncEnabled(disp,
1130 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001131}
1132
Mathias Agopian4fec8732012-06-29 14:12:52 -07001133void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001134 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001135 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001136 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001137 bool frameMissed = !mHadClientComposition &&
1138 mPreviousPresentFence != Fence::NO_FENCE &&
1139 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1140 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001141 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001142 signalLayerUpdate();
1143 break;
1144 }
1145
Dan Stoza6b9454d2014-11-07 16:00:59 -08001146 bool refreshNeeded = handleMessageTransaction();
1147 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001148 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001149 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001150 // Signal a refresh if a transaction modified the window state,
1151 // a new buffer was latched, or if HWC has requested a full
1152 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001153 signalRefresh();
1154 }
1155 break;
1156 }
1157 case MessageQueue::REFRESH: {
1158 handleMessageRefresh();
1159 break;
1160 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161 }
1162}
1163
Dan Stoza6b9454d2014-11-07 16:00:59 -08001164bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001165 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001166 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001167 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001168 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001169 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001170 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001171}
1172
Dan Stoza6b9454d2014-11-07 16:00:59 -08001173bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001174 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001175 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001176}
1177
1178void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001179 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001180
Pablo Ceballos40845df2016-01-25 17:41:15 -08001181 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001182
Brian Andersond6927fb2016-07-23 23:37:30 -07001183 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001184 rebuildLayerStacks();
1185 setUpHWComposer();
1186 doDebugFlashRegions();
1187 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001188 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001189
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001190 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001191
1192 mHadClientComposition = false;
1193 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1194 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1195 mHadClientComposition = mHadClientComposition ||
1196 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1197 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001198
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001200}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001201
Mathias Agopiancd60f992012-08-16 16:28:27 -07001202void SurfaceFlinger::doDebugFlashRegions()
1203{
1204 // is debugging enabled
1205 if (CC_LIKELY(!mDebugRegion))
1206 return;
1207
1208 const bool repaintEverything = mRepaintEverything;
1209 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1210 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001211 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001212 // transform the dirty region into this screen's coordinate space
1213 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1214 if (!dirtyRegion.isEmpty()) {
1215 // redraw the whole screen
1216 doComposeSurfaces(hw, Region(hw->bounds()));
1217
1218 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001219 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001220 RenderEngine& engine(getRenderEngine());
1221 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1222
Mathias Agopianda27af92012-09-13 18:17:13 -07001223 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001224 }
1225 }
1226 }
1227
1228 postFramebuffer();
1229
1230 if (mDebugRegion > 1) {
1231 usleep(mDebugRegion * 1000);
1232 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001233
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001235 auto& displayDevice = mDisplays[displayId];
1236 if (!displayDevice->isDisplayOn()) {
1237 continue;
1238 }
1239
1240 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1242 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001243 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001244}
1245
Brian Andersond6927fb2016-07-23 23:37:30 -07001246void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001247{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001248 ATRACE_CALL();
1249 ALOGV("preComposition");
1250
Mathias Agopiancd60f992012-08-16 16:28:27 -07001251 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001252 mDrawingState.traverseInZOrder([&](Layer* layer) {
1253 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001254 needExtraInvalidate = true;
1255 }
Robert Carr2047fae2016-11-28 14:09:09 -08001256 });
1257
Mathias Agopiancd60f992012-08-16 16:28:27 -07001258 if (needExtraInvalidate) {
1259 signalLayerUpdate();
1260 }
1261}
1262
Brian Andersond6927fb2016-07-23 23:37:30 -07001263void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001264{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001265 ATRACE_CALL();
1266 ALOGV("postComposition");
1267
Brian Anderson3546a3f2016-07-14 11:51:14 -07001268 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001269 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001270 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001271 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001272 }
1273
Brian Andersond6927fb2016-07-23 23:37:30 -07001274 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001275
1276 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1277 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1278 glCompositionDoneFenceTime =
1279 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1280 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1281 } else {
1282 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1283 }
1284 mGlCompositionDoneTimeline.updateSignalTimes();
1285
1286 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1287 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1288 mDisplayTimeline.push(displayFenceTime);
1289 mDisplayTimeline.updateSignalTimes();
1290
1291 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1292 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1293 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1294 presentFenceTime = &displayFenceTime;
1295 } else {
1296 retireFenceTime = &displayFenceTime;
1297 }
Robert Carr2047fae2016-11-28 14:09:09 -08001298 mDrawingState.traverseInZOrder([&](Layer* layer) {
1299 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1300 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001301 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001302 recordBufferingStats(layer->getName().string(),
1303 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001304 }
Robert Carr2047fae2016-11-28 14:09:09 -08001305 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001306
Brian Anderson3d4039d2016-09-23 16:31:30 -07001307 if (displayFence->isValid()) {
1308 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 enableHardwareVsync();
1310 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312 }
1313 }
1314
Andy McFadden5167ec62014-05-22 13:08:43 -07001315 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001316 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317 enableHardwareVsync();
1318 }
1319 }
1320
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001321 if (mAnimCompositionPending) {
1322 mAnimCompositionPending = false;
1323
Brian Anderson3d4039d2016-09-23 16:31:30 -07001324 if (displayFenceTime->isValid()) {
1325 mAnimFrameTracker.setActualPresentFence(
1326 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001327 } else {
1328 // The HWC doesn't support present fences, so use the refresh
1329 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 nsecs_t presentTime =
1331 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001332 mAnimFrameTracker.setActualPresentTime(presentTime);
1333 }
1334 mAnimFrameTracker.advanceFrame();
1335 }
Dan Stozab90cf072015-03-05 11:05:59 -08001336
1337 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1338 return;
1339 }
1340
1341 nsecs_t currentTime = systemTime();
1342 if (mHasPoweredOff) {
1343 mHasPoweredOff = false;
1344 } else {
1345 nsecs_t period = mPrimaryDispSync.getPeriod();
1346 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1347 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1348 if (numPeriods < NUM_BUCKETS - 1) {
1349 mFrameBuckets[numPeriods] += elapsedTime;
1350 } else {
1351 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1352 }
1353 mTotalTime += elapsedTime;
1354 }
1355 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001356}
1357
1358void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 ATRACE_CALL();
1360 ALOGV("rebuildLayerStacks");
1361
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001363 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001364 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001365 mVisibleRegionsDirty = false;
1366 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001367
Mathias Agopian92a979a2012-08-02 18:32:23 -07001368 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001369 Region opaqueRegion;
1370 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 Vector<sp<Layer>> layersSortedByZ;
1372 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1373 const Transform& tr(displayDevice->getTransform());
1374 const Rect bounds(displayDevice->getBounds());
1375 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001376 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 displayDevice->getLayerStack(), dirtyRegion,
1378 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001379
Robert Carr2047fae2016-11-28 14:09:09 -08001380 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001381 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001382 Region drawRegion(tr.transform(
1383 layer->visibleNonTransparentRegion));
1384 drawRegion.andSelf(bounds);
1385 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001386 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001387 } else {
1388 // Clear out the HWC layer if this layer was
1389 // previously visible, but no longer is
1390 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1391 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001392 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001393 }
Robert Carr2047fae2016-11-28 14:09:09 -08001394 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001395 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1397 displayDevice->undefinedRegion.set(bounds);
1398 displayDevice->undefinedRegion.subtractSelf(
1399 tr.transform(opaqueRegion));
1400 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001401 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001402 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001403}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001404
Mathias Agopiancd60f992012-08-16 16:28:27 -07001405void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001406 ATRACE_CALL();
1407 ALOGV("setUpHWComposer");
1408
Jesse Hall028dc8f2013-08-20 16:35:32 -07001409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001410 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1411 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1412 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1413
1414 // If nothing has changed (!dirty), don't recompose.
1415 // If something changed, but we don't currently have any visible layers,
1416 // and didn't when we last did a composition, then skip it this time.
1417 // The second rule does two things:
1418 // - When all layers are removed from a display, we'll emit one black
1419 // frame, then nothing more until we get new layers.
1420 // - When a display is created with a private layer stack, we won't
1421 // emit any black frames until a layer is added to the layer stack.
1422 bool mustRecompose = dirty && !(empty && wasEmpty);
1423
1424 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1425 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1426 mustRecompose ? "doing" : "skipping",
1427 dirty ? "+" : "-",
1428 empty ? "+" : "-",
1429 wasEmpty ? "+" : "-");
1430
Dan Stoza71433162014-02-04 16:22:36 -08001431 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001432
1433 if (mustRecompose) {
1434 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1435 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001436 }
1437
Dan Stoza9e56aa02015-11-02 13:00:03 -08001438 // build the h/w work list
1439 if (CC_UNLIKELY(mGeometryInvalid)) {
1440 mGeometryInvalid = false;
1441 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1442 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1443 const auto hwcId = displayDevice->getHwcDisplayId();
1444 if (hwcId >= 0) {
1445 const Vector<sp<Layer>>& currentLayers(
1446 displayDevice->getVisibleLayersSortedByZ());
1447 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001448 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001449 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 if (!layer->hasHwcLayer(hwcId)) {
1451 auto hwcLayer = mHwc->createLayer(hwcId);
1452 if (hwcLayer) {
1453 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1454 } else {
1455 layer->forceClientComposition(hwcId);
1456 foundLayerWithoutHwc = true;
1457 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001458 }
1459 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001460
Robert Carrae060832016-11-28 10:51:00 -08001461 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001462 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001464 }
1465 }
1466 }
1467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001468 }
Riley Andrews03414a12014-07-01 14:22:59 -07001469
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001470
1471 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1472
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 // Set the per-frame data
1474 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1475 auto& displayDevice = mDisplays[displayId];
1476 const auto hwcId = displayDevice->getHwcDisplayId();
1477 if (hwcId < 0) {
1478 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001479 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001480 if (colorMatrix != mPreviousColorMatrix) {
1481 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1482 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1483 "display %zd: %d", displayId, result);
1484 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001485 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1486 layer->setPerFrameData(displayDevice);
1487 }
1488 }
1489
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001490 mPreviousColorMatrix = colorMatrix;
1491
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001493 auto& displayDevice = mDisplays[displayId];
1494 if (!displayDevice->isDisplayOn()) {
1495 continue;
1496 }
1497
1498 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1500 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001501 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001503
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504void SurfaceFlinger::doComposition() {
1505 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 ALOGV("doComposition");
1507
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001508 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001509 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001510 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001511 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 // transform the dirty region into this screen's coordinate space
1513 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001514
1515 // repaint the framebuffer (if needed)
1516 doDisplayComposition(hw, dirtyRegion);
1517
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518 hw->dirtyRegion.clear();
1519 hw->flip(hw->swapRegion);
1520 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001521 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001523 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524}
1525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001526void SurfaceFlinger::postFramebuffer()
1527{
Mathias Agopian841cde52012-03-01 15:44:37 -08001528 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001530
Mathias Agopiana44b0412011-10-16 18:46:35 -07001531 const nsecs_t now = systemTime();
1532 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001533
Dan Stoza9e56aa02015-11-02 13:00:03 -08001534 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1535 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001536 if (!displayDevice->isDisplayOn()) {
1537 continue;
1538 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001539 const auto hwcId = displayDevice->getHwcDisplayId();
1540 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001541 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001542 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001543 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001544 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001545 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1546 sp<Fence> releaseFence = Fence::NO_FENCE;
1547 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1548 releaseFence = displayDevice->getClientTargetAcquireFence();
1549 } else {
1550 auto hwcLayer = layer->getHwcLayer(hwcId);
1551 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001552 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 layer->onLayerDisplayed(releaseFence);
1554 }
1555 if (hwcId >= 0) {
1556 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001557 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001558 }
1559
Mathias Agopiana44b0412011-10-16 18:46:35 -07001560 mLastSwapBufferTime = systemTime() - now;
1561 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001562
1563 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1564 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1565 logFrameStats();
1566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001567}
1568
Mathias Agopian87baae12012-07-31 12:38:26 -07001569void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001570{
Mathias Agopian841cde52012-03-01 15:44:37 -08001571 ATRACE_CALL();
1572
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001573 // here we keep a copy of the drawing state (that is the state that's
1574 // going to be overwritten by handleTransactionLocked()) outside of
1575 // mStateLock so that the side-effects of the State assignment
1576 // don't happen with mStateLock held (which can cause deadlocks).
1577 State drawingState(mDrawingState);
1578
Mathias Agopianca4d3602011-05-19 15:38:14 -07001579 Mutex::Autolock _l(mStateLock);
1580 const nsecs_t now = systemTime();
1581 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001582
Mathias Agopianca4d3602011-05-19 15:38:14 -07001583 // Here we're guaranteed that some transaction flags are set
1584 // so we can call handleTransactionLocked() unconditionally.
1585 // We call getTransactionFlags(), which will also clear the flags,
1586 // with mStateLock held to guarantee that mCurrentState won't change
1587 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001588
Mathias Agopiane57f2922012-08-09 16:29:12 -07001589 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001590 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001591
Mathias Agopianca4d3602011-05-19 15:38:14 -07001592 mLastTransactionTime = systemTime() - now;
1593 mDebugInTransaction = 0;
1594 invalidateHwcGeometry();
1595 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001596}
1597
Mathias Agopian87baae12012-07-31 12:38:26 -07001598void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001599{
Dan Stoza7dde5992015-05-22 09:51:44 -07001600 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001601 mCurrentState.traverseInZOrder([](Layer* layer) {
1602 layer->notifyAvailableFrames();
1603 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001605 /*
1606 * Traversal of the children
1607 * (perform the transaction for each of them if needed)
1608 */
1609
Mathias Agopian3559b072012-08-15 13:46:03 -07001610 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001611 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001612 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001613 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001614
1615 const uint32_t flags = layer->doTransaction(0);
1616 if (flags & Layer::eVisibleRegion)
1617 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001618 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001619 }
1620
1621 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001622 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001623 */
1624
Mathias Agopiane57f2922012-08-09 16:29:12 -07001625 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001626 // here we take advantage of Vector's copy-on-write semantics to
1627 // improve performance by skipping the transaction entirely when
1628 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001629 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1630 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001631 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001632 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001633 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001634 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001635
1636 // find the displays that were removed
1637 // (ie: in drawing state but not in current state)
1638 // also handle displays that changed
1639 // (ie: displays that are in both lists)
1640 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001641 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1642 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001643 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001644 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001645 // Call makeCurrent() on the primary display so we can
1646 // be sure that nothing associated with this display
1647 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001648 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001649 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001650 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1651 if (hw != NULL)
1652 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001653 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001654 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001655 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001656 } else {
1657 ALOGW("trying to remove the main display");
1658 }
1659 } else {
1660 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001661 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001662 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001663 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1664 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001665 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001666 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001667 // recreating the DisplayDevice, so we just remove it
1668 // from the drawing state, so that it get re-added
1669 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001670 sp<DisplayDevice> hw(getDisplayDevice(display));
1671 if (hw != NULL)
1672 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001673 mDisplays.removeItem(display);
1674 mDrawingState.displays.removeItemsAt(i);
1675 dc--; i--;
1676 // at this point we must loop to the next item
1677 continue;
1678 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001679
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001680 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001681 if (disp != NULL) {
1682 if (state.layerStack != draw[i].layerStack) {
1683 disp->setLayerStack(state.layerStack);
1684 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001685 if ((state.orientation != draw[i].orientation)
1686 || (state.viewport != draw[i].viewport)
1687 || (state.frame != draw[i].frame))
1688 {
1689 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001690 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001691 }
Michael Lentine47e45402014-07-18 15:34:25 -07001692 if (state.width != draw[i].width || state.height != draw[i].height) {
1693 disp->setDisplaySize(state.width, state.height);
1694 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001695 }
1696 }
1697 }
1698
1699 // find displays that were added
1700 // (ie: in current state but not in drawing state)
1701 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001702 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001703 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001704
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001705 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001706 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001707 sp<IGraphicBufferProducer> bqProducer;
1708 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001709 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1710 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001711
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001713 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001714 // Virtual displays without a surface are dormant:
1715 // they have external state (layer stack, projection,
1716 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001717 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001718
Dan Stoza8cf150a2016-08-02 10:27:31 -07001719 if (mUseHwcVirtualDisplays) {
1720 int width = 0;
1721 int status = state.surface->query(
1722 NATIVE_WINDOW_WIDTH, &width);
1723 ALOGE_IF(status != NO_ERROR,
1724 "Unable to query width (%d)", status);
1725 int height = 0;
1726 status = state.surface->query(
1727 NATIVE_WINDOW_HEIGHT, &height);
1728 ALOGE_IF(status != NO_ERROR,
1729 "Unable to query height (%d)", status);
1730 int intFormat = 0;
1731 status = state.surface->query(
1732 NATIVE_WINDOW_FORMAT, &intFormat);
1733 ALOGE_IF(status != NO_ERROR,
1734 "Unable to query format (%d)", status);
1735 auto format = static_cast<android_pixel_format_t>(
1736 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001737
Dan Stoza8cf150a2016-08-02 10:27:31 -07001738 mHwc->allocateVirtualDisplay(width, height, &format,
1739 &hwcId);
1740 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741
Dan Stoza5cf424b2016-05-20 14:02:39 -07001742 // TODO: Plumb requested format back up to consumer
1743
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 sp<VirtualDisplaySurface> vds =
1745 new VirtualDisplaySurface(*mHwc,
1746 hwcId, state.surface, bqProducer,
1747 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001748
1749 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001750 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001751 }
1752 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001753 ALOGE_IF(state.surface!=NULL,
1754 "adding a supported display, but rendering "
1755 "surface is provided (%p), ignoring it",
1756 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1758 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1759 dispSurface = new FramebufferSurface(*mHwc,
1760 DisplayDevice::DISPLAY_EXTERNAL,
1761 bqConsumer);
1762 producer = bqProducer;
1763 } else {
1764 ALOGE("Attempted to add non-external non-virtual"
1765 " display");
1766 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001767 }
1768
1769 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001770 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001771 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 state.type, hwcId, state.isSecure, display,
1773 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001774 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001775 hw->setLayerStack(state.layerStack);
1776 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001777 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001778 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001779 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001780 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001781 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001782 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001783 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001784 }
1785 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001787 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788
Mathias Agopian84300952012-11-21 16:02:13 -08001789 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1790 // The transform hint might have changed for some layers
1791 // (either because a display has changed, or because a layer
1792 // as changed).
1793 //
1794 // Walk through all the layers in currentLayers,
1795 // and update their transform hint.
1796 //
1797 // If a layer is visible only on a single display, then that
1798 // display is used to calculate the hint, otherwise we use the
1799 // default display.
1800 //
1801 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1802 // the hint is set before we acquire a buffer from the surface texture.
1803 //
1804 // NOTE: layer transactions have taken place already, so we use their
1805 // drawing state. However, SurfaceFlinger's own transaction has not
1806 // happened yet, so we must use the current state layer list
1807 // (soon to become the drawing state list).
1808 //
1809 sp<const DisplayDevice> disp;
1810 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001811 bool first = true;
1812 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001813 // NOTE: we rely on the fact that layers are sorted by
1814 // layerStack first (so we don't have to traverse the list
1815 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001816 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001817 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001818 currentlayerStack = layerStack;
1819 // figure out if this layerstack is mirrored
1820 // (more than one display) if so, pick the default display,
1821 // if not, pick the only display it's on.
1822 disp.clear();
1823 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1824 sp<const DisplayDevice> hw(mDisplays[dpy]);
1825 if (hw->getLayerStack() == currentlayerStack) {
1826 if (disp == NULL) {
1827 disp = hw;
1828 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001829 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001830 break;
1831 }
1832 }
1833 }
1834 }
Chet Haase91d25932013-04-11 15:24:55 -07001835 if (disp == NULL) {
1836 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1837 // redraw after transform hint changes. See bug 8508397.
1838
1839 // could be null when this layer is using a layerStack
1840 // that is not visible on any display. Also can occur at
1841 // screen off/on times.
1842 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001843 }
Chet Haase91d25932013-04-11 15:24:55 -07001844 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001845
1846 first = false;
1847 });
Mathias Agopian84300952012-11-21 16:02:13 -08001848 }
1849
1850
Mathias Agopian3559b072012-08-15 13:46:03 -07001851 /*
1852 * Perform our own transaction if needed
1853 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001854
1855 if (mLayersAdded) {
1856 mLayersAdded = false;
1857 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001858 mVisibleRegionsDirty = true;
1859 }
1860
1861 // some layers might have been removed, so
1862 // we need to update the regions they're exposing.
1863 if (mLayersRemoved) {
1864 mLayersRemoved = false;
1865 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001866 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001867 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001868 // this layer is not visible anymore
1869 // TODO: we could traverse the tree from front to back and
1870 // compute the actual visible region
1871 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001872 Region visibleReg;
1873 visibleReg.set(layer->computeScreenBounds());
1874 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001875 }
Robert Carr2047fae2016-11-28 14:09:09 -08001876 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001877 }
1878
1879 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001880
1881 updateCursorAsync();
1882}
1883
1884void SurfaceFlinger::updateCursorAsync()
1885{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1887 auto& displayDevice = mDisplays[displayId];
1888 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001889 continue;
1890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891
1892 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1893 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001894 }
1895 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001896}
1897
1898void SurfaceFlinger::commitTransaction()
1899{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001900 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001901 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001902 for (const auto& l : mLayersPendingRemoval) {
1903 recordBufferingStats(l->getName().string(),
1904 l->getOccupancyHistory(true));
1905 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001906 }
1907 mLayersPendingRemoval.clear();
1908 }
1909
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001910 // If this transaction is part of a window animation then the next frame
1911 // we composite should be considered an animation as well.
1912 mAnimCompositionPending = mAnimTransactionPending;
1913
Mathias Agopian4fec8732012-06-29 14:12:52 -07001914 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001915 mDrawingState.traverseInZOrder([](Layer* layer) {
1916 layer->commitChildList();
1917 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001918 mTransactionPending = false;
1919 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001920 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001921}
1922
Robert Carr2047fae2016-11-28 14:09:09 -08001923void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07001924 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925{
Mathias Agopian841cde52012-03-01 15:44:37 -08001926 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001928
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929 Region aboveOpaqueLayers;
1930 Region aboveCoveredLayers;
1931 Region dirty;
1932
Mathias Agopian87baae12012-07-31 12:38:26 -07001933 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934
Robert Carr2047fae2016-11-28 14:09:09 -08001935 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001936 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001937 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938
Jesse Hall01e29052013-02-19 16:13:35 -08001939 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001940 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001941 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07001942
Mathias Agopianab028732010-03-16 16:41:46 -07001943 /*
1944 * opaqueRegion: area of a surface that is fully opaque.
1945 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001946 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001947
1948 /*
1949 * visibleRegion: area of a surface that is visible on screen
1950 * and not fully transparent. This is essentially the layer's
1951 * footprint minus the opaque regions above it.
1952 * Areas covered by a translucent surface are considered visible.
1953 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001954 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001955
1956 /*
1957 * coveredRegion: area of a surface that is covered by all
1958 * visible regions above it (which includes the translucent areas).
1959 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001961
Jesse Halla8026d22012-09-25 13:25:04 -07001962 /*
1963 * transparentRegion: area of a surface that is hinted to be completely
1964 * transparent. This is only used to tell when the layer has no visible
1965 * non-transparent regions and can be removed from the layer list. It
1966 * does not affect the visibleRegion of this layer or any layers
1967 * beneath it. The hint may not be correct if apps don't respect the
1968 * SurfaceView restrictions (which, sadly, some don't).
1969 */
1970 Region transparentRegion;
1971
Mathias Agopianab028732010-03-16 16:41:46 -07001972
1973 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001974 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001975 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001976 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001978 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07001979 if (!visibleRegion.isEmpty()) {
1980 // Remove the transparent area from the visible region
1981 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001982 if (tr.preserveRects()) {
1983 // transform the transparent region
1984 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001985 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001986 // transformation too complex, can't do the
1987 // transparent region optimization.
1988 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001989 }
Mathias Agopianab028732010-03-16 16:41:46 -07001990 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001991
Mathias Agopianab028732010-03-16 16:41:46 -07001992 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001993 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001995 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1996 // the opaque region is the layer's footprint
1997 opaqueRegion = visibleRegion;
1998 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999 }
2000 }
2001
Mathias Agopianab028732010-03-16 16:41:46 -07002002 // Clip the covered region to the visible region
2003 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2004
2005 // Update aboveCoveredLayers for next (lower) layer
2006 aboveCoveredLayers.orSelf(visibleRegion);
2007
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002008 // subtract the opaque region covered by the layers above us
2009 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010
2011 // compute this layer's dirty region
2012 if (layer->contentDirty) {
2013 // we need to invalidate the whole region
2014 dirty = visibleRegion;
2015 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002017 layer->contentDirty = false;
2018 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002019 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002020 * the exposed region consists of two components:
2021 * 1) what's VISIBLE now and was COVERED before
2022 * 2) what's EXPOSED now less what was EXPOSED before
2023 *
2024 * note that (1) is conservative, we start with the whole
2025 * visible region but only keep what used to be covered by
2026 * something -- which mean it may have been exposed.
2027 *
2028 * (2) handles areas that were not covered by anything but got
2029 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002030 */
Mathias Agopianab028732010-03-16 16:41:46 -07002031 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002032 const Region oldVisibleRegion = layer->visibleRegion;
2033 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002034 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2035 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036 }
2037 dirty.subtractSelf(aboveOpaqueLayers);
2038
2039 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002040 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041
Mathias Agopianab028732010-03-16 16:41:46 -07002042 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002044
Jesse Halla8026d22012-09-25 13:25:04 -07002045 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046 layer->setVisibleRegion(visibleRegion);
2047 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002048 layer->setVisibleNonTransparentRegion(
2049 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002050 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051
Mathias Agopian87baae12012-07-31 12:38:26 -07002052 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002053}
2054
Mathias Agopian87baae12012-07-31 12:38:26 -07002055void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2056 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002057 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002058 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2059 if (hw->getLayerStack() == layerStack) {
2060 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002061 }
2062 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002063}
2064
Dan Stoza6b9454d2014-11-07 16:00:59 -08002065bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 ALOGV("handlePageFlip");
2068
Brian Andersond6927fb2016-07-23 23:37:30 -07002069 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070
Mathias Agopian4fec8732012-06-29 14:12:52 -07002071 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002072 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002073
2074 // Store the set of layers that need updates. This set must not change as
2075 // buffers are being latched, as this could result in a deadlock.
2076 // Example: Two producers share the same command stream and:
2077 // 1.) Layer 0 is latched
2078 // 2.) Layer 0 gets a new frame
2079 // 2.) Layer 1 gets a new frame
2080 // 3.) Layer 1 is latched.
2081 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2082 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002083 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002084 if (layer->hasQueuedFrame()) {
2085 frameQueued = true;
2086 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002087 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002088 } else {
2089 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002090 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002091 } else {
2092 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002093 }
Robert Carr2047fae2016-11-28 14:09:09 -08002094 });
2095
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002097 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002098 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002099 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002100 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002101
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002102 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002103
2104 // If we will need to wake up at some time in the future to deal with a
2105 // queued frame that shouldn't be displayed during this vsync period, wake
2106 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002108 signalLayerUpdate();
2109 }
2110
2111 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113}
2114
Mathias Agopianad456f92011-01-13 17:53:01 -08002115void SurfaceFlinger::invalidateHwcGeometry()
2116{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002118}
2119
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002120
Fabien Sanglard830b8472016-11-30 16:35:58 -08002121void SurfaceFlinger::doDisplayComposition(
2122 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002123 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124{
Dan Stoza71433162014-02-04 16:22:36 -08002125 // We only need to actually compose the display if:
2126 // 1) It is being handled by hardware composer, which may need this to
2127 // keep its virtual display state machine in sync, or
2128 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002129 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002130 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002132 return;
2133 }
2134
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 ALOGV("doDisplayComposition");
2136
Mathias Agopian87baae12012-07-31 12:38:26 -07002137 Region dirtyRegion(inDirtyRegion);
2138
Mathias Agopianb8a55602009-06-26 19:06:36 -07002139 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002140 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002141
Fabien Sanglard830b8472016-11-30 16:35:58 -08002142 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002143 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002144 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2145 // takes a rectangle, we must make sure to update that whole
2146 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002147 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002148 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002149 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002150 // We need to redraw the rectangle that will be updated
2151 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002152 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002153 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002154 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002155 } else {
2156 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002157 dirtyRegion.set(displayDevice->bounds());
2158 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159 }
2160 }
2161
Fabien Sanglard830b8472016-11-30 16:35:58 -08002162 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002164 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002165 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002166
2167 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002168 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169}
2170
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171bool SurfaceFlinger::doComposeSurfaces(
2172 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002173{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002175
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002177
2178 mat4 oldColorMatrix;
2179 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2180 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2181 if (applyColorMatrix) {
2182 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2183 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2184 }
2185
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2187 if (hasClientComposition) {
2188 ALOGV("hasClientComposition");
2189
2190 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002191 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002193 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2194 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2195 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2196 }
2197 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002198 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002199
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002200 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002201 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2202 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002203 // when using overlays, we assume a fully transparent framebuffer
2204 // NOTE: we could reduce how much we need to clear, for instance
2205 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002206 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002207 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002209 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002210 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002212
2213 // we remove the scissor part
2214 // we're left with the letterbox region
2215 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002217
2218 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002219 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002220
2221 // but limit it to the dirty region
2222 region.andSelf(dirty);
2223
Mathias Agopianb9494d52012-04-18 02:28:45 -07002224 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002225 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002226 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002227 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002228 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002229 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002230
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002232 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002233 // scissor on the main display. It should never be needed
2234 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 const Rect& bounds(displayDevice->getBounds());
2236 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002237 if (scissor != bounds) {
2238 // scissor doesn't match the screen's dimensions, so we
2239 // need to clear everything outside of it and enable
2240 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002241
Mathias Agopianf45c5102012-10-24 16:29:17 -07002242 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002243 const uint32_t height = displayDevice->getHeight();
2244 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002245 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002246 }
2247 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002248 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002249
Mathias Agopian85d751c2012-08-29 16:59:24 -07002250 /*
2251 * and then, render the layers targeted at the framebuffer
2252 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002253
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 ALOGV("Rendering client layers");
2255 const Transform& displayTransform = displayDevice->getTransform();
2256 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002257 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002258 bool firstLayer = true;
2259 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2260 const Region clip(dirty.intersect(
2261 displayTransform.transform(layer->visibleRegion)));
2262 ALOGV("Layer: %s", layer->getName().string());
2263 ALOGV(" Composition type: %s",
2264 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002265 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002266 switch (layer->getCompositionType(hwcId)) {
2267 case HWC2::Composition::Cursor:
2268 case HWC2::Composition::Device:
2269 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002270 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002271 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2272 layer->isOpaque(state) && (state.alpha == 1.0f)
2273 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002274 // never clear the very first layer since we're
2275 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002276 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002278 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002279 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002280 case HWC2::Composition::Client: {
2281 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002282 break;
2283 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002284 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002285 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002286 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 } else {
2288 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002289 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002291 }
2292 } else {
2293 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002295 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002297 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002299 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002300 }
2301 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002302
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002303 if (applyColorMatrix) {
2304 getRenderEngine().setupColorTransform(oldColorMatrix);
2305 }
2306
Mathias Agopianf45c5102012-10-24 16:29:17 -07002307 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002308 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002309 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310}
2311
Fabien Sanglard830b8472016-11-30 16:35:58 -08002312void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2313 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002314 RenderEngine& engine(getRenderEngine());
2315 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316}
2317
Dan Stoza7d89d062015-04-30 13:29:25 -07002318status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002319 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002320 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002321 const sp<Layer>& lbc,
2322 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002323{
Dan Stoza7d89d062015-04-30 13:29:25 -07002324 // add this layer to the current state list
2325 {
2326 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002327 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002328 return NO_MEMORY;
2329 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002330 if (parent == nullptr) {
2331 mCurrentState.layersSortedByZ.add(lbc);
2332 } else {
2333 parent->addChild(lbc);
2334 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002335 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002336 mLayersAdded = true;
2337 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002338 }
2339
Mathias Agopian96f08192010-06-02 23:28:45 -07002340 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002341 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002342
Dan Stoza7d89d062015-04-30 13:29:25 -07002343 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002344}
2345
Dan Stoza22851c32016-08-09 13:21:03 -07002346status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002348 sp<Layer> layer = weakLayer.promote();
2349 if (layer == nullptr) {
2350 // The layer has already been removed, carry on
2351 return NO_ERROR;
2352 }
2353
Robert Carr1f0a16a2016-10-24 16:27:39 -07002354 const auto& p = layer->getParent();
2355 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2356 mCurrentState.layersSortedByZ.remove(layer);
2357
2358 if (index < 0) {
2359 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2360 layer->getName().string(),
2361 (p != nullptr) ? p->getName().string() : "no-parent");
2362 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002363 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002364
2365 mLayersPendingRemoval.add(layer);
2366 mLayersRemoved = true;
2367 mNumLayers--;
2368 setTransactionFlags(eTransactionNeeded);
2369 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370}
2371
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002372uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002373 return android_atomic_release_load(&mTransactionFlags);
2374}
2375
Mathias Agopian3f844832013-08-07 21:24:32 -07002376uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2378}
2379
Mathias Agopian3f844832013-08-07 21:24:32 -07002380uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2382 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002383 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384 }
2385 return old;
2386}
2387
Mathias Agopian8b33f032012-07-24 20:43:54 -07002388void SurfaceFlinger::setTransactionState(
2389 const Vector<ComposerState>& state,
2390 const Vector<DisplayState>& displays,
2391 uint32_t flags)
2392{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002393 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002394 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002395 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002396
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002397 if (flags & eAnimation) {
2398 // For window updates that are part of an animation we must wait for
2399 // previous animation "frames" to be handled.
2400 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002401 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002402 if (CC_UNLIKELY(err != NO_ERROR)) {
2403 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002404 // caller after a few seconds.
2405 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2406 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002407 mAnimTransactionPending = false;
2408 break;
2409 }
2410 }
2411 }
2412
Mathias Agopiane57f2922012-08-09 16:29:12 -07002413 size_t count = displays.size();
2414 for (size_t i=0 ; i<count ; i++) {
2415 const DisplayState& s(displays[i]);
2416 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002417 }
2418
Mathias Agopiane57f2922012-08-09 16:29:12 -07002419 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002420 for (size_t i=0 ; i<count ; i++) {
2421 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002422 // Here we need to check that the interface we're given is indeed
2423 // one of our own. A malicious client could give us a NULL
2424 // IInterface, or one of its own or even one of our own but a
2425 // different type. All these situations would cause us to crash.
2426 //
2427 // NOTE: it would be better to use RTTI as we could directly check
2428 // that we have a Client*. however, RTTI is disabled in Android.
2429 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002430 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002431 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002432 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002433 sp<Client> client( static_cast<Client *>(s.client.get()) );
2434 transactionFlags |= setClientStateLocked(client, s.state);
2435 }
2436 }
2437 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002438 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002439
Robert Carr2a7dbb42016-05-24 11:41:28 -07002440 // If a synchronous transaction is explicitly requested without any changes,
2441 // force a transaction anyway. This can be used as a flush mechanism for
2442 // previous async transactions.
2443 if (transactionFlags == 0 && (flags & eSynchronous)) {
2444 transactionFlags = eTransactionNeeded;
2445 }
2446
Mathias Agopian386aa982011-11-07 21:58:03 -08002447 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002448 if (mInterceptor.isEnabled()) {
2449 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2450 }
Irvel468051e2016-06-13 16:44:44 -07002451
Mathias Agopian386aa982011-11-07 21:58:03 -08002452 // this triggers the transaction
2453 setTransactionFlags(transactionFlags);
2454
2455 // if this is a synchronous transaction, wait for it to take effect
2456 // before returning.
2457 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002458 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002459 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002460 if (flags & eAnimation) {
2461 mAnimTransactionPending = true;
2462 }
2463 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002464 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2465 if (CC_UNLIKELY(err != NO_ERROR)) {
2466 // just in case something goes wrong in SF, return to the
2467 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002468 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2469 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002470 break;
2471 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002472 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 }
2474}
2475
Mathias Agopiane57f2922012-08-09 16:29:12 -07002476uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2477{
Jesse Hall9a143922012-10-04 16:29:19 -07002478 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2479 if (dpyIdx < 0)
2480 return 0;
2481
Mathias Agopiane57f2922012-08-09 16:29:12 -07002482 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002483 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002484 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485 const uint32_t what = s.what;
2486 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002487 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002488 disp.surface = s.surface;
2489 flags |= eDisplayTransactionNeeded;
2490 }
2491 }
2492 if (what & DisplayState::eLayerStackChanged) {
2493 if (disp.layerStack != s.layerStack) {
2494 disp.layerStack = s.layerStack;
2495 flags |= eDisplayTransactionNeeded;
2496 }
2497 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002498 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 if (disp.orientation != s.orientation) {
2500 disp.orientation = s.orientation;
2501 flags |= eDisplayTransactionNeeded;
2502 }
2503 if (disp.frame != s.frame) {
2504 disp.frame = s.frame;
2505 flags |= eDisplayTransactionNeeded;
2506 }
2507 if (disp.viewport != s.viewport) {
2508 disp.viewport = s.viewport;
2509 flags |= eDisplayTransactionNeeded;
2510 }
2511 }
Michael Lentine47e45402014-07-18 15:34:25 -07002512 if (what & DisplayState::eDisplaySizeChanged) {
2513 if (disp.width != s.width) {
2514 disp.width = s.width;
2515 flags |= eDisplayTransactionNeeded;
2516 }
2517 if (disp.height != s.height) {
2518 disp.height = s.height;
2519 flags |= eDisplayTransactionNeeded;
2520 }
2521 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 }
2523 return flags;
2524}
2525
2526uint32_t SurfaceFlinger::setClientStateLocked(
2527 const sp<Client>& client,
2528 const layer_state_t& s)
2529{
2530 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002531 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002532 if (layer != 0) {
2533 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002534 bool geometryAppliesWithResize =
2535 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002536 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002537 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002538 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002539 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002540 }
2541 if (what & layer_state_t::eLayerChanged) {
2542 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002543 const auto& p = layer->getParent();
2544 if (p == nullptr) {
2545 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2546 if (layer->setLayer(s.z) && idx >= 0) {
2547 mCurrentState.layersSortedByZ.removeAt(idx);
2548 mCurrentState.layersSortedByZ.add(layer);
2549 // we need traversal (state changed)
2550 // AND transaction (list changed)
2551 flags |= eTransactionNeeded|eTraversalNeeded;
2552 }
2553 } else {
2554 if (p->setChildLayer(layer, s.z)) {
2555 flags |= eTransactionNeeded|eTraversalNeeded;
2556 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002557 }
2558 }
2559 if (what & layer_state_t::eSizeChanged) {
2560 if (layer->setSize(s.w, s.h)) {
2561 flags |= eTraversalNeeded;
2562 }
2563 }
2564 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 flags |= eTraversalNeeded;
2567 }
2568 if (what & layer_state_t::eMatrixChanged) {
2569 if (layer->setMatrix(s.matrix))
2570 flags |= eTraversalNeeded;
2571 }
2572 if (what & layer_state_t::eTransparentRegionChanged) {
2573 if (layer->setTransparentRegionHint(s.transparentRegion))
2574 flags |= eTraversalNeeded;
2575 }
Dan Stoza23116082015-06-18 14:58:39 -07002576 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002577 if (layer->setFlags(s.flags, s.mask))
2578 flags |= eTraversalNeeded;
2579 }
2580 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002581 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002582 flags |= eTraversalNeeded;
2583 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002584 if (what & layer_state_t::eFinalCropChanged) {
2585 if (layer->setFinalCrop(s.finalCrop))
2586 flags |= eTraversalNeeded;
2587 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002588 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002589 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590 // We only allow setting layer stacks for top level layers,
2591 // everything else inherits layer stack from its parent.
2592 if (layer->hasParent()) {
2593 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2594 layer->getName().string());
2595 } else if (idx < 0) {
2596 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2597 "that also does not appear in the top level layer list. Something"
2598 " has gone wrong.", layer->getName().string());
2599 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002600 mCurrentState.layersSortedByZ.removeAt(idx);
2601 mCurrentState.layersSortedByZ.add(layer);
2602 // we need traversal (state changed)
2603 // AND transaction (list changed)
2604 flags |= eTransactionNeeded|eTraversalNeeded;
2605 }
2606 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002607 if (what & layer_state_t::eDeferTransaction) {
2608 layer->deferTransactionUntil(s.handle, s.frameNumber);
2609 // We don't trigger a traversal here because if no other state is
2610 // changed, we don't want this to cause any more work
2611 }
Robert Carr1db73f62016-12-21 12:58:51 -08002612 if (what & layer_state_t::eReparentChildren) {
2613 if (layer->reparentChildren(s.reparentHandle)) {
2614 flags |= eTransactionNeeded|eTraversalNeeded;
2615 }
2616 }
Robert Carrc3574f72016-03-24 12:19:32 -07002617 if (what & layer_state_t::eOverrideScalingModeChanged) {
2618 layer->setOverrideScalingMode(s.overrideScalingMode);
2619 // We don't trigger a traversal here because if no other state is
2620 // changed, we don't want this to cause any more work
2621 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002622 }
2623 return flags;
2624}
2625
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002626status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002627 const String8& name,
2628 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002629 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002630 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2631 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002633 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002634 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002635 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002636 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002637 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002638
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002639 status_t result = NO_ERROR;
2640
2641 sp<Layer> layer;
2642
Mathias Agopian3165cc22012-08-08 19:42:09 -07002643 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2644 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002645 result = createNormalLayer(client,
2646 name, w, h, flags, format,
2647 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002649 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002650 result = createDimLayer(client,
2651 name, w, h, flags,
2652 handle, gbp, &layer);
2653 break;
2654 default:
2655 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 break;
2657 }
2658
Dan Stoza7d89d062015-04-30 13:29:25 -07002659 if (result != NO_ERROR) {
2660 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002662
Albert Chaulk479c60c2017-01-27 14:21:34 -05002663 layer->setInfo(windowType, ownerUid);
2664
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002666 if (result != NO_ERROR) {
2667 return result;
2668 }
Irvelffc9efc2016-07-27 15:16:37 -07002669 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002670
2671 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002672 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673}
2674
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002675status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2676 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2677 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678{
2679 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002680 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681 case PIXEL_FORMAT_TRANSPARENT:
2682 case PIXEL_FORMAT_TRANSLUCENT:
2683 format = PIXEL_FORMAT_RGBA_8888;
2684 break;
2685 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002686 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 break;
2688 }
2689
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002690 *outLayer = new Layer(this, client, name, w, h, flags);
2691 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2692 if (err == NO_ERROR) {
2693 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002694 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002696
2697 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2698 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699}
2700
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002701status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2702 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2703 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002705 *outLayer = new LayerDim(this, client, name, w, h, flags);
2706 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002707 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002708 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002709}
2710
Mathias Agopianac9fa422013-02-11 16:40:36 -08002711status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712{
Mathias Agopian67106042013-03-14 19:18:13 -07002713 // called by the window manager when it wants to remove a Layer
2714 status_t err = NO_ERROR;
2715 sp<Layer> l(client->getLayerUser(handle));
2716 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002717 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002718 err = removeLayer(l);
2719 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2720 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002721 }
2722 return err;
2723}
2724
Mathias Agopian13127d82013-03-05 17:47:11 -08002725status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002726{
Mathias Agopian67106042013-03-14 19:18:13 -07002727 // called by ~LayerCleaner() when all references to the IBinder (handle)
2728 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002729 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730}
2731
Mathias Agopianb60314a2012-04-10 22:09:54 -07002732// ---------------------------------------------------------------------------
2733
Andy McFadden13a082e2012-08-24 10:16:42 -07002734void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002735 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002736 Vector<ComposerState> state;
2737 Vector<DisplayState> displays;
2738 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002739 d.what = DisplayState::eDisplayProjectionChanged |
2740 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002741 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002742 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002743 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002744 d.frame.makeInvalid();
2745 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002746 d.width = 0;
2747 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002748 displays.add(d);
2749 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002750 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002751
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2753 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002754 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002755}
2756
2757void SurfaceFlinger::initializeDisplays() {
2758 class MessageScreenInitialized : public MessageBase {
2759 SurfaceFlinger* flinger;
2760 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002761 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002762 virtual bool handler() {
2763 flinger->onInitializeDisplays();
2764 return true;
2765 }
2766 };
2767 sp<MessageBase> msg = new MessageScreenInitialized(this);
2768 postMessageAsync(msg); // we may be called from main thread, use async message
2769}
2770
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002771void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2772 int mode) {
2773 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2774 this);
2775 int32_t type = hw->getDisplayType();
2776 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002777
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002778 if (mode == currentMode) {
2779 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002780 return;
2781 }
2782
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002783 hw->setPowerMode(mode);
2784 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2785 ALOGW("Trying to set power mode for virtual display");
2786 return;
2787 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002788
Irvelffc9efc2016-07-27 15:16:37 -07002789 if (mInterceptor.isEnabled()) {
2790 Mutex::Autolock _l(mStateLock);
2791 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2792 if (idx < 0) {
2793 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2794 return;
2795 }
2796 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2797 }
2798
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002799 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002800 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002801 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002802 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2803 // FIXME: eventthread only knows about the main display right now
2804 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002805 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002808 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002809 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002810 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002811
2812 struct sched_param param = {0};
2813 param.sched_priority = 1;
2814 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2815 ALOGW("Couldn't set SCHED_FIFO on display on");
2816 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002817 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002818 // Turn off the display
2819 struct sched_param param = {0};
2820 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2821 ALOGW("Couldn't set SCHED_OTHER on display off");
2822 }
2823
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002824 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002825 disableHardwareVsync(true); // also cancels any in-progress resync
2826
Mathias Agopiancde87a32012-09-13 14:09:01 -07002827 // FIXME: eventthread only knows about the main display right now
2828 mEventThread->onScreenReleased();
2829 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002830
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002831 getHwComposer().setPowerMode(type, mode);
2832 mVisibleRegionsDirty = true;
2833 // from this point on, SF will stop drawing on this display
2834 } else {
2835 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002836 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002837}
2838
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002839void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2840 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002841 SurfaceFlinger& mFlinger;
2842 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002843 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002844 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002845 MessageSetPowerMode(SurfaceFlinger& flinger,
2846 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2847 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002848 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002849 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002850 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002851 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002852 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002853 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002854 ALOGW("Attempt to set power mode = %d for virtual display",
2855 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002856 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002857 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002858 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002859 return true;
2860 }
2861 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002862 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002863 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002864}
2865
2866// ---------------------------------------------------------------------------
2867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2869{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002871
Mathias Agopianbd115332013-04-18 16:41:04 -07002872 IPCThreadState* ipc = IPCThreadState::self();
2873 const int pid = ipc->getCallingPid();
2874 const int uid = ipc->getCallingUid();
2875 if ((uid != AID_SHELL) &&
2876 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002877 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002878 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002880 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002881 // (this would indicate SF is stuck, but we want to be able to
2882 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002883 status_t err = mStateLock.timedLock(s2ns(1));
2884 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002885 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002886 result.appendFormat(
2887 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2888 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002889 }
2890
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002891 bool dumpAll = true;
2892 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002893 size_t numArgs = args.size();
2894 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002895 if ((index < numArgs) &&
2896 (args[index] == String16("--list"))) {
2897 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002898 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002899 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002900 }
2901
2902 if ((index < numArgs) &&
2903 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002904 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002905 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002906 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002907 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002908
2909 if ((index < numArgs) &&
2910 (args[index] == String16("--latency-clear"))) {
2911 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002912 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002913 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002914 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002915
2916 if ((index < numArgs) &&
2917 (args[index] == String16("--dispsync"))) {
2918 index++;
2919 mPrimaryDispSync.dump(result);
2920 dumpAll = false;
2921 }
Dan Stozab90cf072015-03-05 11:05:59 -08002922
2923 if ((index < numArgs) &&
2924 (args[index] == String16("--static-screen"))) {
2925 index++;
2926 dumpStaticScreenStats(result);
2927 dumpAll = false;
2928 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002929
2930 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002931 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002932 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002933 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002934 dumpAll = false;
2935 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002937
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002938 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002939 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002940 }
2941
Mathias Agopian9795c422009-08-26 16:36:26 -07002942 if (locked) {
2943 mStateLock.unlock();
2944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
2946 write(fd, result.string(), result.size());
2947 return NO_ERROR;
2948}
2949
Dan Stozac7014012014-02-14 15:03:43 -08002950void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2951 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002952{
Robert Carr2047fae2016-11-28 14:09:09 -08002953 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002954 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002955 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002956}
2957
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002958void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002959 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002960{
2961 String8 name;
2962 if (index < args.size()) {
2963 name = String8(args[index]);
2964 index++;
2965 }
2966
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2968 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002969 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002970
2971 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002972 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002973 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002974 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002975 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002976 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002977 }
Robert Carr2047fae2016-11-28 14:09:09 -08002978 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002979 }
2980}
2981
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002982void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002983 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002984{
2985 String8 name;
2986 if (index < args.size()) {
2987 name = String8(args[index]);
2988 index++;
2989 }
2990
Robert Carr2047fae2016-11-28 14:09:09 -08002991 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002992 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002993 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002994 }
Robert Carr2047fae2016-11-28 14:09:09 -08002995 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002996
Svetoslavd85084b2014-03-20 10:28:31 -07002997 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002998}
2999
Jamie Gennis6547ff42013-07-16 20:12:42 -07003000// This should only be called from the main thread. Otherwise it would need
3001// the lock and should use mCurrentState rather than mDrawingState.
3002void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003003 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003004 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003005 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003006
3007 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3008}
3009
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003010void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003011{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003012 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003013#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003014 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003015#endif
3016#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003017 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003018#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003019 if (isLayerTripleBufferingDisabled())
3020 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003021 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003022}
3023
Dan Stozab90cf072015-03-05 11:05:59 -08003024void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3025{
3026 result.appendFormat("Static screen stats:\n");
3027 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3028 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3029 float percent = 100.0f *
3030 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3031 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3032 b + 1, bucketTimeSec, percent);
3033 }
3034 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3035 float percent = 100.0f *
3036 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3037 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3038 NUM_BUCKETS - 1, bucketTimeSec, percent);
3039}
3040
Dan Stozae77c7662016-05-13 11:37:28 -07003041void SurfaceFlinger::recordBufferingStats(const char* layerName,
3042 std::vector<OccupancyTracker::Segment>&& history) {
3043 Mutex::Autolock lock(mBufferingStatsMutex);
3044 auto& stats = mBufferingStats[layerName];
3045 for (const auto& segment : history) {
3046 if (!segment.usedThirdBuffer) {
3047 stats.twoBufferTime += segment.totalTime;
3048 }
3049 if (segment.occupancyAverage < 1.0f) {
3050 stats.doubleBufferedTime += segment.totalTime;
3051 } else if (segment.occupancyAverage < 2.0f) {
3052 stats.tripleBufferedTime += segment.totalTime;
3053 }
3054 ++stats.numSegments;
3055 stats.totalTime += segment.totalTime;
3056 }
3057}
3058
Brian Andersond6927fb2016-07-23 23:37:30 -07003059void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3060 result.appendFormat("Layer frame timestamps:\n");
3061
3062 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3063 const size_t count = currentLayers.size();
3064 for (size_t i=0 ; i<count ; i++) {
3065 currentLayers[i]->dumpFrameEvents(result);
3066 }
3067}
3068
Dan Stozae77c7662016-05-13 11:37:28 -07003069void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3070 result.append("Buffering stats:\n");
3071 result.append(" [Layer name] <Active time> <Two buffer> "
3072 "<Double buffered> <Triple buffered>\n");
3073 Mutex::Autolock lock(mBufferingStatsMutex);
3074 typedef std::tuple<std::string, float, float, float> BufferTuple;
3075 std::map<float, BufferTuple, std::greater<float>> sorted;
3076 for (const auto& statsPair : mBufferingStats) {
3077 const char* name = statsPair.first.c_str();
3078 const BufferingStats& stats = statsPair.second;
3079 if (stats.numSegments == 0) {
3080 continue;
3081 }
3082 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3083 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3084 stats.totalTime;
3085 float doubleBufferRatio = static_cast<float>(
3086 stats.doubleBufferedTime) / stats.totalTime;
3087 float tripleBufferRatio = static_cast<float>(
3088 stats.tripleBufferedTime) / stats.totalTime;
3089 sorted.insert({activeTime, {name, twoBufferRatio,
3090 doubleBufferRatio, tripleBufferRatio}});
3091 }
3092 for (const auto& sortedPair : sorted) {
3093 float activeTime = sortedPair.first;
3094 const BufferTuple& values = sortedPair.second;
3095 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3096 std::get<0>(values).c_str(), activeTime,
3097 std::get<1>(values), std::get<2>(values),
3098 std::get<3>(values));
3099 }
3100 result.append("\n");
3101}
3102
3103
Mathias Agopian74d211a2013-04-22 16:55:35 +02003104void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3105 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003106{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003107 bool colorize = false;
3108 if (index < args.size()
3109 && (args[index] == String16("--color"))) {
3110 colorize = true;
3111 index++;
3112 }
3113
3114 Colorizer colorizer(colorize);
3115
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003116 // figure out if we're stuck somewhere
3117 const nsecs_t now = systemTime();
3118 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3119 const nsecs_t inTransaction(mDebugInTransaction);
3120 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3121 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3122
3123 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003124 * Dump library configuration.
3125 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003126
3127 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003128 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003129 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003130 appendSfConfigString(result);
3131 appendUiConfigString(result);
3132 appendGuiConfigString(result);
3133 result.append("\n");
3134
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003135 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003136 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003137 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003138 result.append(SyncFeatures::getInstance().toString());
3139 result.append("\n");
3140
Dan Stoza9e56aa02015-11-02 13:00:03 -08003141 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3142
Andy McFadden41d67d72014-04-25 16:58:34 -07003143 colorizer.bold(result);
3144 result.append("DispSync configuration: ");
3145 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003146 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3147 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3149 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003150 result.append("\n");
3151
Dan Stozab90cf072015-03-05 11:05:59 -08003152 // Dump static screen stats
3153 result.append("\n");
3154 dumpStaticScreenStats(result);
3155 result.append("\n");
3156
Dan Stozae77c7662016-05-13 11:37:28 -07003157 dumpBufferingStats(result);
3158
Andy McFadden4803b742012-09-24 19:07:20 -07003159 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003160 * Dump the visible layer list
3161 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003162 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003163 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003164 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003166 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003167 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003168
3169 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003170 * Dump Display state
3171 */
3172
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003173 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003174 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003175 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003176 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3177 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003178 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003179 }
3180
3181 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003182 * Dump SurfaceFlinger global state
3183 */
3184
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003185 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003187 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003188
Mathias Agopian888c8222012-08-04 21:10:38 -07003189 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003190 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003191
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003192 colorizer.bold(result);
3193 result.appendFormat("EGL implementation : %s\n",
3194 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3195 colorizer.reset(result);
3196 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003197 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003198
Mathias Agopian875d8e12013-06-07 15:35:48 -07003199 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003200
Mathias Agopian42977342012-08-05 00:40:46 -07003201 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003202 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3203 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003204 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003205 " last eglSwapBuffers() time: %f us\n"
3206 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003207 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003208 " refresh-rate : %f fps\n"
3209 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003210 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003211 " gpu_to_cpu_unsupported : %d\n"
3212 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003213 mLastSwapBufferTime/1000.0,
3214 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003215 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003216 1e9 / activeConfig->getVsyncPeriod(),
3217 activeConfig->getDpiX(),
3218 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003219 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003220
Mathias Agopian74d211a2013-04-22 16:55:35 +02003221 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003222 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003223
Mathias Agopian74d211a2013-04-22 16:55:35 +02003224 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003225 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003226
3227 /*
3228 * VSYNC state
3229 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003230 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003231 result.append("\n");
3232
3233 /*
3234 * HWC layer minidump
3235 */
3236 for (size_t d = 0; d < mDisplays.size(); d++) {
3237 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3238 int32_t hwcId = displayDevice->getHwcDisplayId();
3239 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3240 continue;
3241 }
3242
3243 result.appendFormat("Display %d HWC layers:\n", hwcId);
3244 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003246 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003247 });
Dan Stozae22aec72016-08-01 13:20:59 -07003248 result.append("\n");
3249 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003250
3251 /*
3252 * Dump HWComposer state
3253 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003254 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003255 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003256 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003257 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 result.appendFormat(" h/w composer %s\n",
3259 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003260 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003261
3262 /*
3263 * Dump gralloc state
3264 */
3265 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3266 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003267}
3268
Mathias Agopian13127d82013-03-05 17:47:11 -08003269const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003270SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003271 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003272 wp<IBinder> dpy;
3273 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3274 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3275 dpy = mDisplays.keyAt(i);
3276 break;
3277 }
3278 }
3279 if (dpy == NULL) {
3280 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3281 // Just use the primary display so we have something to return
3282 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3283 }
3284 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003285}
3286
Keun young Park63f165f2012-08-31 10:53:36 -07003287bool SurfaceFlinger::startDdmConnection()
3288{
3289 void* libddmconnection_dso =
3290 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3291 if (!libddmconnection_dso) {
3292 return false;
3293 }
3294 void (*DdmConnection_start)(const char* name);
3295 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003296 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003297 if (!DdmConnection_start) {
3298 dlclose(libddmconnection_dso);
3299 return false;
3300 }
3301 (*DdmConnection_start)(getServiceName());
3302 return true;
3303}
3304
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003305status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003306 switch (code) {
3307 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003308 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003310 case CLEAR_ANIMATION_FRAME_STATS:
3311 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003312 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003313 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314 {
3315 // codes that require permission check
3316 IPCThreadState* ipc = IPCThreadState::self();
3317 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003318 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003319 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003320 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003321 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003322 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003324 break;
3325 }
Robert Carr1db73f62016-12-21 12:58:51 -08003326 /*
3327 * Calling setTransactionState is safe, because you need to have been
3328 * granted a reference to Client* and Handle* to do anything with it.
3329 *
3330 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3331 */
3332 case SET_TRANSACTION_STATE:
3333 case CREATE_SCOPED_CONNECTION:
3334 {
3335 return OK;
3336 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003337 case CAPTURE_SCREEN:
3338 {
3339 // codes that require permission check
3340 IPCThreadState* ipc = IPCThreadState::self();
3341 const int pid = ipc->getCallingPid();
3342 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003343 if ((uid != AID_GRAPHICS) &&
3344 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003345 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003346 return PERMISSION_DENIED;
3347 }
3348 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 }
3350 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003351 return OK;
3352}
3353
3354status_t SurfaceFlinger::onTransact(
3355 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3356{
3357 status_t credentialCheck = CheckTransactCodeCredentials(code);
3358 if (credentialCheck != OK) {
3359 return credentialCheck;
3360 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3363 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003364 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003365 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003366 IPCThreadState* ipc = IPCThreadState::self();
3367 const int pid = ipc->getCallingPid();
3368 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003369 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003370 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371 return PERMISSION_DENIED;
3372 }
3373 int n;
3374 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003375 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003376 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003377 return NO_ERROR;
3378 case 1002: // SHOW_UPDATES
3379 n = data.readInt32();
3380 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003381 invalidateHwcGeometry();
3382 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003383 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003385 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003386 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003387 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003388 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003389 setTransactionFlags(
3390 eTransactionNeeded|
3391 eDisplayTransactionNeeded|
3392 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003393 return NO_ERROR;
3394 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003395 case 1006:{ // send empty update
3396 signalRefresh();
3397 return NO_ERROR;
3398 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003399 case 1008: // toggle use of hw composer
3400 n = data.readInt32();
3401 mDebugDisableHWC = n ? 1 : 0;
3402 invalidateHwcGeometry();
3403 repaintEverything();
3404 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003405 case 1009: // toggle use of transform hint
3406 n = data.readInt32();
3407 mDebugDisableTransformHint = n ? 1 : 0;
3408 invalidateHwcGeometry();
3409 repaintEverything();
3410 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003411 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003412 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 reply->writeInt32(0);
3414 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003415 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003416 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003417 return NO_ERROR;
3418 case 1013: {
3419 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003420 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3421 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003422 return NO_ERROR;
3423 }
3424 case 1014: {
3425 // daltonize
3426 n = data.readInt32();
3427 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003428 case 1:
3429 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3430 break;
3431 case 2:
3432 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3433 break;
3434 case 3:
3435 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3436 break;
3437 default:
3438 mDaltonizer.setType(ColorBlindnessType::None);
3439 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003440 }
3441 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003442 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003443 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003444 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003445 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003446 invalidateHwcGeometry();
3447 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003448 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003450 case 1015: {
3451 // apply a color matrix
3452 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003453 if (n) {
3454 // color matrix is sent as mat3 matrix followed by vec3
3455 // offset, then packed into a mat4 where the last row is
3456 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003457 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003458 for (size_t j = 0; j < 4; j++) {
3459 mColorMatrix[i][j] = data.readFloat();
3460 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003461 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003462 } else {
3463 mColorMatrix = mat4();
3464 }
3465 invalidateHwcGeometry();
3466 repaintEverything();
3467 return NO_ERROR;
3468 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003469 // This is an experimental interface
3470 // Needs to be shifted to proper binder interface when we productize
3471 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003472 n = data.readInt32();
3473 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003474 return NO_ERROR;
3475 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003476 case 1017: {
3477 n = data.readInt32();
3478 mForceFullDamage = static_cast<bool>(n);
3479 return NO_ERROR;
3480 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003481 case 1018: { // Modify Choreographer's phase offset
3482 n = data.readInt32();
3483 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3484 return NO_ERROR;
3485 }
3486 case 1019: { // Modify SurfaceFlinger's phase offset
3487 n = data.readInt32();
3488 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3489 return NO_ERROR;
3490 }
Irvel468051e2016-06-13 16:44:44 -07003491 case 1020: { // Layer updates interceptor
3492 n = data.readInt32();
3493 if (n) {
3494 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003495 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003496 }
3497 else{
3498 ALOGV("Interceptor disabled");
3499 mInterceptor.disable();
3500 }
3501 return NO_ERROR;
3502 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003503 case 1021: { // Disable HWC virtual displays
3504 n = data.readInt32();
3505 mUseHwcVirtualDisplays = !n;
3506 return NO_ERROR;
3507 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 }
3509 }
3510 return err;
3511}
3512
Mathias Agopian53331da2011-08-22 21:44:41 -07003513void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003514 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003515 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003516}
3517
Mathias Agopian59119e62010-10-11 12:37:43 -07003518// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003519// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003520// ---------------------------------------------------------------------------
3521
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003522/* The code below is here to handle b/8734824
3523 *
3524 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003525 * from the surfaceflinger thread to the calling binder thread, where they
3526 * are executed. This allows the calling thread in the calling process to be
3527 * reused and not depend on having "enough" binder threads to handle the
3528 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003529 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003530class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003531 /* Parts of GraphicProducerWrapper are run on two different threads,
3532 * communicating by sending messages via Looper but also by shared member
3533 * data. Coherence maintenance is subtle and in places implicit (ugh).
3534 *
3535 * Don't rely on Looper's sendMessage/handleMessage providing
3536 * release/acquire semantics for any data not actually in the Message.
3537 * Data going from surfaceflinger to binder threads needs to be
3538 * synchronized explicitly.
3539 *
3540 * Barrier open/wait do provide release/acquire semantics. This provides
3541 * implicit synchronization for data coming back from binder to
3542 * surfaceflinger threads.
3543 */
3544
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003545 sp<IGraphicBufferProducer> impl;
3546 sp<Looper> looper;
3547 status_t result;
3548 bool exitPending;
3549 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003550 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003551 uint32_t code;
3552 Parcel const* data;
3553 Parcel* reply;
3554
3555 enum {
3556 MSG_API_CALL,
3557 MSG_EXIT
3558 };
3559
3560 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003561 * Called on surfaceflinger thread. This is called by our "fake"
3562 * BpGraphicBufferProducer. We package the data and reply Parcel and
3563 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003564 */
3565 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003566 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003567 this->code = code;
3568 this->data = &data;
3569 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003570 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003571 // if we've exited, we run the message synchronously right here.
3572 // note (JH): as far as I can tell from looking at the code, this
3573 // never actually happens. if it does, i'm not sure if it happens
3574 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003575 handleMessage(Message(MSG_API_CALL));
3576 } else {
3577 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003578 // Prevent stores to this->{code, data, reply} from being
3579 // reordered later than the construction of Message.
3580 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003581 looper->sendMessage(this, Message(MSG_API_CALL));
3582 barrier.wait();
3583 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003584 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003585 }
3586
3587 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003588 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003589 * call the real BpGraphicBufferProducer.
3590 */
3591 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003592 int what = message.what;
3593 // Prevent reads below from happening before the read from Message
3594 atomic_thread_fence(memory_order_acquire);
3595 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003596 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003597 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003598 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003599 exitRequested = true;
3600 }
3601 }
3602
3603public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003604 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003605 : impl(impl),
3606 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003607 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003608 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003609 exitRequested(false),
3610 code(0),
3611 data(NULL),
3612 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003613 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003614
Jesse Hallb154c422014-07-13 12:47:02 -07003615 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003616 status_t waitForResponse() {
3617 do {
3618 looper->pollOnce(-1);
3619 } while (!exitRequested);
3620 return result;
3621 }
3622
Jesse Hallb154c422014-07-13 12:47:02 -07003623 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003624 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003625 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003626 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003627 // Ensure this->result is visible to the binder thread before it
3628 // handles the message.
3629 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003630 looper->sendMessage(this, Message(MSG_EXIT));
3631 }
3632};
3633
3634
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003635status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3636 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003637 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003638 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003639 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003640
3641 if (CC_UNLIKELY(display == 0))
3642 return BAD_VALUE;
3643
3644 if (CC_UNLIKELY(producer == 0))
3645 return BAD_VALUE;
3646
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003647 // if we have secure windows on this display, never allow the screen capture
3648 // unless the producer interface is local (i.e.: we can take a screenshot for
3649 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003650 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003651
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003652 // Convert to surfaceflinger's internal rotation type.
3653 Transform::orientation_flags rotationFlags;
3654 switch (rotation) {
3655 case ISurfaceComposer::eRotateNone:
3656 rotationFlags = Transform::ROT_0;
3657 break;
3658 case ISurfaceComposer::eRotate90:
3659 rotationFlags = Transform::ROT_90;
3660 break;
3661 case ISurfaceComposer::eRotate180:
3662 rotationFlags = Transform::ROT_180;
3663 break;
3664 case ISurfaceComposer::eRotate270:
3665 rotationFlags = Transform::ROT_270;
3666 break;
3667 default:
3668 rotationFlags = Transform::ROT_0;
3669 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3670 break;
3671 }
3672
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003673 class MessageCaptureScreen : public MessageBase {
3674 SurfaceFlinger* flinger;
3675 sp<IBinder> display;
3676 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003677 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003678 uint32_t reqWidth, reqHeight;
3679 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003680 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003681 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003682 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003683 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003684 public:
3685 MessageCaptureScreen(SurfaceFlinger* flinger,
3686 const sp<IBinder>& display,
3687 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003688 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003689 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003690 bool useIdentityTransform,
3691 Transform::orientation_flags rotation,
3692 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003693 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003694 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003695 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003696 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003697 rotation(rotation), result(PERMISSION_DENIED),
3698 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003699 {
3700 }
3701 status_t getResult() const {
3702 return result;
3703 }
3704 virtual bool handler() {
3705 Mutex::Autolock _l(flinger->mStateLock);
3706 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003707 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003708 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003709 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003710 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003711 return true;
3712 }
3713 };
3714
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003715 // this creates a "fake" BBinder which will serve as a "fake" remote
3716 // binder to receive the marshaled calls and forward them to the
3717 // real remote (a BpGraphicBufferProducer)
3718 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3719
3720 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3721 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003722 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003723 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003724 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003725 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003726
3727 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003728 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003729 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003730 }
3731 return res;
3732}
3733
Mathias Agopian180f10d2013-04-10 22:55:41 -07003734
3735void SurfaceFlinger::renderScreenImplLocked(
3736 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003737 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003738 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003739 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003740{
3741 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003742 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003743
3744 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003745 const int32_t hw_w = hw->getWidth();
3746 const int32_t hw_h = hw->getHeight();
3747 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003748 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003749
Dan Stozac1879002014-05-22 15:59:05 -07003750 // if a default or invalid sourceCrop is passed in, set reasonable values
3751 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3752 !sourceCrop.isValid()) {
3753 sourceCrop.setLeftTop(Point(0, 0));
3754 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3755 }
3756
3757 // ensure that sourceCrop is inside screen
3758 if (sourceCrop.left < 0) {
3759 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3760 }
Dan Stozabe31f442014-06-11 11:20:54 -07003761 if (sourceCrop.right > hw_w) {
3762 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003763 }
3764 if (sourceCrop.top < 0) {
3765 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3766 }
Dan Stozabe31f442014-06-11 11:20:54 -07003767 if (sourceCrop.bottom > hw_h) {
3768 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003769 }
3770
Mathias Agopian180f10d2013-04-10 22:55:41 -07003771 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003772 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003773
3774 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003775 engine.setViewportAndProjection(
3776 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003777 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003778
3779 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003780 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003781
Robert Carr1f0a16a2016-10-24 16:27:39 -07003782 // We loop through the first level of layers without traversing,
3783 // as we need to interpret min/max layer Z in the top level Z space.
3784 for (const auto& layer : mDrawingState.layersSortedByZ) {
3785 if (layer->getLayerStack() != hw->getLayerStack()) {
3786 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003788 const Layer::State& state(layer->getDrawingState());
3789 if (state.z < minLayerZ || state.z > maxLayerZ) {
3790 continue;
3791 }
3792 layer->traverseInZOrder([&](Layer* layer) {
3793 if (!layer->isVisible()) {
3794 return;
3795 }
3796 if (filtering) layer->setFiltering(true);
3797 layer->draw(hw, useIdentityTransform);
3798 if (filtering) layer->setFiltering(false);
3799 });
3800 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003801
Mathias Agopian931bda12013-08-28 18:11:46 -07003802 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003803}
3804
3805
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003806status_t SurfaceFlinger::captureScreenImplLocked(
3807 const sp<const DisplayDevice>& hw,
3808 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003809 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003810 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003811 bool useIdentityTransform, Transform::orientation_flags rotation,
3812 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003813{
3814 ATRACE_CALL();
3815
Mathias Agopian180f10d2013-04-10 22:55:41 -07003816 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003817 uint32_t hw_w = hw->getWidth();
3818 uint32_t hw_h = hw->getHeight();
3819
3820 if (rotation & Transform::ROT_90) {
3821 std::swap(hw_w, hw_h);
3822 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003823
Mathias Agopian180f10d2013-04-10 22:55:41 -07003824 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3825 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3826 reqWidth, reqHeight, hw_w, hw_h);
3827 return BAD_VALUE;
3828 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003829
Mathias Agopian180f10d2013-04-10 22:55:41 -07003830 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3831 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3832
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003833 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003834 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003835 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003836 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3837 (state.z < minLayerZ || state.z > maxLayerZ)) {
3838 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003839 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003840 layer->traverseInZOrder([&](Layer *layer) {
3841 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3842 layer->isSecure());
3843 });
3844 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003845
3846 if (!isLocalScreenshot && secureLayerIsVisible) {
3847 ALOGW("FB is protected: PERMISSION_DENIED");
3848 return PERMISSION_DENIED;
3849 }
3850
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003851 // create a surface (because we're a producer, and we need to
3852 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003853 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003854
3855 // Put the screenshot Surface into async mode so that
3856 // Layer::headFenceHasSignaled will always return true and we'll latch the
3857 // first buffer regardless of whether or not its acquire fence has
3858 // signaled. This is needed to avoid a race condition in the rotation
3859 // animation. See b/30209608
3860 sur->setAsyncMode(true);
3861
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003862 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003863
Michael Lentine5a16a622015-05-21 13:48:24 -07003864 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3865 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003866 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3867 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003868
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003869 int err = 0;
3870 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003871 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003872 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3873 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003874
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003875 if (err == NO_ERROR) {
3876 ANativeWindowBuffer* buffer;
3877 /* TODO: Once we have the sync framework everywhere this can use
3878 * server-side waits on the fence that dequeueBuffer returns.
3879 */
3880 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3881 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003882 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003883 // create an EGLImage from the buffer so we can later
3884 // turn it into a texture
3885 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3886 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3887 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003888 // this binds the given EGLImage as a framebuffer for the
3889 // duration of this scope.
3890 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3891 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003892 // this will in fact render into our dequeued buffer
3893 // via an FBO, which means we didn't have to create
3894 // an EGLSurface and therefore we're not
3895 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003896 renderScreenImplLocked(
3897 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3898 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003899
Riley Andrews86639902014-08-15 12:27:24 -07003900 // Attempt to create a sync khr object that can produce a sync point. If that
3901 // isn't available, create a non-dupable sync object in the fallback path and
3902 // wait on it directly.
3903 EGLSyncKHR sync;
3904 if (!DEBUG_SCREENSHOTS) {
3905 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003906 // native fence fd will not be populated until flush() is done.
3907 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003908 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003909 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003910 }
Riley Andrews86639902014-08-15 12:27:24 -07003911 if (sync != EGL_NO_SYNC_KHR) {
3912 // get the sync fd
3913 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3914 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3915 ALOGW("captureScreen: failed to dup sync khr object");
3916 syncFd = -1;
3917 }
3918 eglDestroySyncKHR(mEGLDisplay, sync);
3919 } else {
3920 // fallback path
3921 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3922 if (sync != EGL_NO_SYNC_KHR) {
3923 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3924 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3925 EGLint eglErr = eglGetError();
3926 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3927 ALOGW("captureScreen: fence wait timed out");
3928 } else {
3929 ALOGW_IF(eglErr != EGL_SUCCESS,
3930 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3931 }
3932 eglDestroySyncKHR(mEGLDisplay, sync);
3933 } else {
3934 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3935 }
3936 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003937 if (DEBUG_SCREENSHOTS) {
3938 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3939 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3940 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3941 hw, minLayerZ, maxLayerZ);
3942 delete [] pixels;
3943 }
3944
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003945 } else {
3946 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3947 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003948 window->cancelBuffer(window, buffer, syncFd);
3949 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003950 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003951 // destroy our image
3952 eglDestroyImageKHR(mEGLDisplay, image);
3953 } else {
3954 result = BAD_VALUE;
3955 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003956 if (buffer) {
3957 // queueBuffer takes ownership of syncFd
3958 result = window->queueBuffer(window, buffer, syncFd);
3959 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003960 }
3961 } else {
3962 result = BAD_VALUE;
3963 }
3964 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3965 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003966
Mathias Agopian74c40c02010-09-29 13:02:36 -07003967 return result;
3968}
3969
Mathias Agopiand5556842013-09-19 17:08:37 -07003970void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003971 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003972 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003973 for (size_t y=0 ; y<h ; y++) {
3974 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3975 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003976 if (p[x] != 0xFF000000) return;
3977 }
3978 }
3979 ALOGE("*** we just took a black screenshot ***\n"
3980 "requested minz=%d, maxz=%d, layerStack=%d",
3981 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003982
Robert Carr2047fae2016-11-28 14:09:09 -08003983 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003984 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003985 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003986 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3987 state.z <= maxLayerZ) {
3988 layer->traverseInZOrder([&](Layer* layer) {
3989 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3990 layer->isVisible() ? '+' : '-',
3991 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07003992 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003993 i++;
3994 });
3995 }
3996 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07003997 }
3998}
3999
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004000// ---------------------------------------------------------------------------
4001
Robert Carr2047fae2016-11-28 14:09:09 -08004002void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4003 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004004}
4005
Robert Carr2047fae2016-11-28 14:09:09 -08004006void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4007 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004008}
4009
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004011
4012
4013#if defined(__gl_h_)
4014#error "don't include gl/gl.h in this file"
4015#endif
4016
4017#if defined(__gl2_h_)
4018#error "don't include gl2/gl2.h in this file"
4019#endif