blob: 9e25e0739d370d99d11f4fdacd4837650375e8c2 [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");
216 mLayerTripleBufferingDisabled = !atoi(value);
217 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218}
219
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220void SurfaceFlinger::onFirstRef()
221{
222 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800223}
224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225SurfaceFlinger::~SurfaceFlinger()
226{
Mathias Agopiana4912602012-07-12 14:25:33 -0700227 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
228 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
229 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230}
231
Dan Stozac7014012014-02-14 15:03:43 -0800232void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233{
234 // the window manager died on us. prepare its eulogy.
235
Andy McFadden13a082e2012-08-24 10:16:42 -0700236 // restore initial conditions (default device unblank, etc)
237 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238
239 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700240 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241}
242
Robert Carr1db73f62016-12-21 12:58:51 -0800243static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700244 status_t err = client->initCheck();
245 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800246 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 }
Robert Carr1db73f62016-12-21 12:58:51 -0800248 return nullptr;
249}
250
251sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
252 return initClient(new Client(this));
253}
254
255sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
256 const sp<IGraphicBufferProducer>& gbp) {
257 if (authenticateSurfaceTexture(gbp) == false) {
258 return nullptr;
259 }
260 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
261 if (layer == nullptr) {
262 return nullptr;
263 }
264
265 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266}
267
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700268sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
269 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700270{
271 class DisplayToken : public BBinder {
272 sp<SurfaceFlinger> flinger;
273 virtual ~DisplayToken() {
274 // no more references, this display must be terminated
275 Mutex::Autolock _l(flinger->mStateLock);
276 flinger->mCurrentState.displays.removeItem(this);
277 flinger->setTransactionFlags(eDisplayTransactionNeeded);
278 }
279 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700280 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281 : flinger(flinger) {
282 }
283 };
284
285 sp<BBinder> token = new DisplayToken(this);
286
287 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700288 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700289 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700291 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700292 return token;
293}
294
Jesse Hall6c913be2013-08-08 12:15:49 -0700295void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
296 Mutex::Autolock _l(mStateLock);
297
298 ssize_t idx = mCurrentState.displays.indexOfKey(display);
299 if (idx < 0) {
300 ALOGW("destroyDisplay: invalid display token");
301 return;
302 }
303
304 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
305 if (!info.isVirtualDisplay()) {
306 ALOGE("destroyDisplay called for non-virtual display");
307 return;
308 }
Irvelffc9efc2016-07-27 15:16:37 -0700309 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700310 mCurrentState.displays.removeItemsAt(idx);
311 setTransactionFlags(eDisplayTransactionNeeded);
312}
313
Jesse Hall692c7232012-11-08 15:41:56 -0800314void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800315 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800316 ALOGW_IF(mBuiltinDisplays[type],
317 "Overwriting display token for display type %d", type);
318 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800319 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700320 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800321 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700322 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800323}
324
Mathias Agopiane57f2922012-08-09 16:29:12 -0700325sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700326 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700327 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
328 return NULL;
329 }
Jesse Hall692c7232012-11-08 15:41:56 -0800330 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700331}
332
Jamie Gennis9a78c902011-01-12 18:30:40 -0800333sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
334{
335 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
336 return gba;
337}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339void SurfaceFlinger::bootFinished()
340{
Wei Wangb254fa32017-01-31 17:43:23 -0800341 if (mStartBootAnimThread->join() != NO_ERROR) {
342 ALOGE("Join StartBootAnimThread failed!");
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344 const nsecs_t now = systemTime();
345 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000346 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700347 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700348
349 // wait patiently for the window manager death
350 const String16 name("window");
351 sp<IBinder> window(defaultServiceManager()->getService(name));
352 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700353 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700354 }
355
356 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700357 // formerly we would just kill the process, but we now ask it to exit so it
358 // can choose where to stop the animation.
359 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700360
361 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
362 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
363 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364}
365
Mathias Agopian3f844832013-08-07 21:24:32 -0700366void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700367 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700368 RenderEngine& engine;
369 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700370 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700371 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
372 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700373 }
374 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376 return true;
377 }
378 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700379 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380}
381
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700382class DispSyncSource : public VSyncSource, private DispSync::Callback {
383public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700384 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000385 const char* name) :
386 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700387 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700388 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000389 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
390 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700391 mDispSync(dispSync),
392 mCallbackMutex(),
393 mCallback(),
394 mVsyncMutex(),
395 mPhaseOffset(phaseOffset),
396 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700397
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398 virtual ~DispSyncSource() {}
399
400 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700401 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700402 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error registering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700409 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 } else {
411 status_t err = mDispSync->removeEventListener(
412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error unregistering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700417 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 }
421
422 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 mCallback = callback;
425 }
426
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700427 virtual void setPhaseOffset(nsecs_t phaseOffset) {
428 Mutex::Autolock lock(mVsyncMutex);
429
430 // Normalize phaseOffset to [0, period)
431 auto period = mDispSync->getPeriod();
432 phaseOffset %= period;
433 if (phaseOffset < 0) {
434 // If we're here, then phaseOffset is in (-period, 0). After this
435 // operation, it will be in (0, period)
436 phaseOffset += period;
437 }
438 mPhaseOffset = phaseOffset;
439
440 // If we're not enabled, we don't need to mess with the listeners
441 if (!mEnabled) {
442 return;
443 }
444
445 // Remove the listener with the old offset
446 status_t err = mDispSync->removeEventListener(
447 static_cast<DispSync::Callback*>(this));
448 if (err != NO_ERROR) {
449 ALOGE("error unregistering vsync callback: %s (%d)",
450 strerror(-err), err);
451 }
452
453 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000454 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error registering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
460 }
461
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462private:
463 virtual void onDispSyncEvent(nsecs_t when) {
464 sp<VSyncSource::Callback> callback;
465 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 callback = mCallback;
468
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700469 if (mTraceVsync) {
470 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700471 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700472 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 }
474
475 if (callback != NULL) {
476 callback->onVSyncEvent(when);
477 }
478 }
479
Tim Murray4a4e4a22016-04-19 16:29:23 +0000480 const char* const mName;
481
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 int mValue;
483
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 const String8 mVsyncOnLabel;
486 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700487
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489
490 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700492
493 Mutex mVsyncMutex; // Protects the following
494 nsecs_t mPhaseOffset;
495 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496};
497
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700498class InjectVSyncSource : public VSyncSource {
499public:
500 InjectVSyncSource() {}
501
502 virtual ~InjectVSyncSource() {}
503
504 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
505 std::lock_guard<std::mutex> lock(mCallbackMutex);
506 mCallback = callback;
507 }
508
509 virtual void onInjectSyncEvent(nsecs_t when) {
510 std::lock_guard<std::mutex> lock(mCallbackMutex);
511 mCallback->onVSyncEvent(when);
512 }
513
514 virtual void setVSyncEnabled(bool) {}
515 virtual void setPhaseOffset(nsecs_t) {}
516
517private:
518 std::mutex mCallbackMutex; // Protects the following
519 sp<VSyncSource::Callback> mCallback;
520};
521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700523 ALOGI( "SurfaceFlinger's main thread ready to run. "
524 "Initializing graphics H/W...");
525
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900526 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
527
Dan Stoza9e56aa02015-11-02 13:00:03 -0800528 { // Autolock scope
529 Mutex::Autolock _l(mStateLock);
530
531 // initialize EGL for the default display
532 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
533 eglInitialize(mEGLDisplay, NULL, NULL);
534
535 // start the EventThread
536 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
537 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700538 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800539 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
540 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700541 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 mEventQueue.setEventThread(mSFEventThread);
543
Tim Murrayacff43d2016-07-29 13:57:24 -0700544 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700545 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700546 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700547 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
548 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
549 }
550
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 // Get a RenderEngine for the given display / config (can't fail)
552 mRenderEngine = RenderEngine::create(mEGLDisplay,
553 HAL_PIXEL_FORMAT_RGBA_8888);
554 }
555
556 // Drop the state lock while we initialize the hardware composer. We drop
557 // the lock because on creation, it will call back into SurfaceFlinger to
558 // initialize the primary display.
559 mHwc = new HWComposer(this);
560 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
561
Jesse Hall692c7232012-11-08 15:41:56 -0800562 Mutex::Autolock _l(mStateLock);
563
Mathias Agopian875d8e12013-06-07 15:35:48 -0700564 // retrieve the EGL context that was selected/created
565 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700566
Mathias Agopianda27af92012-09-13 18:17:13 -0700567 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
568 "couldn't create EGLContext");
569
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 // make the GLContext current so that we can create textures when creating
571 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700572 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
573
Jamie Gennisd1700752013-10-14 12:22:52 -0700574 mEventControlThread = new EventControlThread(this);
575 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
576
Mathias Agopian92a979a2012-08-02 18:32:23 -0700577 // initialize our drawing state
578 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700579
Andy McFadden13a082e2012-08-24 10:16:42 -0700580 // set initial conditions (e.g. unblank default device)
581 initializeDisplays();
582
Dan Stoza4e637772016-07-28 13:31:51 -0700583 mRenderEngine->primeCache();
584
Wei Wangb254fa32017-01-31 17:43:23 -0800585 mStartBootAnimThread = new StartBootAnimThread();
586 if (mStartBootAnimThread->Start() != NO_ERROR) {
587 ALOGE("Run StartBootAnimThread failed!");
588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700591}
592
Mathias Agopiana67e4182012-06-19 17:26:12 -0700593void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800594 // Start boot animation service by setting a property mailbox
595 // if property setting thread is already running, Start() will be just a NOP
596 mStartBootAnimThread->Start();
597 // Wait until property was set
598 if (mStartBootAnimThread->join() != NO_ERROR) {
599 ALOGE("Join StartBootAnimThread failed!");
600 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700601}
602
Mathias Agopian875d8e12013-06-07 15:35:48 -0700603size_t SurfaceFlinger::getMaxTextureSize() const {
604 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700605}
606
Mathias Agopian875d8e12013-06-07 15:35:48 -0700607size_t SurfaceFlinger::getMaxViewportDims() const {
608 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700609}
610
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800611// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800612
Jamie Gennis582270d2011-08-17 18:19:00 -0700613bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800614 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800615 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800616 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700617 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800618}
619
Brian Anderson069b3652016-07-22 10:32:47 -0700620status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700621 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700622 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700623 FrameEvent::REQUESTED_PRESENT,
624 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700625 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700626 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700627 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700628 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700629 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700630 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700631 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700632 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700633 };
634 return NO_ERROR;
635}
636
Dan Stoza7f7da322014-05-02 15:26:25 -0700637status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
638 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700639 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700640 return BAD_VALUE;
641 }
642
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500643 if (!display.get())
644 return NAME_NOT_FOUND;
645
Jesse Hall692c7232012-11-08 15:41:56 -0800646 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700647 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800648 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700649 type = i;
650 break;
651 }
652 }
653
654 if (type < 0) {
655 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700656 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700657
Mathias Agopian8b736f12012-08-13 17:54:26 -0700658 // TODO: Not sure if display density should handled by SF any longer
659 class Density {
660 static int getDensityFromProperty(char const* propName) {
661 char property[PROPERTY_VALUE_MAX];
662 int density = 0;
663 if (property_get(propName, property, NULL) > 0) {
664 density = atoi(property);
665 }
666 return density;
667 }
668 public:
669 static int getEmuDensity() {
670 return getDensityFromProperty("qemu.sf.lcd_density"); }
671 static int getBuildDensity() {
672 return getDensityFromProperty("ro.sf.lcd_density"); }
673 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700674
Dan Stoza7f7da322014-05-02 15:26:25 -0700675 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700676
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700678 DisplayInfo info = DisplayInfo();
679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 float xdpi = hwConfig->getDpiX();
681 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700682
683 if (type == DisplayDevice::DISPLAY_PRIMARY) {
684 // The density of the device is provided by a build property
685 float density = Density::getBuildDensity() / 160.0f;
686 if (density == 0) {
687 // the build doesn't provide a density -- this is wrong!
688 // use xdpi instead
689 ALOGE("ro.sf.lcd_density must be defined as a build property");
690 density = xdpi / 160.0f;
691 }
692 if (Density::getEmuDensity()) {
693 // if "qemu.sf.lcd_density" is specified, it overrides everything
694 xdpi = ydpi = density = Density::getEmuDensity();
695 density /= 160.0f;
696 }
697 info.density = density;
698
699 // TODO: this needs to go away (currently needed only by webkit)
700 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
701 info.orientation = hw->getOrientation();
702 } else {
703 // TODO: where should this value come from?
704 static const int TV_DENSITY = 213;
705 info.density = TV_DENSITY / 160.0f;
706 info.orientation = 0;
707 }
708
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 info.w = hwConfig->getWidth();
710 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700711 info.xdpi = xdpi;
712 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900714 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800715
Andy McFadden91b2ca82014-06-13 14:04:23 -0700716 // This is how far in advance a buffer must be queued for
717 // presentation at a given time. If you want a buffer to appear
718 // on the screen at time N, you must submit the buffer before
719 // (N - presentationDeadline).
720 //
721 // Normally it's one full refresh period (to give SF a chance to
722 // latch the buffer), but this can be reduced by configuring a
723 // DispSync offset. Any additional delays introduced by the hardware
724 // composer or panel must be accounted for here.
725 //
726 // We add an additional 1ms to allow for processing time and
727 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 info.presentationDeadline = hwConfig->getVsyncPeriod() -
729 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700730
731 // All non-virtual displays are currently considered secure.
732 info.secure = true;
733
Michael Wright28f24d02016-07-12 13:30:53 -0700734 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700735 }
736
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 return NO_ERROR;
738}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700739
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800740status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700741 DisplayStatInfo* stats) {
742 if (stats == NULL) {
743 return BAD_VALUE;
744 }
745
746 // FIXME for now we always return stats for the primary display
747 memset(stats, 0, sizeof(*stats));
748 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
749 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
750 return NO_ERROR;
751}
752
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700753int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800754 if (display == NULL) {
755 ALOGE("%s : display is NULL", __func__);
756 return BAD_VALUE;
757 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700758 sp<DisplayDevice> device(getDisplayDevice(display));
759 if (device != NULL) {
760 return device->getActiveConfig();
761 }
762 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700763}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700764
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700765void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
766 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
767 this);
768 int32_t type = hw->getDisplayType();
769 int currentMode = hw->getActiveConfig();
770
771 if (mode == currentMode) {
772 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
773 return;
774 }
775
776 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
777 ALOGW("Trying to set config for virtual display");
778 return;
779 }
780
781 hw->setActiveConfig(mode);
782 getHwComposer().setActiveConfig(type, mode);
783}
784
785status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
786 class MessageSetActiveConfig: public MessageBase {
787 SurfaceFlinger& mFlinger;
788 sp<IBinder> mDisplay;
789 int mMode;
790 public:
791 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
792 int mode) :
793 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
794 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700795 Vector<DisplayInfo> configs;
796 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700797 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700798 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700799 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700800 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700801 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700802 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
803 if (hw == NULL) {
804 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700805 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700806 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
807 ALOGW("Attempt to set active config = %d for virtual display",
808 mMode);
809 } else {
810 mFlinger.setActiveConfigInternal(hw, mMode);
811 }
812 return true;
813 }
814 };
815 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
816 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700817 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818}
Michael Wright28f24d02016-07-12 13:30:53 -0700819status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
820 Vector<android_color_mode_t>* outColorModes) {
821 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
822 return BAD_VALUE;
823 }
824
825 if (!display.get()) {
826 return NAME_NOT_FOUND;
827 }
828
829 int32_t type = NAME_NOT_FOUND;
830 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
831 if (display == mBuiltinDisplays[i]) {
832 type = i;
833 break;
834 }
835 }
836
837 if (type < 0) {
838 return type;
839 }
840
841 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
842 outColorModes->clear();
843 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
844
845 return NO_ERROR;
846}
847
848android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
849 sp<DisplayDevice> device(getDisplayDevice(display));
850 if (device != nullptr) {
851 return device->getActiveColorMode();
852 }
853 return static_cast<android_color_mode_t>(BAD_VALUE);
854}
855
856void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
857 android_color_mode_t mode) {
858 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
859 this);
860 int32_t type = hw->getDisplayType();
861 android_color_mode_t currentMode = hw->getActiveColorMode();
862
863 if (mode == currentMode) {
864 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
865 return;
866 }
867
868 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
869 ALOGW("Trying to set config for virtual display");
870 return;
871 }
872
873 hw->setActiveColorMode(mode);
874 getHwComposer().setActiveColorMode(type, mode);
875}
876
877
878status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
879 android_color_mode_t colorMode) {
880 class MessageSetActiveColorMode: public MessageBase {
881 SurfaceFlinger& mFlinger;
882 sp<IBinder> mDisplay;
883 android_color_mode_t mMode;
884 public:
885 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
886 android_color_mode_t mode) :
887 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
888 virtual bool handler() {
889 Vector<android_color_mode_t> modes;
890 mFlinger.getDisplayColorModes(mDisplay, &modes);
891 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
892 if (mMode < 0 || !exists) {
893 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
894 mDisplay.get());
895 return true;
896 }
897 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
898 if (hw == nullptr) {
899 ALOGE("Attempt to set active color mode = %d for null display %p",
900 mMode, mDisplay.get());
901 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
902 ALOGW("Attempt to set active color mode= %d for virtual display",
903 mMode);
904 } else {
905 mFlinger.setActiveColorModeInternal(hw, mMode);
906 }
907 return true;
908 }
909 };
910 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
911 postMessageSync(msg);
912 return NO_ERROR;
913}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700914
Svetoslavd85084b2014-03-20 10:28:31 -0700915status_t SurfaceFlinger::clearAnimationFrameStats() {
916 Mutex::Autolock _l(mStateLock);
917 mAnimFrameTracker.clearStats();
918 return NO_ERROR;
919}
920
921status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
922 Mutex::Autolock _l(mStateLock);
923 mAnimFrameTracker.getStats(outStats);
924 return NO_ERROR;
925}
926
Dan Stozac4f471e2016-03-24 09:31:08 -0700927status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
928 HdrCapabilities* outCapabilities) const {
929 Mutex::Autolock _l(mStateLock);
930
931 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
932 if (displayDevice == nullptr) {
933 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
934 return BAD_VALUE;
935 }
936
937 std::unique_ptr<HdrCapabilities> capabilities =
938 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
939 if (capabilities) {
940 std::swap(*outCapabilities, *capabilities);
941 } else {
942 return BAD_VALUE;
943 }
944
945 return NO_ERROR;
946}
947
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700948status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
949 if (enable == mInjectVSyncs) {
950 return NO_ERROR;
951 }
952
953 if (enable) {
954 mInjectVSyncs = enable;
955 ALOGV("VSync Injections enabled");
956 if (mVSyncInjector.get() == nullptr) {
957 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700958 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700959 }
960 mEventQueue.setEventThread(mInjectorEventThread);
961 } else {
962 mInjectVSyncs = enable;
963 ALOGV("VSync Injections disabled");
964 mEventQueue.setEventThread(mSFEventThread);
965 mVSyncInjector.clear();
966 }
967 return NO_ERROR;
968}
969
970status_t SurfaceFlinger::injectVSync(nsecs_t when) {
971 if (!mInjectVSyncs) {
972 ALOGE("VSync Injections not enabled");
973 return BAD_VALUE;
974 }
975 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
976 ALOGV("Injecting VSync inside SurfaceFlinger");
977 mVSyncInjector->onInjectSyncEvent(when);
978 }
979 return NO_ERROR;
980}
981
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800982// ----------------------------------------------------------------------------
983
984sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800985 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700986}
987
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800988// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800989
990void SurfaceFlinger::waitForEvent() {
991 mEventQueue.waitMessage();
992}
993
994void SurfaceFlinger::signalTransaction() {
995 mEventQueue.invalidate();
996}
997
998void SurfaceFlinger::signalLayerUpdate() {
999 mEventQueue.invalidate();
1000}
1001
1002void SurfaceFlinger::signalRefresh() {
1003 mEventQueue.refresh();
1004}
1005
1006status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001007 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001008 return mEventQueue.postMessage(msg, reltime);
1009}
1010
1011status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001012 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001013 status_t res = mEventQueue.postMessage(msg, reltime);
1014 if (res == NO_ERROR) {
1015 msg->wait();
1016 }
1017 return res;
1018}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001020void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001021 do {
1022 waitForEvent();
1023 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024}
1025
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001026void SurfaceFlinger::enableHardwareVsync() {
1027 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001028 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001030 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1031 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001032 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001033 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001034}
1035
Jesse Hall948fe0c2013-10-14 12:56:09 -07001036void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001037 Mutex::Autolock _l(mHWVsyncLock);
1038
Jesse Hall948fe0c2013-10-14 12:56:09 -07001039 if (makeAvailable) {
1040 mHWVsyncAvailable = true;
1041 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001042 // Hardware vsync is not currently available, so abort the resync
1043 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001044 return;
1045 }
1046
Dan Stoza9e56aa02015-11-02 13:00:03 -08001047 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1048 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049
1050 mPrimaryDispSync.reset();
1051 mPrimaryDispSync.setPeriod(period);
1052
1053 if (!mPrimaryHWVsyncEnabled) {
1054 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1056 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057 mPrimaryHWVsyncEnabled = true;
1058 }
1059}
1060
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001062 Mutex::Autolock _l(mHWVsyncLock);
1063 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001064 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1065 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001066 mPrimaryDispSync.endResync();
1067 mPrimaryHWVsyncEnabled = false;
1068 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069 if (makeUnavailable) {
1070 mHWVsyncAvailable = false;
1071 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072}
1073
Tim Murray4a4e4a22016-04-19 16:29:23 +00001074void SurfaceFlinger::resyncWithRateLimit() {
1075 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1076 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001077 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001078 }
1079}
1080
Dan Stoza9e56aa02015-11-02 13:00:03 -08001081void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001082 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083
Jamie Gennisd1700752013-10-14 12:22:52 -07001084 { // Scope for the lock
1085 Mutex::Autolock _l(mHWVsyncLock);
1086 if (type == 0 && mPrimaryHWVsyncEnabled) {
1087 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001089 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001090
1091 if (needsHwVsync) {
1092 enableHardwareVsync();
1093 } else {
1094 disableHardwareVsync(false);
1095 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001096}
1097
Dan Stoza9e56aa02015-11-02 13:00:03 -08001098void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1099 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1100 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1101 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001102
Dan Stoza9e56aa02015-11-02 13:00:03 -08001103 // All non-virtual displays are currently considered secure.
1104 bool isSecure = true;
1105
1106 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1107 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1108 wp<IBinder> token = mBuiltinDisplays[type];
1109
1110 sp<IGraphicBufferProducer> producer;
1111 sp<IGraphicBufferConsumer> consumer;
1112 BufferQueue::createBufferQueue(&producer, &consumer,
1113 new GraphicBufferAlloc());
1114
1115 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1116 DisplayDevice::DISPLAY_PRIMARY, consumer);
1117 sp<DisplayDevice> hw = new DisplayDevice(this,
1118 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1119 producer, mRenderEngine->getEGLConfig());
1120 mDisplays.add(token, hw);
1121 } else {
1122 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001123 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001124 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001125 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001126 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001127 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1128 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001129 }
1130 setTransactionFlags(eDisplayTransactionNeeded);
1131
Andy McFadden9e9689c2012-10-10 18:17:51 -07001132 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001133 }
Mathias Agopian86303202012-07-24 22:46:10 -07001134}
1135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001137 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001138 getHwComposer().setVsyncEnabled(disp,
1139 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001140}
1141
Mathias Agopian4fec8732012-06-29 14:12:52 -07001142void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001143 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001144 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001145 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001146 bool frameMissed = !mHadClientComposition &&
1147 mPreviousPresentFence != Fence::NO_FENCE &&
1148 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1149 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001150 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001151 signalLayerUpdate();
1152 break;
1153 }
1154
Dan Stoza6b9454d2014-11-07 16:00:59 -08001155 bool refreshNeeded = handleMessageTransaction();
1156 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001157 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001158 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001159 // Signal a refresh if a transaction modified the window state,
1160 // a new buffer was latched, or if HWC has requested a full
1161 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001162 signalRefresh();
1163 }
1164 break;
1165 }
1166 case MessageQueue::REFRESH: {
1167 handleMessageRefresh();
1168 break;
1169 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170 }
1171}
1172
Dan Stoza6b9454d2014-11-07 16:00:59 -08001173bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001174 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001175 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001176 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001177 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001178 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001179 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001180}
1181
Dan Stoza6b9454d2014-11-07 16:00:59 -08001182bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001183 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001184 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001185}
1186
1187void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001188 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001189
Pablo Ceballos40845df2016-01-25 17:41:15 -08001190 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001191
Brian Andersond6927fb2016-07-23 23:37:30 -07001192 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001193 rebuildLayerStacks();
1194 setUpHWComposer();
1195 doDebugFlashRegions();
1196 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001197 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001198
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001199 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001200
1201 mHadClientComposition = false;
1202 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1203 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1204 mHadClientComposition = mHadClientComposition ||
1205 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1206 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001207
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001209}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001210
Mathias Agopiancd60f992012-08-16 16:28:27 -07001211void SurfaceFlinger::doDebugFlashRegions()
1212{
1213 // is debugging enabled
1214 if (CC_LIKELY(!mDebugRegion))
1215 return;
1216
1217 const bool repaintEverything = mRepaintEverything;
1218 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1219 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001220 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001221 // transform the dirty region into this screen's coordinate space
1222 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1223 if (!dirtyRegion.isEmpty()) {
1224 // redraw the whole screen
1225 doComposeSurfaces(hw, Region(hw->bounds()));
1226
1227 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001228 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001229 RenderEngine& engine(getRenderEngine());
1230 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1231
Mathias Agopianda27af92012-09-13 18:17:13 -07001232 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001233 }
1234 }
1235 }
1236
1237 postFramebuffer();
1238
1239 if (mDebugRegion > 1) {
1240 usleep(mDebugRegion * 1000);
1241 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001242
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001244 auto& displayDevice = mDisplays[displayId];
1245 if (!displayDevice->isDisplayOn()) {
1246 continue;
1247 }
1248
1249 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1251 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001252 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001253}
1254
Brian Andersond6927fb2016-07-23 23:37:30 -07001255void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001256{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001257 ATRACE_CALL();
1258 ALOGV("preComposition");
1259
Mathias Agopiancd60f992012-08-16 16:28:27 -07001260 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001261 mDrawingState.traverseInZOrder([&](Layer* layer) {
1262 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001263 needExtraInvalidate = true;
1264 }
Robert Carr2047fae2016-11-28 14:09:09 -08001265 });
1266
Mathias Agopiancd60f992012-08-16 16:28:27 -07001267 if (needExtraInvalidate) {
1268 signalLayerUpdate();
1269 }
1270}
1271
Brian Andersond6927fb2016-07-23 23:37:30 -07001272void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001273{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 ATRACE_CALL();
1275 ALOGV("postComposition");
1276
Brian Anderson3546a3f2016-07-14 11:51:14 -07001277 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001278 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001279 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001280 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001281 }
1282
Brian Andersond6927fb2016-07-23 23:37:30 -07001283 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001284
1285 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1286 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1287 glCompositionDoneFenceTime =
1288 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1289 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1290 } else {
1291 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1292 }
1293 mGlCompositionDoneTimeline.updateSignalTimes();
1294
1295 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1296 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1297 mDisplayTimeline.push(displayFenceTime);
1298 mDisplayTimeline.updateSignalTimes();
1299
1300 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1301 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1302 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1303 presentFenceTime = &displayFenceTime;
1304 } else {
1305 retireFenceTime = &displayFenceTime;
1306 }
Robert Carr2047fae2016-11-28 14:09:09 -08001307 mDrawingState.traverseInZOrder([&](Layer* layer) {
1308 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1309 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001310 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001311 recordBufferingStats(layer->getName().string(),
1312 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001313 }
Robert Carr2047fae2016-11-28 14:09:09 -08001314 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001315
Brian Anderson3d4039d2016-09-23 16:31:30 -07001316 if (displayFence->isValid()) {
1317 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318 enableHardwareVsync();
1319 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001320 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321 }
1322 }
1323
Andy McFadden5167ec62014-05-22 13:08:43 -07001324 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001325 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326 enableHardwareVsync();
1327 }
1328 }
1329
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001330 if (mAnimCompositionPending) {
1331 mAnimCompositionPending = false;
1332
Brian Anderson3d4039d2016-09-23 16:31:30 -07001333 if (displayFenceTime->isValid()) {
1334 mAnimFrameTracker.setActualPresentFence(
1335 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001336 } else {
1337 // The HWC doesn't support present fences, so use the refresh
1338 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001339 nsecs_t presentTime =
1340 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001341 mAnimFrameTracker.setActualPresentTime(presentTime);
1342 }
1343 mAnimFrameTracker.advanceFrame();
1344 }
Dan Stozab90cf072015-03-05 11:05:59 -08001345
1346 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1347 return;
1348 }
1349
1350 nsecs_t currentTime = systemTime();
1351 if (mHasPoweredOff) {
1352 mHasPoweredOff = false;
1353 } else {
1354 nsecs_t period = mPrimaryDispSync.getPeriod();
1355 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1356 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1357 if (numPeriods < NUM_BUCKETS - 1) {
1358 mFrameBuckets[numPeriods] += elapsedTime;
1359 } else {
1360 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1361 }
1362 mTotalTime += elapsedTime;
1363 }
1364 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365}
1366
1367void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 ATRACE_CALL();
1369 ALOGV("rebuildLayerStacks");
1370
Mathias Agopiancd60f992012-08-16 16:28:27 -07001371 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001372 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001374 mVisibleRegionsDirty = false;
1375 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001376
Mathias Agopian92a979a2012-08-02 18:32:23 -07001377 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001378 Region opaqueRegion;
1379 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380 Vector<sp<Layer>> layersSortedByZ;
1381 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1382 const Transform& tr(displayDevice->getTransform());
1383 const Rect bounds(displayDevice->getBounds());
1384 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001385 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 displayDevice->getLayerStack(), dirtyRegion,
1387 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001388
Robert Carr2047fae2016-11-28 14:09:09 -08001389 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001390 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001391 Region drawRegion(tr.transform(
1392 layer->visibleNonTransparentRegion));
1393 drawRegion.andSelf(bounds);
1394 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001395 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 } else {
1397 // Clear out the HWC layer if this layer was
1398 // previously visible, but no longer is
1399 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1400 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001401 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001402 }
Robert Carr2047fae2016-11-28 14:09:09 -08001403 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001404 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001405 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1406 displayDevice->undefinedRegion.set(bounds);
1407 displayDevice->undefinedRegion.subtractSelf(
1408 tr.transform(opaqueRegion));
1409 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001410 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001411 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001412}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001413
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001415 ATRACE_CALL();
1416 ALOGV("setUpHWComposer");
1417
Jesse Hall028dc8f2013-08-20 16:35:32 -07001418 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001419 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1420 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1421 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1422
1423 // If nothing has changed (!dirty), don't recompose.
1424 // If something changed, but we don't currently have any visible layers,
1425 // and didn't when we last did a composition, then skip it this time.
1426 // The second rule does two things:
1427 // - When all layers are removed from a display, we'll emit one black
1428 // frame, then nothing more until we get new layers.
1429 // - When a display is created with a private layer stack, we won't
1430 // emit any black frames until a layer is added to the layer stack.
1431 bool mustRecompose = dirty && !(empty && wasEmpty);
1432
1433 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1434 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1435 mustRecompose ? "doing" : "skipping",
1436 dirty ? "+" : "-",
1437 empty ? "+" : "-",
1438 wasEmpty ? "+" : "-");
1439
Dan Stoza71433162014-02-04 16:22:36 -08001440 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001441
1442 if (mustRecompose) {
1443 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1444 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001445 }
1446
Dan Stoza9e56aa02015-11-02 13:00:03 -08001447 // build the h/w work list
1448 if (CC_UNLIKELY(mGeometryInvalid)) {
1449 mGeometryInvalid = false;
1450 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1451 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1452 const auto hwcId = displayDevice->getHwcDisplayId();
1453 if (hwcId >= 0) {
1454 const Vector<sp<Layer>>& currentLayers(
1455 displayDevice->getVisibleLayersSortedByZ());
1456 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001457 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001458 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 if (!layer->hasHwcLayer(hwcId)) {
1460 auto hwcLayer = mHwc->createLayer(hwcId);
1461 if (hwcLayer) {
1462 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1463 } else {
1464 layer->forceClientComposition(hwcId);
1465 foundLayerWithoutHwc = true;
1466 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001467 }
1468 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001469
Robert Carrae060832016-11-28 10:51:00 -08001470 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001471 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001472 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001473 }
1474 }
1475 }
1476 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 }
Riley Andrews03414a12014-07-01 14:22:59 -07001478
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001479
1480 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1481
Dan Stoza9e56aa02015-11-02 13:00:03 -08001482 // Set the per-frame data
1483 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1484 auto& displayDevice = mDisplays[displayId];
1485 const auto hwcId = displayDevice->getHwcDisplayId();
1486 if (hwcId < 0) {
1487 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001488 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001489 if (colorMatrix != mPreviousColorMatrix) {
1490 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1491 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1492 "display %zd: %d", displayId, result);
1493 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001494 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1495 layer->setPerFrameData(displayDevice);
1496 }
1497 }
1498
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001499 mPreviousColorMatrix = colorMatrix;
1500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001502 auto& displayDevice = mDisplays[displayId];
1503 if (!displayDevice->isDisplayOn()) {
1504 continue;
1505 }
1506
1507 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001508 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1509 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001510 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001512
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513void SurfaceFlinger::doComposition() {
1514 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001515 ALOGV("doComposition");
1516
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001517 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001518 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001519 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001520 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 // transform the dirty region into this screen's coordinate space
1522 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001523
1524 // repaint the framebuffer (if needed)
1525 doDisplayComposition(hw, dirtyRegion);
1526
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 hw->dirtyRegion.clear();
1528 hw->flip(hw->swapRegion);
1529 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001530 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001532 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001533}
1534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535void SurfaceFlinger::postFramebuffer()
1536{
Mathias Agopian841cde52012-03-01 15:44:37 -08001537 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001538 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001539
Mathias Agopiana44b0412011-10-16 18:46:35 -07001540 const nsecs_t now = systemTime();
1541 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001542
Dan Stoza9e56aa02015-11-02 13:00:03 -08001543 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1544 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001545 if (!displayDevice->isDisplayOn()) {
1546 continue;
1547 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001548 const auto hwcId = displayDevice->getHwcDisplayId();
1549 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001550 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001551 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001552 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001553 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001554 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1555 sp<Fence> releaseFence = Fence::NO_FENCE;
1556 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1557 releaseFence = displayDevice->getClientTargetAcquireFence();
1558 } else {
1559 auto hwcLayer = layer->getHwcLayer(hwcId);
1560 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001561 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 layer->onLayerDisplayed(releaseFence);
1563 }
1564 if (hwcId >= 0) {
1565 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001566 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001567 }
1568
Mathias Agopiana44b0412011-10-16 18:46:35 -07001569 mLastSwapBufferTime = systemTime() - now;
1570 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001571
1572 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1573 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1574 logFrameStats();
1575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001576}
1577
Mathias Agopian87baae12012-07-31 12:38:26 -07001578void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001579{
Mathias Agopian841cde52012-03-01 15:44:37 -08001580 ATRACE_CALL();
1581
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001582 // here we keep a copy of the drawing state (that is the state that's
1583 // going to be overwritten by handleTransactionLocked()) outside of
1584 // mStateLock so that the side-effects of the State assignment
1585 // don't happen with mStateLock held (which can cause deadlocks).
1586 State drawingState(mDrawingState);
1587
Mathias Agopianca4d3602011-05-19 15:38:14 -07001588 Mutex::Autolock _l(mStateLock);
1589 const nsecs_t now = systemTime();
1590 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001591
Mathias Agopianca4d3602011-05-19 15:38:14 -07001592 // Here we're guaranteed that some transaction flags are set
1593 // so we can call handleTransactionLocked() unconditionally.
1594 // We call getTransactionFlags(), which will also clear the flags,
1595 // with mStateLock held to guarantee that mCurrentState won't change
1596 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001597
Mathias Agopiane57f2922012-08-09 16:29:12 -07001598 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001599 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001600
Mathias Agopianca4d3602011-05-19 15:38:14 -07001601 mLastTransactionTime = systemTime() - now;
1602 mDebugInTransaction = 0;
1603 invalidateHwcGeometry();
1604 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001605}
1606
Mathias Agopian87baae12012-07-31 12:38:26 -07001607void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001608{
Dan Stoza7dde5992015-05-22 09:51:44 -07001609 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001610 mCurrentState.traverseInZOrder([](Layer* layer) {
1611 layer->notifyAvailableFrames();
1612 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001613
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001614 /*
1615 * Traversal of the children
1616 * (perform the transaction for each of them if needed)
1617 */
1618
Mathias Agopian3559b072012-08-15 13:46:03 -07001619 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001620 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001621 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001622 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001623
1624 const uint32_t flags = layer->doTransaction(0);
1625 if (flags & Layer::eVisibleRegion)
1626 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001627 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001628 }
1629
1630 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001631 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001632 */
1633
Mathias Agopiane57f2922012-08-09 16:29:12 -07001634 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001635 // here we take advantage of Vector's copy-on-write semantics to
1636 // improve performance by skipping the transaction entirely when
1637 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001638 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1639 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001640 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001641 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001642 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001643 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001644
1645 // find the displays that were removed
1646 // (ie: in drawing state but not in current state)
1647 // also handle displays that changed
1648 // (ie: displays that are in both lists)
1649 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001650 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1651 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001652 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001653 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001654 // Call makeCurrent() on the primary display so we can
1655 // be sure that nothing associated with this display
1656 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001657 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001658 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001659 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1660 if (hw != NULL)
1661 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001662 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001663 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001664 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001665 } else {
1666 ALOGW("trying to remove the main display");
1667 }
1668 } else {
1669 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001670 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001671 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001672 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1673 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001674 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001675 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001676 // recreating the DisplayDevice, so we just remove it
1677 // from the drawing state, so that it get re-added
1678 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001679 sp<DisplayDevice> hw(getDisplayDevice(display));
1680 if (hw != NULL)
1681 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001682 mDisplays.removeItem(display);
1683 mDrawingState.displays.removeItemsAt(i);
1684 dc--; i--;
1685 // at this point we must loop to the next item
1686 continue;
1687 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001688
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001689 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001690 if (disp != NULL) {
1691 if (state.layerStack != draw[i].layerStack) {
1692 disp->setLayerStack(state.layerStack);
1693 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001694 if ((state.orientation != draw[i].orientation)
1695 || (state.viewport != draw[i].viewport)
1696 || (state.frame != draw[i].frame))
1697 {
1698 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001699 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001700 }
Michael Lentine47e45402014-07-18 15:34:25 -07001701 if (state.width != draw[i].width || state.height != draw[i].height) {
1702 disp->setDisplaySize(state.width, state.height);
1703 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001704 }
1705 }
1706 }
1707
1708 // find displays that were added
1709 // (ie: in current state but not in drawing state)
1710 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001711 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001712 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001713
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001714 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001715 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001716 sp<IGraphicBufferProducer> bqProducer;
1717 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001718 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1719 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001720
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001722 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001723 // Virtual displays without a surface are dormant:
1724 // they have external state (layer stack, projection,
1725 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001726 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001727
Dan Stoza8cf150a2016-08-02 10:27:31 -07001728 if (mUseHwcVirtualDisplays) {
1729 int width = 0;
1730 int status = state.surface->query(
1731 NATIVE_WINDOW_WIDTH, &width);
1732 ALOGE_IF(status != NO_ERROR,
1733 "Unable to query width (%d)", status);
1734 int height = 0;
1735 status = state.surface->query(
1736 NATIVE_WINDOW_HEIGHT, &height);
1737 ALOGE_IF(status != NO_ERROR,
1738 "Unable to query height (%d)", status);
1739 int intFormat = 0;
1740 status = state.surface->query(
1741 NATIVE_WINDOW_FORMAT, &intFormat);
1742 ALOGE_IF(status != NO_ERROR,
1743 "Unable to query format (%d)", status);
1744 auto format = static_cast<android_pixel_format_t>(
1745 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001746
Dan Stoza8cf150a2016-08-02 10:27:31 -07001747 mHwc->allocateVirtualDisplay(width, height, &format,
1748 &hwcId);
1749 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750
Dan Stoza5cf424b2016-05-20 14:02:39 -07001751 // TODO: Plumb requested format back up to consumer
1752
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 sp<VirtualDisplaySurface> vds =
1754 new VirtualDisplaySurface(*mHwc,
1755 hwcId, state.surface, bqProducer,
1756 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001757
1758 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001759 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001760 }
1761 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001762 ALOGE_IF(state.surface!=NULL,
1763 "adding a supported display, but rendering "
1764 "surface is provided (%p), ignoring it",
1765 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1767 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1768 dispSurface = new FramebufferSurface(*mHwc,
1769 DisplayDevice::DISPLAY_EXTERNAL,
1770 bqConsumer);
1771 producer = bqProducer;
1772 } else {
1773 ALOGE("Attempted to add non-external non-virtual"
1774 " display");
1775 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001776 }
1777
1778 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001779 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001780 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001781 state.type, hwcId, state.isSecure, display,
1782 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001783 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001784 hw->setLayerStack(state.layerStack);
1785 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001786 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001787 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001788 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001789 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001790 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001791 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001792 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001793 }
1794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001796 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797
Mathias Agopian84300952012-11-21 16:02:13 -08001798 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1799 // The transform hint might have changed for some layers
1800 // (either because a display has changed, or because a layer
1801 // as changed).
1802 //
1803 // Walk through all the layers in currentLayers,
1804 // and update their transform hint.
1805 //
1806 // If a layer is visible only on a single display, then that
1807 // display is used to calculate the hint, otherwise we use the
1808 // default display.
1809 //
1810 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1811 // the hint is set before we acquire a buffer from the surface texture.
1812 //
1813 // NOTE: layer transactions have taken place already, so we use their
1814 // drawing state. However, SurfaceFlinger's own transaction has not
1815 // happened yet, so we must use the current state layer list
1816 // (soon to become the drawing state list).
1817 //
1818 sp<const DisplayDevice> disp;
1819 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001820 bool first = true;
1821 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001822 // NOTE: we rely on the fact that layers are sorted by
1823 // layerStack first (so we don't have to traverse the list
1824 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001826 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001827 currentlayerStack = layerStack;
1828 // figure out if this layerstack is mirrored
1829 // (more than one display) if so, pick the default display,
1830 // if not, pick the only display it's on.
1831 disp.clear();
1832 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1833 sp<const DisplayDevice> hw(mDisplays[dpy]);
1834 if (hw->getLayerStack() == currentlayerStack) {
1835 if (disp == NULL) {
1836 disp = hw;
1837 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001838 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001839 break;
1840 }
1841 }
1842 }
1843 }
Chet Haase91d25932013-04-11 15:24:55 -07001844 if (disp == NULL) {
1845 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1846 // redraw after transform hint changes. See bug 8508397.
1847
1848 // could be null when this layer is using a layerStack
1849 // that is not visible on any display. Also can occur at
1850 // screen off/on times.
1851 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001852 }
Chet Haase91d25932013-04-11 15:24:55 -07001853 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001854
1855 first = false;
1856 });
Mathias Agopian84300952012-11-21 16:02:13 -08001857 }
1858
1859
Mathias Agopian3559b072012-08-15 13:46:03 -07001860 /*
1861 * Perform our own transaction if needed
1862 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001863
1864 if (mLayersAdded) {
1865 mLayersAdded = false;
1866 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001867 mVisibleRegionsDirty = true;
1868 }
1869
1870 // some layers might have been removed, so
1871 // we need to update the regions they're exposing.
1872 if (mLayersRemoved) {
1873 mLayersRemoved = false;
1874 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001875 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001877 // this layer is not visible anymore
1878 // TODO: we could traverse the tree from front to back and
1879 // compute the actual visible region
1880 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001881 Region visibleReg;
1882 visibleReg.set(layer->computeScreenBounds());
1883 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001884 }
Robert Carr2047fae2016-11-28 14:09:09 -08001885 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886 }
1887
1888 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001889
1890 updateCursorAsync();
1891}
1892
1893void SurfaceFlinger::updateCursorAsync()
1894{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1896 auto& displayDevice = mDisplays[displayId];
1897 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001898 continue;
1899 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900
1901 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1902 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001903 }
1904 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001905}
1906
1907void SurfaceFlinger::commitTransaction()
1908{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001909 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001910 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001911 for (const auto& l : mLayersPendingRemoval) {
1912 recordBufferingStats(l->getName().string(),
1913 l->getOccupancyHistory(true));
1914 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001915 }
1916 mLayersPendingRemoval.clear();
1917 }
1918
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001919 // If this transaction is part of a window animation then the next frame
1920 // we composite should be considered an animation as well.
1921 mAnimCompositionPending = mAnimTransactionPending;
1922
Mathias Agopian4fec8732012-06-29 14:12:52 -07001923 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001924 mDrawingState.traverseInZOrder([](Layer* layer) {
1925 layer->commitChildList();
1926 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001927 mTransactionPending = false;
1928 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001929 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930}
1931
Robert Carr2047fae2016-11-28 14:09:09 -08001932void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07001933 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934{
Mathias Agopian841cde52012-03-01 15:44:37 -08001935 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938 Region aboveOpaqueLayers;
1939 Region aboveCoveredLayers;
1940 Region dirty;
1941
Mathias Agopian87baae12012-07-31 12:38:26 -07001942 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001943
Robert Carr2047fae2016-11-28 14:09:09 -08001944 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001945 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001946 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947
Jesse Hall01e29052013-02-19 16:13:35 -08001948 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001949 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001950 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07001951
Mathias Agopianab028732010-03-16 16:41:46 -07001952 /*
1953 * opaqueRegion: area of a surface that is fully opaque.
1954 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001955 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001956
1957 /*
1958 * visibleRegion: area of a surface that is visible on screen
1959 * and not fully transparent. This is essentially the layer's
1960 * footprint minus the opaque regions above it.
1961 * Areas covered by a translucent surface are considered visible.
1962 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001964
1965 /*
1966 * coveredRegion: area of a surface that is covered by all
1967 * visible regions above it (which includes the translucent areas).
1968 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001970
Jesse Halla8026d22012-09-25 13:25:04 -07001971 /*
1972 * transparentRegion: area of a surface that is hinted to be completely
1973 * transparent. This is only used to tell when the layer has no visible
1974 * non-transparent regions and can be removed from the layer list. It
1975 * does not affect the visibleRegion of this layer or any layers
1976 * beneath it. The hint may not be correct if apps don't respect the
1977 * SurfaceView restrictions (which, sadly, some don't).
1978 */
1979 Region transparentRegion;
1980
Mathias Agopianab028732010-03-16 16:41:46 -07001981
1982 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001983 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001984 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001985 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001987 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07001988 if (!visibleRegion.isEmpty()) {
1989 // Remove the transparent area from the visible region
1990 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001991 if (tr.preserveRects()) {
1992 // transform the transparent region
1993 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001994 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001995 // transformation too complex, can't do the
1996 // transparent region optimization.
1997 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001998 }
Mathias Agopianab028732010-03-16 16:41:46 -07001999 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000
Mathias Agopianab028732010-03-16 16:41:46 -07002001 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002002 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002004 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2005 // the opaque region is the layer's footprint
2006 opaqueRegion = visibleRegion;
2007 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002008 }
2009 }
2010
Mathias Agopianab028732010-03-16 16:41:46 -07002011 // Clip the covered region to the visible region
2012 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2013
2014 // Update aboveCoveredLayers for next (lower) layer
2015 aboveCoveredLayers.orSelf(visibleRegion);
2016
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002017 // subtract the opaque region covered by the layers above us
2018 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002019
2020 // compute this layer's dirty region
2021 if (layer->contentDirty) {
2022 // we need to invalidate the whole region
2023 dirty = visibleRegion;
2024 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002025 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002026 layer->contentDirty = false;
2027 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002028 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002029 * the exposed region consists of two components:
2030 * 1) what's VISIBLE now and was COVERED before
2031 * 2) what's EXPOSED now less what was EXPOSED before
2032 *
2033 * note that (1) is conservative, we start with the whole
2034 * visible region but only keep what used to be covered by
2035 * something -- which mean it may have been exposed.
2036 *
2037 * (2) handles areas that were not covered by anything but got
2038 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002039 */
Mathias Agopianab028732010-03-16 16:41:46 -07002040 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041 const Region oldVisibleRegion = layer->visibleRegion;
2042 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002043 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2044 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045 }
2046 dirty.subtractSelf(aboveOpaqueLayers);
2047
2048 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002049 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050
Mathias Agopianab028732010-03-16 16:41:46 -07002051 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002053
Jesse Halla8026d22012-09-25 13:25:04 -07002054 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 layer->setVisibleRegion(visibleRegion);
2056 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002057 layer->setVisibleNonTransparentRegion(
2058 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002059 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060
Mathias Agopian87baae12012-07-31 12:38:26 -07002061 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062}
2063
Mathias Agopian87baae12012-07-31 12:38:26 -07002064void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2065 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002066 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002067 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2068 if (hw->getLayerStack() == layerStack) {
2069 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002070 }
2071 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002072}
2073
Dan Stoza6b9454d2014-11-07 16:00:59 -08002074bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002075{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 ALOGV("handlePageFlip");
2077
Brian Andersond6927fb2016-07-23 23:37:30 -07002078 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079
Mathias Agopian4fec8732012-06-29 14:12:52 -07002080 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002081 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002082
2083 // Store the set of layers that need updates. This set must not change as
2084 // buffers are being latched, as this could result in a deadlock.
2085 // Example: Two producers share the same command stream and:
2086 // 1.) Layer 0 is latched
2087 // 2.) Layer 0 gets a new frame
2088 // 2.) Layer 1 gets a new frame
2089 // 3.) Layer 1 is latched.
2090 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2091 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002092 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002093 if (layer->hasQueuedFrame()) {
2094 frameQueued = true;
2095 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002096 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002097 } else {
2098 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002099 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002100 } else {
2101 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002102 }
Robert Carr2047fae2016-11-28 14:09:09 -08002103 });
2104
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002106 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002107 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002108 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002109 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002110
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002111 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002112
2113 // If we will need to wake up at some time in the future to deal with a
2114 // queued frame that shouldn't be displayed during this vsync period, wake
2115 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002117 signalLayerUpdate();
2118 }
2119
2120 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002121 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122}
2123
Mathias Agopianad456f92011-01-13 17:53:01 -08002124void SurfaceFlinger::invalidateHwcGeometry()
2125{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002127}
2128
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002129
Fabien Sanglard830b8472016-11-30 16:35:58 -08002130void SurfaceFlinger::doDisplayComposition(
2131 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002132 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133{
Dan Stoza71433162014-02-04 16:22:36 -08002134 // We only need to actually compose the display if:
2135 // 1) It is being handled by hardware composer, which may need this to
2136 // keep its virtual display state machine in sync, or
2137 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002138 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002139 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002141 return;
2142 }
2143
Dan Stoza9e56aa02015-11-02 13:00:03 -08002144 ALOGV("doDisplayComposition");
2145
Mathias Agopian87baae12012-07-31 12:38:26 -07002146 Region dirtyRegion(inDirtyRegion);
2147
Mathias Agopianb8a55602009-06-26 19:06:36 -07002148 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002149 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150
Fabien Sanglard830b8472016-11-30 16:35:58 -08002151 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002152 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002153 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2154 // takes a rectangle, we must make sure to update that whole
2155 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002156 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002157 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002158 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002159 // We need to redraw the rectangle that will be updated
2160 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002161 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002162 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002163 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002164 } else {
2165 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002166 dirtyRegion.set(displayDevice->bounds());
2167 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168 }
2169 }
2170
Fabien Sanglard830b8472016-11-30 16:35:58 -08002171 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002173 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002174 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002175
2176 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002177 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178}
2179
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180bool SurfaceFlinger::doComposeSurfaces(
2181 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002182{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002183 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002184
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002186
2187 mat4 oldColorMatrix;
2188 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2189 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2190 if (applyColorMatrix) {
2191 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2192 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2193 }
2194
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2196 if (hasClientComposition) {
2197 ALOGV("hasClientComposition");
2198
2199 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002200 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002201 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002202 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2203 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2204 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2205 }
2206 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002207 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002208
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002209 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002210 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2211 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002212 // when using overlays, we assume a fully transparent framebuffer
2213 // NOTE: we could reduce how much we need to clear, for instance
2214 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002215 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002216 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002218 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002219 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002221
2222 // we remove the scissor part
2223 // we're left with the letterbox region
2224 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002226
2227 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002229
2230 // but limit it to the dirty region
2231 region.andSelf(dirty);
2232
Mathias Agopianb9494d52012-04-18 02:28:45 -07002233 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002234 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002235 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002237 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002238 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002239
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002241 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002242 // scissor on the main display. It should never be needed
2243 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 const Rect& bounds(displayDevice->getBounds());
2245 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002246 if (scissor != bounds) {
2247 // scissor doesn't match the screen's dimensions, so we
2248 // need to clear everything outside of it and enable
2249 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002250
Mathias Agopianf45c5102012-10-24 16:29:17 -07002251 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 const uint32_t height = displayDevice->getHeight();
2253 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002254 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002255 }
2256 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002257 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002258
Mathias Agopian85d751c2012-08-29 16:59:24 -07002259 /*
2260 * and then, render the layers targeted at the framebuffer
2261 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002262
Dan Stoza9e56aa02015-11-02 13:00:03 -08002263 ALOGV("Rendering client layers");
2264 const Transform& displayTransform = displayDevice->getTransform();
2265 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002266 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 bool firstLayer = true;
2268 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2269 const Region clip(dirty.intersect(
2270 displayTransform.transform(layer->visibleRegion)));
2271 ALOGV("Layer: %s", layer->getName().string());
2272 ALOGV(" Composition type: %s",
2273 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002274 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 switch (layer->getCompositionType(hwcId)) {
2276 case HWC2::Composition::Cursor:
2277 case HWC2::Composition::Device:
2278 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002279 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002280 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2281 layer->isOpaque(state) && (state.alpha == 1.0f)
2282 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002283 // never clear the very first layer since we're
2284 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002285 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002286 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002287 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002288 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 case HWC2::Composition::Client: {
2290 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002291 break;
2292 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002293 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002294 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002295 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 } else {
2297 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002298 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002300 }
2301 } else {
2302 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002303 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002304 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002306 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002308 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002309 }
2310 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002311
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002312 if (applyColorMatrix) {
2313 getRenderEngine().setupColorTransform(oldColorMatrix);
2314 }
2315
Mathias Agopianf45c5102012-10-24 16:29:17 -07002316 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002318 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319}
2320
Fabien Sanglard830b8472016-11-30 16:35:58 -08002321void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2322 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002323 RenderEngine& engine(getRenderEngine());
2324 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325}
2326
Dan Stoza7d89d062015-04-30 13:29:25 -07002327status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002328 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002329 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002330 const sp<Layer>& lbc,
2331 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002332{
Dan Stoza7d89d062015-04-30 13:29:25 -07002333 // add this layer to the current state list
2334 {
2335 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002336 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002337 return NO_MEMORY;
2338 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002339 if (parent == nullptr) {
2340 mCurrentState.layersSortedByZ.add(lbc);
2341 } else {
2342 parent->addChild(lbc);
2343 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002344 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002345 mLayersAdded = true;
2346 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002347 }
2348
Mathias Agopian96f08192010-06-02 23:28:45 -07002349 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002350 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002351
Dan Stoza7d89d062015-04-30 13:29:25 -07002352 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002353}
2354
Dan Stoza22851c32016-08-09 13:21:03 -07002355status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002357 sp<Layer> layer = weakLayer.promote();
2358 if (layer == nullptr) {
2359 // The layer has already been removed, carry on
2360 return NO_ERROR;
2361 }
2362
Robert Carr1f0a16a2016-10-24 16:27:39 -07002363 const auto& p = layer->getParent();
2364 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2365 mCurrentState.layersSortedByZ.remove(layer);
2366
2367 if (index < 0) {
2368 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2369 layer->getName().string(),
2370 (p != nullptr) ? p->getName().string() : "no-parent");
2371 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002372 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002373
2374 mLayersPendingRemoval.add(layer);
2375 mLayersRemoved = true;
2376 mNumLayers--;
2377 setTransactionFlags(eTransactionNeeded);
2378 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379}
2380
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002381uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002382 return android_atomic_release_load(&mTransactionFlags);
2383}
2384
Mathias Agopian3f844832013-08-07 21:24:32 -07002385uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002386 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2387}
2388
Mathias Agopian3f844832013-08-07 21:24:32 -07002389uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002390 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2391 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002392 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 }
2394 return old;
2395}
2396
Mathias Agopian8b33f032012-07-24 20:43:54 -07002397void SurfaceFlinger::setTransactionState(
2398 const Vector<ComposerState>& state,
2399 const Vector<DisplayState>& displays,
2400 uint32_t flags)
2401{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002402 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002403 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002404 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002405
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002406 if (flags & eAnimation) {
2407 // For window updates that are part of an animation we must wait for
2408 // previous animation "frames" to be handled.
2409 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002410 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002411 if (CC_UNLIKELY(err != NO_ERROR)) {
2412 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002413 // caller after a few seconds.
2414 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2415 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002416 mAnimTransactionPending = false;
2417 break;
2418 }
2419 }
2420 }
2421
Mathias Agopiane57f2922012-08-09 16:29:12 -07002422 size_t count = displays.size();
2423 for (size_t i=0 ; i<count ; i++) {
2424 const DisplayState& s(displays[i]);
2425 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002426 }
2427
Mathias Agopiane57f2922012-08-09 16:29:12 -07002428 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002429 for (size_t i=0 ; i<count ; i++) {
2430 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002431 // Here we need to check that the interface we're given is indeed
2432 // one of our own. A malicious client could give us a NULL
2433 // IInterface, or one of its own or even one of our own but a
2434 // different type. All these situations would cause us to crash.
2435 //
2436 // NOTE: it would be better to use RTTI as we could directly check
2437 // that we have a Client*. however, RTTI is disabled in Android.
2438 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002439 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002440 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002441 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002442 sp<Client> client( static_cast<Client *>(s.client.get()) );
2443 transactionFlags |= setClientStateLocked(client, s.state);
2444 }
2445 }
2446 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002447 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002448
Robert Carr2a7dbb42016-05-24 11:41:28 -07002449 // If a synchronous transaction is explicitly requested without any changes,
2450 // force a transaction anyway. This can be used as a flush mechanism for
2451 // previous async transactions.
2452 if (transactionFlags == 0 && (flags & eSynchronous)) {
2453 transactionFlags = eTransactionNeeded;
2454 }
2455
Mathias Agopian386aa982011-11-07 21:58:03 -08002456 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002457 if (mInterceptor.isEnabled()) {
2458 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2459 }
Irvel468051e2016-06-13 16:44:44 -07002460
Mathias Agopian386aa982011-11-07 21:58:03 -08002461 // this triggers the transaction
2462 setTransactionFlags(transactionFlags);
2463
2464 // if this is a synchronous transaction, wait for it to take effect
2465 // before returning.
2466 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002467 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002468 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002469 if (flags & eAnimation) {
2470 mAnimTransactionPending = true;
2471 }
2472 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002473 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2474 if (CC_UNLIKELY(err != NO_ERROR)) {
2475 // just in case something goes wrong in SF, return to the
2476 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002477 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2478 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002479 break;
2480 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 }
2483}
2484
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2486{
Jesse Hall9a143922012-10-04 16:29:19 -07002487 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2488 if (dpyIdx < 0)
2489 return 0;
2490
Mathias Agopiane57f2922012-08-09 16:29:12 -07002491 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002492 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002493 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002494 const uint32_t what = s.what;
2495 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002496 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 disp.surface = s.surface;
2498 flags |= eDisplayTransactionNeeded;
2499 }
2500 }
2501 if (what & DisplayState::eLayerStackChanged) {
2502 if (disp.layerStack != s.layerStack) {
2503 disp.layerStack = s.layerStack;
2504 flags |= eDisplayTransactionNeeded;
2505 }
2506 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002507 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002508 if (disp.orientation != s.orientation) {
2509 disp.orientation = s.orientation;
2510 flags |= eDisplayTransactionNeeded;
2511 }
2512 if (disp.frame != s.frame) {
2513 disp.frame = s.frame;
2514 flags |= eDisplayTransactionNeeded;
2515 }
2516 if (disp.viewport != s.viewport) {
2517 disp.viewport = s.viewport;
2518 flags |= eDisplayTransactionNeeded;
2519 }
2520 }
Michael Lentine47e45402014-07-18 15:34:25 -07002521 if (what & DisplayState::eDisplaySizeChanged) {
2522 if (disp.width != s.width) {
2523 disp.width = s.width;
2524 flags |= eDisplayTransactionNeeded;
2525 }
2526 if (disp.height != s.height) {
2527 disp.height = s.height;
2528 flags |= eDisplayTransactionNeeded;
2529 }
2530 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002531 }
2532 return flags;
2533}
2534
2535uint32_t SurfaceFlinger::setClientStateLocked(
2536 const sp<Client>& client,
2537 const layer_state_t& s)
2538{
2539 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002540 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002541 if (layer != 0) {
2542 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002543 bool geometryAppliesWithResize =
2544 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002545 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002546 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002547 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002549 }
2550 if (what & layer_state_t::eLayerChanged) {
2551 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552 const auto& p = layer->getParent();
2553 if (p == nullptr) {
2554 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2555 if (layer->setLayer(s.z) && idx >= 0) {
2556 mCurrentState.layersSortedByZ.removeAt(idx);
2557 mCurrentState.layersSortedByZ.add(layer);
2558 // we need traversal (state changed)
2559 // AND transaction (list changed)
2560 flags |= eTransactionNeeded|eTraversalNeeded;
2561 }
2562 } else {
2563 if (p->setChildLayer(layer, s.z)) {
2564 flags |= eTransactionNeeded|eTraversalNeeded;
2565 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 }
2567 }
2568 if (what & layer_state_t::eSizeChanged) {
2569 if (layer->setSize(s.w, s.h)) {
2570 flags |= eTraversalNeeded;
2571 }
2572 }
2573 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002575 flags |= eTraversalNeeded;
2576 }
2577 if (what & layer_state_t::eMatrixChanged) {
2578 if (layer->setMatrix(s.matrix))
2579 flags |= eTraversalNeeded;
2580 }
2581 if (what & layer_state_t::eTransparentRegionChanged) {
2582 if (layer->setTransparentRegionHint(s.transparentRegion))
2583 flags |= eTraversalNeeded;
2584 }
Dan Stoza23116082015-06-18 14:58:39 -07002585 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002586 if (layer->setFlags(s.flags, s.mask))
2587 flags |= eTraversalNeeded;
2588 }
2589 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002590 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591 flags |= eTraversalNeeded;
2592 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002593 if (what & layer_state_t::eFinalCropChanged) {
2594 if (layer->setFinalCrop(s.finalCrop))
2595 flags |= eTraversalNeeded;
2596 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002597 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002598 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599 // We only allow setting layer stacks for top level layers,
2600 // everything else inherits layer stack from its parent.
2601 if (layer->hasParent()) {
2602 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2603 layer->getName().string());
2604 } else if (idx < 0) {
2605 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2606 "that also does not appear in the top level layer list. Something"
2607 " has gone wrong.", layer->getName().string());
2608 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002609 mCurrentState.layersSortedByZ.removeAt(idx);
2610 mCurrentState.layersSortedByZ.add(layer);
2611 // we need traversal (state changed)
2612 // AND transaction (list changed)
2613 flags |= eTransactionNeeded|eTraversalNeeded;
2614 }
2615 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002616 if (what & layer_state_t::eDeferTransaction) {
2617 layer->deferTransactionUntil(s.handle, s.frameNumber);
2618 // We don't trigger a traversal here because if no other state is
2619 // changed, we don't want this to cause any more work
2620 }
Robert Carr1db73f62016-12-21 12:58:51 -08002621 if (what & layer_state_t::eReparentChildren) {
2622 if (layer->reparentChildren(s.reparentHandle)) {
2623 flags |= eTransactionNeeded|eTraversalNeeded;
2624 }
2625 }
Robert Carrc3574f72016-03-24 12:19:32 -07002626 if (what & layer_state_t::eOverrideScalingModeChanged) {
2627 layer->setOverrideScalingMode(s.overrideScalingMode);
2628 // We don't trigger a traversal here because if no other state is
2629 // changed, we don't want this to cause any more work
2630 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002631 }
2632 return flags;
2633}
2634
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002635status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002636 const String8& name,
2637 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002638 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002639 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2640 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002642 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002643 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002644 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002645 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002646 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002647
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002648 status_t result = NO_ERROR;
2649
2650 sp<Layer> layer;
2651
Mathias Agopian3165cc22012-08-08 19:42:09 -07002652 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2653 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002654 result = createNormalLayer(client,
2655 name, w, h, flags, format,
2656 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002658 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002659 result = createDimLayer(client,
2660 name, w, h, flags,
2661 handle, gbp, &layer);
2662 break;
2663 default:
2664 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 break;
2666 }
2667
Dan Stoza7d89d062015-04-30 13:29:25 -07002668 if (result != NO_ERROR) {
2669 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002671
Albert Chaulk479c60c2017-01-27 14:21:34 -05002672 layer->setInfo(windowType, ownerUid);
2673
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002675 if (result != NO_ERROR) {
2676 return result;
2677 }
Irvelffc9efc2016-07-27 15:16:37 -07002678 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002679
2680 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002681 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682}
2683
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002684status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2685 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2686 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687{
2688 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002689 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 case PIXEL_FORMAT_TRANSPARENT:
2691 case PIXEL_FORMAT_TRANSLUCENT:
2692 format = PIXEL_FORMAT_RGBA_8888;
2693 break;
2694 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002695 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 break;
2697 }
2698
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002699 *outLayer = new Layer(this, client, name, w, h, flags);
2700 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2701 if (err == NO_ERROR) {
2702 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002703 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002705
2706 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2707 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708}
2709
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002710status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2711 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2712 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002714 *outLayer = new LayerDim(this, client, name, w, h, flags);
2715 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002716 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002717 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002718}
2719
Mathias Agopianac9fa422013-02-11 16:40:36 -08002720status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721{
Mathias Agopian67106042013-03-14 19:18:13 -07002722 // called by the window manager when it wants to remove a Layer
2723 status_t err = NO_ERROR;
2724 sp<Layer> l(client->getLayerUser(handle));
2725 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002726 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002727 err = removeLayer(l);
2728 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2729 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002730 }
2731 return err;
2732}
2733
Mathias Agopian13127d82013-03-05 17:47:11 -08002734status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002735{
Mathias Agopian67106042013-03-14 19:18:13 -07002736 // called by ~LayerCleaner() when all references to the IBinder (handle)
2737 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002738 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739}
2740
Mathias Agopianb60314a2012-04-10 22:09:54 -07002741// ---------------------------------------------------------------------------
2742
Andy McFadden13a082e2012-08-24 10:16:42 -07002743void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002744 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002745 Vector<ComposerState> state;
2746 Vector<DisplayState> displays;
2747 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002748 d.what = DisplayState::eDisplayProjectionChanged |
2749 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002750 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002751 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002752 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002753 d.frame.makeInvalid();
2754 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002755 d.width = 0;
2756 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002757 displays.add(d);
2758 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002759 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002760
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2762 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002763 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002764}
2765
2766void SurfaceFlinger::initializeDisplays() {
2767 class MessageScreenInitialized : public MessageBase {
2768 SurfaceFlinger* flinger;
2769 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002770 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002771 virtual bool handler() {
2772 flinger->onInitializeDisplays();
2773 return true;
2774 }
2775 };
2776 sp<MessageBase> msg = new MessageScreenInitialized(this);
2777 postMessageAsync(msg); // we may be called from main thread, use async message
2778}
2779
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002780void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2781 int mode) {
2782 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2783 this);
2784 int32_t type = hw->getDisplayType();
2785 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002786
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002787 if (mode == currentMode) {
2788 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002789 return;
2790 }
2791
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002792 hw->setPowerMode(mode);
2793 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2794 ALOGW("Trying to set power mode for virtual display");
2795 return;
2796 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002797
Irvelffc9efc2016-07-27 15:16:37 -07002798 if (mInterceptor.isEnabled()) {
2799 Mutex::Autolock _l(mStateLock);
2800 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2801 if (idx < 0) {
2802 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2803 return;
2804 }
2805 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2806 }
2807
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002808 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002809 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002810 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2812 // FIXME: eventthread only knows about the main display right now
2813 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002814 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002815 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002817 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002818 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002819 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002820
2821 struct sched_param param = {0};
2822 param.sched_priority = 1;
2823 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2824 ALOGW("Couldn't set SCHED_FIFO on display on");
2825 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002826 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002827 // Turn off the display
2828 struct sched_param param = {0};
2829 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2830 ALOGW("Couldn't set SCHED_OTHER on display off");
2831 }
2832
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002833 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002834 disableHardwareVsync(true); // also cancels any in-progress resync
2835
Mathias Agopiancde87a32012-09-13 14:09:01 -07002836 // FIXME: eventthread only knows about the main display right now
2837 mEventThread->onScreenReleased();
2838 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002839
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002840 getHwComposer().setPowerMode(type, mode);
2841 mVisibleRegionsDirty = true;
2842 // from this point on, SF will stop drawing on this display
2843 } else {
2844 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002845 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002846}
2847
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002848void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2849 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002850 SurfaceFlinger& mFlinger;
2851 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002852 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002853 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002854 MessageSetPowerMode(SurfaceFlinger& flinger,
2855 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2856 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002857 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002858 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002859 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002860 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002861 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002862 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002863 ALOGW("Attempt to set power mode = %d for virtual display",
2864 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002865 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002866 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002867 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002868 return true;
2869 }
2870 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002871 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002872 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002873}
2874
2875// ---------------------------------------------------------------------------
2876
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2878{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002880
Mathias Agopianbd115332013-04-18 16:41:04 -07002881 IPCThreadState* ipc = IPCThreadState::self();
2882 const int pid = ipc->getCallingPid();
2883 const int uid = ipc->getCallingUid();
2884 if ((uid != AID_SHELL) &&
2885 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002886 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002887 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002889 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002890 // (this would indicate SF is stuck, but we want to be able to
2891 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002892 status_t err = mStateLock.timedLock(s2ns(1));
2893 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002894 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002895 result.appendFormat(
2896 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2897 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002898 }
2899
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002900 bool dumpAll = true;
2901 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002902 size_t numArgs = args.size();
2903 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002904 if ((index < numArgs) &&
2905 (args[index] == String16("--list"))) {
2906 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002907 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002908 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002909 }
2910
2911 if ((index < numArgs) &&
2912 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002913 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002914 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002915 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002916 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002917
2918 if ((index < numArgs) &&
2919 (args[index] == String16("--latency-clear"))) {
2920 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002921 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002922 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002923 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002924
2925 if ((index < numArgs) &&
2926 (args[index] == String16("--dispsync"))) {
2927 index++;
2928 mPrimaryDispSync.dump(result);
2929 dumpAll = false;
2930 }
Dan Stozab90cf072015-03-05 11:05:59 -08002931
2932 if ((index < numArgs) &&
2933 (args[index] == String16("--static-screen"))) {
2934 index++;
2935 dumpStaticScreenStats(result);
2936 dumpAll = false;
2937 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002938
2939 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002940 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002941 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002942 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002943 dumpAll = false;
2944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002946
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002947 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002948 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002949 }
2950
Mathias Agopian9795c422009-08-26 16:36:26 -07002951 if (locked) {
2952 mStateLock.unlock();
2953 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954 }
2955 write(fd, result.string(), result.size());
2956 return NO_ERROR;
2957}
2958
Dan Stozac7014012014-02-14 15:03:43 -08002959void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2960 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002961{
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002963 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002964 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002965}
2966
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002967void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002968 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002969{
2970 String8 name;
2971 if (index < args.size()) {
2972 name = String8(args[index]);
2973 index++;
2974 }
2975
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2977 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002978 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002979
2980 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002981 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002982 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002983 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002984 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002985 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002986 }
Robert Carr2047fae2016-11-28 14:09:09 -08002987 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002988 }
2989}
2990
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002991void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002992 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002993{
2994 String8 name;
2995 if (index < args.size()) {
2996 name = String8(args[index]);
2997 index++;
2998 }
2999
Robert Carr2047fae2016-11-28 14:09:09 -08003000 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003001 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003002 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003003 }
Robert Carr2047fae2016-11-28 14:09:09 -08003004 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003005
Svetoslavd85084b2014-03-20 10:28:31 -07003006 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003007}
3008
Jamie Gennis6547ff42013-07-16 20:12:42 -07003009// This should only be called from the main thread. Otherwise it would need
3010// the lock and should use mCurrentState rather than mDrawingState.
3011void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003012 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003013 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003014 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003015
3016 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3017}
3018
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003019void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003020{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003021 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003022#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003023 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003024#endif
3025#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003026 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003027#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003028 if (isLayerTripleBufferingDisabled())
3029 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003030 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003031}
3032
Dan Stozab90cf072015-03-05 11:05:59 -08003033void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3034{
3035 result.appendFormat("Static screen stats:\n");
3036 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3037 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3038 float percent = 100.0f *
3039 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3040 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3041 b + 1, bucketTimeSec, percent);
3042 }
3043 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3044 float percent = 100.0f *
3045 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3046 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3047 NUM_BUCKETS - 1, bucketTimeSec, percent);
3048}
3049
Dan Stozae77c7662016-05-13 11:37:28 -07003050void SurfaceFlinger::recordBufferingStats(const char* layerName,
3051 std::vector<OccupancyTracker::Segment>&& history) {
3052 Mutex::Autolock lock(mBufferingStatsMutex);
3053 auto& stats = mBufferingStats[layerName];
3054 for (const auto& segment : history) {
3055 if (!segment.usedThirdBuffer) {
3056 stats.twoBufferTime += segment.totalTime;
3057 }
3058 if (segment.occupancyAverage < 1.0f) {
3059 stats.doubleBufferedTime += segment.totalTime;
3060 } else if (segment.occupancyAverage < 2.0f) {
3061 stats.tripleBufferedTime += segment.totalTime;
3062 }
3063 ++stats.numSegments;
3064 stats.totalTime += segment.totalTime;
3065 }
3066}
3067
Brian Andersond6927fb2016-07-23 23:37:30 -07003068void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3069 result.appendFormat("Layer frame timestamps:\n");
3070
3071 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3072 const size_t count = currentLayers.size();
3073 for (size_t i=0 ; i<count ; i++) {
3074 currentLayers[i]->dumpFrameEvents(result);
3075 }
3076}
3077
Dan Stozae77c7662016-05-13 11:37:28 -07003078void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3079 result.append("Buffering stats:\n");
3080 result.append(" [Layer name] <Active time> <Two buffer> "
3081 "<Double buffered> <Triple buffered>\n");
3082 Mutex::Autolock lock(mBufferingStatsMutex);
3083 typedef std::tuple<std::string, float, float, float> BufferTuple;
3084 std::map<float, BufferTuple, std::greater<float>> sorted;
3085 for (const auto& statsPair : mBufferingStats) {
3086 const char* name = statsPair.first.c_str();
3087 const BufferingStats& stats = statsPair.second;
3088 if (stats.numSegments == 0) {
3089 continue;
3090 }
3091 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3092 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3093 stats.totalTime;
3094 float doubleBufferRatio = static_cast<float>(
3095 stats.doubleBufferedTime) / stats.totalTime;
3096 float tripleBufferRatio = static_cast<float>(
3097 stats.tripleBufferedTime) / stats.totalTime;
3098 sorted.insert({activeTime, {name, twoBufferRatio,
3099 doubleBufferRatio, tripleBufferRatio}});
3100 }
3101 for (const auto& sortedPair : sorted) {
3102 float activeTime = sortedPair.first;
3103 const BufferTuple& values = sortedPair.second;
3104 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3105 std::get<0>(values).c_str(), activeTime,
3106 std::get<1>(values), std::get<2>(values),
3107 std::get<3>(values));
3108 }
3109 result.append("\n");
3110}
3111
3112
Mathias Agopian74d211a2013-04-22 16:55:35 +02003113void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3114 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003115{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003116 bool colorize = false;
3117 if (index < args.size()
3118 && (args[index] == String16("--color"))) {
3119 colorize = true;
3120 index++;
3121 }
3122
3123 Colorizer colorizer(colorize);
3124
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125 // figure out if we're stuck somewhere
3126 const nsecs_t now = systemTime();
3127 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3128 const nsecs_t inTransaction(mDebugInTransaction);
3129 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3130 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3131
3132 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003133 * Dump library configuration.
3134 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003135
3136 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003137 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003138 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003139 appendSfConfigString(result);
3140 appendUiConfigString(result);
3141 appendGuiConfigString(result);
3142 result.append("\n");
3143
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003144 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003145 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003146 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003147 result.append(SyncFeatures::getInstance().toString());
3148 result.append("\n");
3149
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3151
Andy McFadden41d67d72014-04-25 16:58:34 -07003152 colorizer.bold(result);
3153 result.append("DispSync configuration: ");
3154 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003155 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3156 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003157 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3158 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003159 result.append("\n");
3160
Dan Stozab90cf072015-03-05 11:05:59 -08003161 // Dump static screen stats
3162 result.append("\n");
3163 dumpStaticScreenStats(result);
3164 result.append("\n");
3165
Dan Stozae77c7662016-05-13 11:37:28 -07003166 dumpBufferingStats(result);
3167
Andy McFadden4803b742012-09-24 19:07:20 -07003168 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003169 * Dump the visible layer list
3170 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003171 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003173 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003174 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003175 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003176 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003177
3178 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003179 * Dump Display state
3180 */
3181
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003182 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003183 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003184 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003185 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3186 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003187 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003188 }
3189
3190 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003191 * Dump SurfaceFlinger global state
3192 */
3193
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003194 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003195 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003196 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003197
Mathias Agopian888c8222012-08-04 21:10:38 -07003198 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003199 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003200
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003201 colorizer.bold(result);
3202 result.appendFormat("EGL implementation : %s\n",
3203 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3204 colorizer.reset(result);
3205 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003206 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003207
Mathias Agopian875d8e12013-06-07 15:35:48 -07003208 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003209
Mathias Agopian42977342012-08-05 00:40:46 -07003210 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003211 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3212 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003213 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003214 " last eglSwapBuffers() time: %f us\n"
3215 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003216 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003217 " refresh-rate : %f fps\n"
3218 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003219 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003220 " gpu_to_cpu_unsupported : %d\n"
3221 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003222 mLastSwapBufferTime/1000.0,
3223 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003224 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003225 1e9 / activeConfig->getVsyncPeriod(),
3226 activeConfig->getDpiX(),
3227 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003228 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003229
Mathias Agopian74d211a2013-04-22 16:55:35 +02003230 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003231 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003232
Mathias Agopian74d211a2013-04-22 16:55:35 +02003233 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003234 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003235
3236 /*
3237 * VSYNC state
3238 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003239 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003240 result.append("\n");
3241
3242 /*
3243 * HWC layer minidump
3244 */
3245 for (size_t d = 0; d < mDisplays.size(); d++) {
3246 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3247 int32_t hwcId = displayDevice->getHwcDisplayId();
3248 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3249 continue;
3250 }
3251
3252 result.appendFormat("Display %d HWC layers:\n", hwcId);
3253 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003254 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003255 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003256 });
Dan Stozae22aec72016-08-01 13:20:59 -07003257 result.append("\n");
3258 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003259
3260 /*
3261 * Dump HWComposer state
3262 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003263 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003264 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003265 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003266 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 result.appendFormat(" h/w composer %s\n",
3268 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003269 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003270
3271 /*
3272 * Dump gralloc state
3273 */
3274 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3275 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003276}
3277
Mathias Agopian13127d82013-03-05 17:47:11 -08003278const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003279SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003280 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003281 wp<IBinder> dpy;
3282 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3283 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3284 dpy = mDisplays.keyAt(i);
3285 break;
3286 }
3287 }
3288 if (dpy == NULL) {
3289 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3290 // Just use the primary display so we have something to return
3291 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3292 }
3293 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003294}
3295
Keun young Park63f165f2012-08-31 10:53:36 -07003296bool SurfaceFlinger::startDdmConnection()
3297{
3298 void* libddmconnection_dso =
3299 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3300 if (!libddmconnection_dso) {
3301 return false;
3302 }
3303 void (*DdmConnection_start)(const char* name);
3304 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003305 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003306 if (!DdmConnection_start) {
3307 dlclose(libddmconnection_dso);
3308 return false;
3309 }
3310 (*DdmConnection_start)(getServiceName());
3311 return true;
3312}
3313
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003314status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 switch (code) {
3316 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003317 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003319 case CLEAR_ANIMATION_FRAME_STATS:
3320 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003321 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003322 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 {
3324 // codes that require permission check
3325 IPCThreadState* ipc = IPCThreadState::self();
3326 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003327 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003328 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003329 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003330 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003331 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003333 break;
3334 }
Robert Carr1db73f62016-12-21 12:58:51 -08003335 /*
3336 * Calling setTransactionState is safe, because you need to have been
3337 * granted a reference to Client* and Handle* to do anything with it.
3338 *
3339 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3340 */
3341 case SET_TRANSACTION_STATE:
3342 case CREATE_SCOPED_CONNECTION:
3343 {
3344 return OK;
3345 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003346 case CAPTURE_SCREEN:
3347 {
3348 // codes that require permission check
3349 IPCThreadState* ipc = IPCThreadState::self();
3350 const int pid = ipc->getCallingPid();
3351 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003352 if ((uid != AID_GRAPHICS) &&
3353 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003354 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003355 return PERMISSION_DENIED;
3356 }
3357 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358 }
3359 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003360 return OK;
3361}
3362
3363status_t SurfaceFlinger::onTransact(
3364 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3365{
3366 status_t credentialCheck = CheckTransactCodeCredentials(code);
3367 if (credentialCheck != OK) {
3368 return credentialCheck;
3369 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3372 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003373 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003374 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003375 IPCThreadState* ipc = IPCThreadState::self();
3376 const int pid = ipc->getCallingPid();
3377 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003378 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003379 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380 return PERMISSION_DENIED;
3381 }
3382 int n;
3383 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003384 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003385 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003386 return NO_ERROR;
3387 case 1002: // SHOW_UPDATES
3388 n = data.readInt32();
3389 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003390 invalidateHwcGeometry();
3391 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003392 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003394 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003395 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003396 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003397 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003398 setTransactionFlags(
3399 eTransactionNeeded|
3400 eDisplayTransactionNeeded|
3401 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003402 return NO_ERROR;
3403 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003404 case 1006:{ // send empty update
3405 signalRefresh();
3406 return NO_ERROR;
3407 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003408 case 1008: // toggle use of hw composer
3409 n = data.readInt32();
3410 mDebugDisableHWC = n ? 1 : 0;
3411 invalidateHwcGeometry();
3412 repaintEverything();
3413 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003414 case 1009: // toggle use of transform hint
3415 n = data.readInt32();
3416 mDebugDisableTransformHint = n ? 1 : 0;
3417 invalidateHwcGeometry();
3418 repaintEverything();
3419 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003420 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003421 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422 reply->writeInt32(0);
3423 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003424 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003425 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003426 return NO_ERROR;
3427 case 1013: {
3428 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003429 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3430 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003431 return NO_ERROR;
3432 }
3433 case 1014: {
3434 // daltonize
3435 n = data.readInt32();
3436 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003437 case 1:
3438 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3439 break;
3440 case 2:
3441 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3442 break;
3443 case 3:
3444 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3445 break;
3446 default:
3447 mDaltonizer.setType(ColorBlindnessType::None);
3448 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003449 }
3450 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003451 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003452 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003453 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003454 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003455 invalidateHwcGeometry();
3456 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003457 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003458 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003459 case 1015: {
3460 // apply a color matrix
3461 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003462 if (n) {
3463 // color matrix is sent as mat3 matrix followed by vec3
3464 // offset, then packed into a mat4 where the last row is
3465 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003466 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003467 for (size_t j = 0; j < 4; j++) {
3468 mColorMatrix[i][j] = data.readFloat();
3469 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003470 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003471 } else {
3472 mColorMatrix = mat4();
3473 }
3474 invalidateHwcGeometry();
3475 repaintEverything();
3476 return NO_ERROR;
3477 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003478 // This is an experimental interface
3479 // Needs to be shifted to proper binder interface when we productize
3480 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003481 n = data.readInt32();
3482 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003483 return NO_ERROR;
3484 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003485 case 1017: {
3486 n = data.readInt32();
3487 mForceFullDamage = static_cast<bool>(n);
3488 return NO_ERROR;
3489 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003490 case 1018: { // Modify Choreographer's phase offset
3491 n = data.readInt32();
3492 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3493 return NO_ERROR;
3494 }
3495 case 1019: { // Modify SurfaceFlinger's phase offset
3496 n = data.readInt32();
3497 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3498 return NO_ERROR;
3499 }
Irvel468051e2016-06-13 16:44:44 -07003500 case 1020: { // Layer updates interceptor
3501 n = data.readInt32();
3502 if (n) {
3503 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003504 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003505 }
3506 else{
3507 ALOGV("Interceptor disabled");
3508 mInterceptor.disable();
3509 }
3510 return NO_ERROR;
3511 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003512 case 1021: { // Disable HWC virtual displays
3513 n = data.readInt32();
3514 mUseHwcVirtualDisplays = !n;
3515 return NO_ERROR;
3516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 }
3518 }
3519 return err;
3520}
3521
Mathias Agopian53331da2011-08-22 21:44:41 -07003522void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003523 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003524 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003525}
3526
Mathias Agopian59119e62010-10-11 12:37:43 -07003527// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003528// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003529// ---------------------------------------------------------------------------
3530
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003531/* The code below is here to handle b/8734824
3532 *
3533 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003534 * from the surfaceflinger thread to the calling binder thread, where they
3535 * are executed. This allows the calling thread in the calling process to be
3536 * reused and not depend on having "enough" binder threads to handle the
3537 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003538 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003539class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003540 /* Parts of GraphicProducerWrapper are run on two different threads,
3541 * communicating by sending messages via Looper but also by shared member
3542 * data. Coherence maintenance is subtle and in places implicit (ugh).
3543 *
3544 * Don't rely on Looper's sendMessage/handleMessage providing
3545 * release/acquire semantics for any data not actually in the Message.
3546 * Data going from surfaceflinger to binder threads needs to be
3547 * synchronized explicitly.
3548 *
3549 * Barrier open/wait do provide release/acquire semantics. This provides
3550 * implicit synchronization for data coming back from binder to
3551 * surfaceflinger threads.
3552 */
3553
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003554 sp<IGraphicBufferProducer> impl;
3555 sp<Looper> looper;
3556 status_t result;
3557 bool exitPending;
3558 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003559 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003560 uint32_t code;
3561 Parcel const* data;
3562 Parcel* reply;
3563
3564 enum {
3565 MSG_API_CALL,
3566 MSG_EXIT
3567 };
3568
3569 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003570 * Called on surfaceflinger thread. This is called by our "fake"
3571 * BpGraphicBufferProducer. We package the data and reply Parcel and
3572 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003573 */
3574 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003575 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003576 this->code = code;
3577 this->data = &data;
3578 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003579 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003580 // if we've exited, we run the message synchronously right here.
3581 // note (JH): as far as I can tell from looking at the code, this
3582 // never actually happens. if it does, i'm not sure if it happens
3583 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003584 handleMessage(Message(MSG_API_CALL));
3585 } else {
3586 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003587 // Prevent stores to this->{code, data, reply} from being
3588 // reordered later than the construction of Message.
3589 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003590 looper->sendMessage(this, Message(MSG_API_CALL));
3591 barrier.wait();
3592 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003593 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003594 }
3595
3596 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003597 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003598 * call the real BpGraphicBufferProducer.
3599 */
3600 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003601 int what = message.what;
3602 // Prevent reads below from happening before the read from Message
3603 atomic_thread_fence(memory_order_acquire);
3604 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003605 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003606 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003607 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003608 exitRequested = true;
3609 }
3610 }
3611
3612public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003613 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003614 : impl(impl),
3615 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003616 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003617 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003618 exitRequested(false),
3619 code(0),
3620 data(NULL),
3621 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003622 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003623
Jesse Hallb154c422014-07-13 12:47:02 -07003624 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003625 status_t waitForResponse() {
3626 do {
3627 looper->pollOnce(-1);
3628 } while (!exitRequested);
3629 return result;
3630 }
3631
Jesse Hallb154c422014-07-13 12:47:02 -07003632 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003633 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003634 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003635 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003636 // Ensure this->result is visible to the binder thread before it
3637 // handles the message.
3638 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003639 looper->sendMessage(this, Message(MSG_EXIT));
3640 }
3641};
3642
3643
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003644status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3645 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003646 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003647 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003648 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003649
3650 if (CC_UNLIKELY(display == 0))
3651 return BAD_VALUE;
3652
3653 if (CC_UNLIKELY(producer == 0))
3654 return BAD_VALUE;
3655
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003656 // if we have secure windows on this display, never allow the screen capture
3657 // unless the producer interface is local (i.e.: we can take a screenshot for
3658 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003659 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003660
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003661 // Convert to surfaceflinger's internal rotation type.
3662 Transform::orientation_flags rotationFlags;
3663 switch (rotation) {
3664 case ISurfaceComposer::eRotateNone:
3665 rotationFlags = Transform::ROT_0;
3666 break;
3667 case ISurfaceComposer::eRotate90:
3668 rotationFlags = Transform::ROT_90;
3669 break;
3670 case ISurfaceComposer::eRotate180:
3671 rotationFlags = Transform::ROT_180;
3672 break;
3673 case ISurfaceComposer::eRotate270:
3674 rotationFlags = Transform::ROT_270;
3675 break;
3676 default:
3677 rotationFlags = Transform::ROT_0;
3678 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3679 break;
3680 }
3681
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003682 class MessageCaptureScreen : public MessageBase {
3683 SurfaceFlinger* flinger;
3684 sp<IBinder> display;
3685 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003686 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003687 uint32_t reqWidth, reqHeight;
3688 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003689 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003690 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003691 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003692 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003693 public:
3694 MessageCaptureScreen(SurfaceFlinger* flinger,
3695 const sp<IBinder>& display,
3696 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003697 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003698 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003699 bool useIdentityTransform,
3700 Transform::orientation_flags rotation,
3701 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003702 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003703 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003704 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003705 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003706 rotation(rotation), result(PERMISSION_DENIED),
3707 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003708 {
3709 }
3710 status_t getResult() const {
3711 return result;
3712 }
3713 virtual bool handler() {
3714 Mutex::Autolock _l(flinger->mStateLock);
3715 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003716 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003717 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003718 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003719 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003720 return true;
3721 }
3722 };
3723
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003724 // this creates a "fake" BBinder which will serve as a "fake" remote
3725 // binder to receive the marshaled calls and forward them to the
3726 // real remote (a BpGraphicBufferProducer)
3727 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3728
3729 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3730 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003731 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003732 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003733 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003734 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003735
3736 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003737 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003738 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003739 }
3740 return res;
3741}
3742
Mathias Agopian180f10d2013-04-10 22:55:41 -07003743
3744void SurfaceFlinger::renderScreenImplLocked(
3745 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003746 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003747 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003748 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003749{
3750 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003751 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003752
3753 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003754 const int32_t hw_w = hw->getWidth();
3755 const int32_t hw_h = hw->getHeight();
3756 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003757 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003758
Dan Stozac1879002014-05-22 15:59:05 -07003759 // if a default or invalid sourceCrop is passed in, set reasonable values
3760 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3761 !sourceCrop.isValid()) {
3762 sourceCrop.setLeftTop(Point(0, 0));
3763 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3764 }
3765
3766 // ensure that sourceCrop is inside screen
3767 if (sourceCrop.left < 0) {
3768 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3769 }
Dan Stozabe31f442014-06-11 11:20:54 -07003770 if (sourceCrop.right > hw_w) {
3771 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003772 }
3773 if (sourceCrop.top < 0) {
3774 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3775 }
Dan Stozabe31f442014-06-11 11:20:54 -07003776 if (sourceCrop.bottom > hw_h) {
3777 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003778 }
3779
Mathias Agopian180f10d2013-04-10 22:55:41 -07003780 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003781 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003782
3783 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003784 engine.setViewportAndProjection(
3785 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003786 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003787
3788 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003789 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003790
Robert Carr1f0a16a2016-10-24 16:27:39 -07003791 // We loop through the first level of layers without traversing,
3792 // as we need to interpret min/max layer Z in the top level Z space.
3793 for (const auto& layer : mDrawingState.layersSortedByZ) {
3794 if (layer->getLayerStack() != hw->getLayerStack()) {
3795 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003796 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003797 const Layer::State& state(layer->getDrawingState());
3798 if (state.z < minLayerZ || state.z > maxLayerZ) {
3799 continue;
3800 }
3801 layer->traverseInZOrder([&](Layer* layer) {
3802 if (!layer->isVisible()) {
3803 return;
3804 }
3805 if (filtering) layer->setFiltering(true);
3806 layer->draw(hw, useIdentityTransform);
3807 if (filtering) layer->setFiltering(false);
3808 });
3809 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003810
Mathias Agopian931bda12013-08-28 18:11:46 -07003811 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003812}
3813
3814
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003815status_t SurfaceFlinger::captureScreenImplLocked(
3816 const sp<const DisplayDevice>& hw,
3817 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003818 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003819 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003820 bool useIdentityTransform, Transform::orientation_flags rotation,
3821 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003822{
3823 ATRACE_CALL();
3824
Mathias Agopian180f10d2013-04-10 22:55:41 -07003825 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003826 uint32_t hw_w = hw->getWidth();
3827 uint32_t hw_h = hw->getHeight();
3828
3829 if (rotation & Transform::ROT_90) {
3830 std::swap(hw_w, hw_h);
3831 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003832
Mathias Agopian180f10d2013-04-10 22:55:41 -07003833 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3834 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3835 reqWidth, reqHeight, hw_w, hw_h);
3836 return BAD_VALUE;
3837 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003838
Mathias Agopian180f10d2013-04-10 22:55:41 -07003839 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3840 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3841
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003842 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003843 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003844 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003845 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3846 (state.z < minLayerZ || state.z > maxLayerZ)) {
3847 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003848 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003849 layer->traverseInZOrder([&](Layer *layer) {
3850 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3851 layer->isSecure());
3852 });
3853 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003854
3855 if (!isLocalScreenshot && secureLayerIsVisible) {
3856 ALOGW("FB is protected: PERMISSION_DENIED");
3857 return PERMISSION_DENIED;
3858 }
3859
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003860 // create a surface (because we're a producer, and we need to
3861 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003862 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003863
3864 // Put the screenshot Surface into async mode so that
3865 // Layer::headFenceHasSignaled will always return true and we'll latch the
3866 // first buffer regardless of whether or not its acquire fence has
3867 // signaled. This is needed to avoid a race condition in the rotation
3868 // animation. See b/30209608
3869 sur->setAsyncMode(true);
3870
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003871 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003872
Michael Lentine5a16a622015-05-21 13:48:24 -07003873 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3874 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003875 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3876 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003877
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003878 int err = 0;
3879 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003880 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003881 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3882 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003883
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003884 if (err == NO_ERROR) {
3885 ANativeWindowBuffer* buffer;
3886 /* TODO: Once we have the sync framework everywhere this can use
3887 * server-side waits on the fence that dequeueBuffer returns.
3888 */
3889 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3890 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003891 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003892 // create an EGLImage from the buffer so we can later
3893 // turn it into a texture
3894 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3895 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3896 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003897 // this binds the given EGLImage as a framebuffer for the
3898 // duration of this scope.
3899 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3900 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003901 // this will in fact render into our dequeued buffer
3902 // via an FBO, which means we didn't have to create
3903 // an EGLSurface and therefore we're not
3904 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003905 renderScreenImplLocked(
3906 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3907 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003908
Riley Andrews86639902014-08-15 12:27:24 -07003909 // Attempt to create a sync khr object that can produce a sync point. If that
3910 // isn't available, create a non-dupable sync object in the fallback path and
3911 // wait on it directly.
3912 EGLSyncKHR sync;
3913 if (!DEBUG_SCREENSHOTS) {
3914 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003915 // native fence fd will not be populated until flush() is done.
3916 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003917 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003918 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003919 }
Riley Andrews86639902014-08-15 12:27:24 -07003920 if (sync != EGL_NO_SYNC_KHR) {
3921 // get the sync fd
3922 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3923 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3924 ALOGW("captureScreen: failed to dup sync khr object");
3925 syncFd = -1;
3926 }
3927 eglDestroySyncKHR(mEGLDisplay, sync);
3928 } else {
3929 // fallback path
3930 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3931 if (sync != EGL_NO_SYNC_KHR) {
3932 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3933 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3934 EGLint eglErr = eglGetError();
3935 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3936 ALOGW("captureScreen: fence wait timed out");
3937 } else {
3938 ALOGW_IF(eglErr != EGL_SUCCESS,
3939 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3940 }
3941 eglDestroySyncKHR(mEGLDisplay, sync);
3942 } else {
3943 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3944 }
3945 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003946 if (DEBUG_SCREENSHOTS) {
3947 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3948 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3949 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3950 hw, minLayerZ, maxLayerZ);
3951 delete [] pixels;
3952 }
3953
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003954 } else {
3955 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3956 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003957 window->cancelBuffer(window, buffer, syncFd);
3958 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003959 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003960 // destroy our image
3961 eglDestroyImageKHR(mEGLDisplay, image);
3962 } else {
3963 result = BAD_VALUE;
3964 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003965 if (buffer) {
3966 // queueBuffer takes ownership of syncFd
3967 result = window->queueBuffer(window, buffer, syncFd);
3968 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003969 }
3970 } else {
3971 result = BAD_VALUE;
3972 }
3973 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3974 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003975
Mathias Agopian74c40c02010-09-29 13:02:36 -07003976 return result;
3977}
3978
Mathias Agopiand5556842013-09-19 17:08:37 -07003979void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003980 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003981 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003982 for (size_t y=0 ; y<h ; y++) {
3983 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3984 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003985 if (p[x] != 0xFF000000) return;
3986 }
3987 }
3988 ALOGE("*** we just took a black screenshot ***\n"
3989 "requested minz=%d, maxz=%d, layerStack=%d",
3990 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003991
Robert Carr2047fae2016-11-28 14:09:09 -08003992 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003993 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003994 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003995 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3996 state.z <= maxLayerZ) {
3997 layer->traverseInZOrder([&](Layer* layer) {
3998 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3999 layer->isVisible() ? '+' : '-',
4000 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004001 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004002 i++;
4003 });
4004 }
4005 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004006 }
4007}
4008
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004009// ---------------------------------------------------------------------------
4010
Robert Carr2047fae2016-11-28 14:09:09 -08004011void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4012 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004013}
4014
Robert Carr2047fae2016-11-28 14:09:09 -08004015void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4016 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004017}
4018
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004020
4021
4022#if defined(__gl_h_)
4023#error "don't include gl/gl.h in this file"
4024#endif
4025
4026#if defined(__gl2_h_)
4027#error "don't include gl2/gl2.h in this file"
4028#endif