blob: 3677c2e09d644c8317fa4c9100852118e52182af [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 Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Mathias Agopianc666cae2012-07-25 18:56:13 -070040#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070041#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042
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>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070071#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080073#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080075#include "VrStateCallbacks.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>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Jaesoo Lee43518572017-01-23 19:03:16 +0900101using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102using namespace android::hardware::configstore::V1_0;
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104// ---------------------------------------------------------------------------
105
Mathias Agopian99b49842011-06-27 16:05:52 -0700106const String16 sHardwareTest("android.permission.HARDWARE_TEST");
107const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
108const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
109const String16 sDump("android.permission.DUMP");
110
111// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800112int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
113int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700114bool SurfaceFlinger::useContextPriority;
Mathias Agopian99b49842011-06-27 16:05:52 -0700115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800116SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700117 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700119 mTransactionPending(false),
120 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700121 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700122 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700123 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800124 mHwc(nullptr),
125 mRealHwc(nullptr),
126 mVrHwc(nullptr),
127 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800129 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800131 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800132 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800133 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700135 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700136 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700137 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700138 mDebugInSwapBuffers(0),
139 mLastSwapBufferTime(0),
140 mDebugInTransaction(0),
141 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700142 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700143 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800144 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000145 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700146 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700147 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800148 mHasColorMatrix(false),
149 mHasPoweredOff(false),
150 mFrameBuckets(),
151 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700152 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800153 mNumLayers(0)
154#ifdef USE_HWC2
155 ,mEnterVrMode(false)
156#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157{
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800158
159 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
160 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
161
162 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
163 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
164
Steve Blocka19954a2012-01-04 20:05:49 +0000165 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700167 useContextPriority = getBool< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::useContextPriority>(false);
169
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 // debugging stuff...
171 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800173 // TODO (urbanus): remove once b/35319396 is fixed.
174 property_get("ro.boot.vr", value, "0");
175 mVrModeSupported = atoi(value);
176
Mathias Agopianb4b17302013-03-20 18:36:41 -0700177 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700178 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 property_get("debug.sf.showupdates", value, "0");
181 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700182
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700183 property_get("debug.sf.ddms", value, "0");
184 mDebugDDMS = atoi(value);
185 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700186 if (!startDdmConnection()) {
187 // start failed, and DDMS debugging not enabled
188 mDebugDDMS = 0;
189 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700190 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700191 ALOGI_IF(mDebugRegion, "showupdates enabled");
192 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700193
194 property_get("debug.sf.disable_backpressure", value, "0");
195 mPropagateBackpressure = !atoi(value);
196 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700197
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800198 property_get("debug.sf.enable_hwc_vds", value, "0");
199 mUseHwcVirtualDisplays = atoi(value);
200 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800201
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800202 property_get("ro.sf.disable_triple_buffer", value, "1");
203 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800204 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205}
206
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207void SurfaceFlinger::onFirstRef()
208{
209 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800210}
211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212SurfaceFlinger::~SurfaceFlinger()
213{
Mathias Agopiana4912602012-07-12 14:25:33 -0700214 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
215 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
216 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800217
218 if (mVrStateCallbacks.get()) {
219 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
220 defaultServiceManager()->checkService(String16("vrmanager")));
221 if (vrManagerService.get()) {
222 vrManagerService->unregisterListener(mVrStateCallbacks);
223 }
224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225}
226
Dan Stozac7014012014-02-14 15:03:43 -0800227void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800228{
229 // the window manager died on us. prepare its eulogy.
230
Andy McFadden13a082e2012-08-24 10:16:42 -0700231 // restore initial conditions (default device unblank, etc)
232 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233
234 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700235 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800236}
237
Robert Carr1db73f62016-12-21 12:58:51 -0800238static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700239 status_t err = client->initCheck();
240 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800241 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 }
Robert Carr1db73f62016-12-21 12:58:51 -0800243 return nullptr;
244}
245
246sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
247 return initClient(new Client(this));
248}
249
250sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
251 const sp<IGraphicBufferProducer>& gbp) {
252 if (authenticateSurfaceTexture(gbp) == false) {
253 return nullptr;
254 }
255 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
256 if (layer == nullptr) {
257 return nullptr;
258 }
259
260 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261}
262
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700263sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
264 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700265{
266 class DisplayToken : public BBinder {
267 sp<SurfaceFlinger> flinger;
268 virtual ~DisplayToken() {
269 // no more references, this display must be terminated
270 Mutex::Autolock _l(flinger->mStateLock);
271 flinger->mCurrentState.displays.removeItem(this);
272 flinger->setTransactionFlags(eDisplayTransactionNeeded);
273 }
274 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700275 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700276 : flinger(flinger) {
277 }
278 };
279
280 sp<BBinder> token = new DisplayToken(this);
281
282 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700283 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700284 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700286 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700287 return token;
288}
289
Jesse Hall6c913be2013-08-08 12:15:49 -0700290void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
291 Mutex::Autolock _l(mStateLock);
292
293 ssize_t idx = mCurrentState.displays.indexOfKey(display);
294 if (idx < 0) {
295 ALOGW("destroyDisplay: invalid display token");
296 return;
297 }
298
299 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
300 if (!info.isVirtualDisplay()) {
301 ALOGE("destroyDisplay called for non-virtual display");
302 return;
303 }
Irvelffc9efc2016-07-27 15:16:37 -0700304 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700305 mCurrentState.displays.removeItemsAt(idx);
306 setTransactionFlags(eDisplayTransactionNeeded);
307}
308
Jesse Hall692c7232012-11-08 15:41:56 -0800309void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800310 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800311 ALOGW_IF(mBuiltinDisplays[type],
312 "Overwriting display token for display type %d", type);
313 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800314 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700315 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800316 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700317 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800318}
319
Mathias Agopiane57f2922012-08-09 16:29:12 -0700320sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700321 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700322 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
323 return NULL;
324 }
Jesse Hall692c7232012-11-08 15:41:56 -0800325 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700326}
327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328void SurfaceFlinger::bootFinished()
329{
Wei Wangb254fa32017-01-31 17:43:23 -0800330 if (mStartBootAnimThread->join() != NO_ERROR) {
331 ALOGE("Join StartBootAnimThread failed!");
332 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 const nsecs_t now = systemTime();
334 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000335 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700336 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700337
338 // wait patiently for the window manager death
339 const String16 name("window");
340 sp<IBinder> window(defaultServiceManager()->getService(name));
341 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700342 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700343 }
344
345 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700346 // formerly we would just kill the process, but we now ask it to exit so it
347 // can choose where to stop the animation.
348 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700349
350 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
351 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
352 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800353
354 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
355 defaultServiceManager()->checkService(String16("vrmanager")));
356 if (vrManagerService.get()) {
357 mVrStateCallbacks = new VrStateCallbacks(*this);
358 vrManagerService->registerListener(mVrStateCallbacks);
359 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360}
361
Mathias Agopian3f844832013-08-07 21:24:32 -0700362void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700364 RenderEngine& engine;
365 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700366 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700367 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
368 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700369 }
370 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700371 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700372 return true;
373 }
374 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376}
377
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700378class DispSyncSource : public VSyncSource, private DispSync::Callback {
379public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700380 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000381 const char* name) :
382 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700383 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700384 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000385 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
386 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700387 mDispSync(dispSync),
388 mCallbackMutex(),
389 mCallback(),
390 mVsyncMutex(),
391 mPhaseOffset(phaseOffset),
392 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700393
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394 virtual ~DispSyncSource() {}
395
396 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700397 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700400 static_cast<DispSync::Callback*>(this));
401 if (err != NO_ERROR) {
402 ALOGE("error registering vsync callback: %s (%d)",
403 strerror(-err), err);
404 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700405 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700406 } else {
407 status_t err = mDispSync->removeEventListener(
408 static_cast<DispSync::Callback*>(this));
409 if (err != NO_ERROR) {
410 ALOGE("error unregistering vsync callback: %s (%d)",
411 strerror(-err), err);
412 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700413 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 }
417
418 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 mCallback = callback;
421 }
422
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 virtual void setPhaseOffset(nsecs_t phaseOffset) {
424 Mutex::Autolock lock(mVsyncMutex);
425
426 // Normalize phaseOffset to [0, period)
427 auto period = mDispSync->getPeriod();
428 phaseOffset %= period;
429 if (phaseOffset < 0) {
430 // If we're here, then phaseOffset is in (-period, 0). After this
431 // operation, it will be in (0, period)
432 phaseOffset += period;
433 }
434 mPhaseOffset = phaseOffset;
435
436 // If we're not enabled, we don't need to mess with the listeners
437 if (!mEnabled) {
438 return;
439 }
440
441 // Remove the listener with the old offset
442 status_t err = mDispSync->removeEventListener(
443 static_cast<DispSync::Callback*>(this));
444 if (err != NO_ERROR) {
445 ALOGE("error unregistering vsync callback: %s (%d)",
446 strerror(-err), err);
447 }
448
449 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000450 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451 static_cast<DispSync::Callback*>(this));
452 if (err != NO_ERROR) {
453 ALOGE("error registering vsync callback: %s (%d)",
454 strerror(-err), err);
455 }
456 }
457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458private:
459 virtual void onDispSyncEvent(nsecs_t when) {
460 sp<VSyncSource::Callback> callback;
461 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 callback = mCallback;
464
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700465 if (mTraceVsync) {
466 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700467 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700468 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 }
470
471 if (callback != NULL) {
472 callback->onVSyncEvent(when);
473 }
474 }
475
Tim Murray4a4e4a22016-04-19 16:29:23 +0000476 const char* const mName;
477
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 int mValue;
479
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700480 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700481 const String8 mVsyncOnLabel;
482 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485
486 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700488
489 Mutex mVsyncMutex; // Protects the following
490 nsecs_t mPhaseOffset;
491 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492};
493
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700494class InjectVSyncSource : public VSyncSource {
495public:
496 InjectVSyncSource() {}
497
498 virtual ~InjectVSyncSource() {}
499
500 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
501 std::lock_guard<std::mutex> lock(mCallbackMutex);
502 mCallback = callback;
503 }
504
505 virtual void onInjectSyncEvent(nsecs_t when) {
506 std::lock_guard<std::mutex> lock(mCallbackMutex);
507 mCallback->onVSyncEvent(when);
508 }
509
510 virtual void setVSyncEnabled(bool) {}
511 virtual void setPhaseOffset(nsecs_t) {}
512
513private:
514 std::mutex mCallbackMutex; // Protects the following
515 sp<VSyncSource::Callback> mCallback;
516};
517
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700519 ALOGI( "SurfaceFlinger's main thread ready to run. "
520 "Initializing graphics H/W...");
521
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900522 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
523
Dan Stoza9e56aa02015-11-02 13:00:03 -0800524 { // Autolock scope
525 Mutex::Autolock _l(mStateLock);
526
527 // initialize EGL for the default display
528 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
529 eglInitialize(mEGLDisplay, NULL, NULL);
530
531 // start the EventThread
532 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
533 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700534 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800535 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
536 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700537 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800538 mEventQueue.setEventThread(mSFEventThread);
539
Tim Murrayacff43d2016-07-29 13:57:24 -0700540 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700541 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700542 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700543 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
544 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
545 }
546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 // Get a RenderEngine for the given display / config (can't fail)
548 mRenderEngine = RenderEngine::create(mEGLDisplay,
549 HAL_PIXEL_FORMAT_RGBA_8888);
550 }
551
552 // Drop the state lock while we initialize the hardware composer. We drop
553 // the lock because on creation, it will call back into SurfaceFlinger to
554 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800555 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800556 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800557 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
559
Jesse Hall692c7232012-11-08 15:41:56 -0800560 Mutex::Autolock _l(mStateLock);
561
Mathias Agopian875d8e12013-06-07 15:35:48 -0700562 // retrieve the EGL context that was selected/created
563 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700564
Mathias Agopianda27af92012-09-13 18:17:13 -0700565 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
566 "couldn't create EGLContext");
567
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 // make the GLContext current so that we can create textures when creating
569 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700570 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
571
Jamie Gennisd1700752013-10-14 12:22:52 -0700572 mEventControlThread = new EventControlThread(this);
573 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
574
Mathias Agopian92a979a2012-08-02 18:32:23 -0700575 // initialize our drawing state
576 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700577
Andy McFadden13a082e2012-08-24 10:16:42 -0700578 // set initial conditions (e.g. unblank default device)
579 initializeDisplays();
580
Dan Stoza4e637772016-07-28 13:31:51 -0700581 mRenderEngine->primeCache();
582
Wei Wangb254fa32017-01-31 17:43:23 -0800583 mStartBootAnimThread = new StartBootAnimThread();
584 if (mStartBootAnimThread->Start() != NO_ERROR) {
585 ALOGE("Run StartBootAnimThread failed!");
586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700589}
590
Mathias Agopiana67e4182012-06-19 17:26:12 -0700591void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800592 // Start boot animation service by setting a property mailbox
593 // if property setting thread is already running, Start() will be just a NOP
594 mStartBootAnimThread->Start();
595 // Wait until property was set
596 if (mStartBootAnimThread->join() != NO_ERROR) {
597 ALOGE("Join StartBootAnimThread failed!");
598 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700599}
600
Mathias Agopian875d8e12013-06-07 15:35:48 -0700601size_t SurfaceFlinger::getMaxTextureSize() const {
602 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700603}
604
Mathias Agopian875d8e12013-06-07 15:35:48 -0700605size_t SurfaceFlinger::getMaxViewportDims() const {
606 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700607}
608
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800609// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800610
Jamie Gennis582270d2011-08-17 18:19:00 -0700611bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800612 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800613 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800614 return authenticateSurfaceTextureLocked(bufferProducer);
615}
616
617bool SurfaceFlinger::authenticateSurfaceTextureLocked(
618 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800619 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700620 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800621}
622
Brian Anderson069b3652016-07-22 10:32:47 -0700623status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700624 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700625 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700626 FrameEvent::REQUESTED_PRESENT,
627 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700628 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700629 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700630 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700631 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700632 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700633 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700634 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700635 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700636 };
637 return NO_ERROR;
638}
639
Dan Stoza7f7da322014-05-02 15:26:25 -0700640status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
641 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700642 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700643 return BAD_VALUE;
644 }
645
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500646 if (!display.get())
647 return NAME_NOT_FOUND;
648
Jesse Hall692c7232012-11-08 15:41:56 -0800649 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700650 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800651 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700652 type = i;
653 break;
654 }
655 }
656
657 if (type < 0) {
658 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700659 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700660
Mathias Agopian8b736f12012-08-13 17:54:26 -0700661 // TODO: Not sure if display density should handled by SF any longer
662 class Density {
663 static int getDensityFromProperty(char const* propName) {
664 char property[PROPERTY_VALUE_MAX];
665 int density = 0;
666 if (property_get(propName, property, NULL) > 0) {
667 density = atoi(property);
668 }
669 return density;
670 }
671 public:
672 static int getEmuDensity() {
673 return getDensityFromProperty("qemu.sf.lcd_density"); }
674 static int getBuildDensity() {
675 return getDensityFromProperty("ro.sf.lcd_density"); }
676 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700677
Dan Stoza7f7da322014-05-02 15:26:25 -0700678 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700681 DisplayInfo info = DisplayInfo();
682
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 float xdpi = hwConfig->getDpiX();
684 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700685
686 if (type == DisplayDevice::DISPLAY_PRIMARY) {
687 // The density of the device is provided by a build property
688 float density = Density::getBuildDensity() / 160.0f;
689 if (density == 0) {
690 // the build doesn't provide a density -- this is wrong!
691 // use xdpi instead
692 ALOGE("ro.sf.lcd_density must be defined as a build property");
693 density = xdpi / 160.0f;
694 }
695 if (Density::getEmuDensity()) {
696 // if "qemu.sf.lcd_density" is specified, it overrides everything
697 xdpi = ydpi = density = Density::getEmuDensity();
698 density /= 160.0f;
699 }
700 info.density = density;
701
702 // TODO: this needs to go away (currently needed only by webkit)
703 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
704 info.orientation = hw->getOrientation();
705 } else {
706 // TODO: where should this value come from?
707 static const int TV_DENSITY = 213;
708 info.density = TV_DENSITY / 160.0f;
709 info.orientation = 0;
710 }
711
Dan Stoza9e56aa02015-11-02 13:00:03 -0800712 info.w = hwConfig->getWidth();
713 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700714 info.xdpi = xdpi;
715 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800716 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900717 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800718
Andy McFadden91b2ca82014-06-13 14:04:23 -0700719 // This is how far in advance a buffer must be queued for
720 // presentation at a given time. If you want a buffer to appear
721 // on the screen at time N, you must submit the buffer before
722 // (N - presentationDeadline).
723 //
724 // Normally it's one full refresh period (to give SF a chance to
725 // latch the buffer), but this can be reduced by configuring a
726 // DispSync offset. Any additional delays introduced by the hardware
727 // composer or panel must be accounted for here.
728 //
729 // We add an additional 1ms to allow for processing time and
730 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800732 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700733
734 // All non-virtual displays are currently considered secure.
735 info.secure = true;
736
Michael Wright28f24d02016-07-12 13:30:53 -0700737 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700738 }
739
Dan Stoza7f7da322014-05-02 15:26:25 -0700740 return NO_ERROR;
741}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700742
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800743status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700744 DisplayStatInfo* stats) {
745 if (stats == NULL) {
746 return BAD_VALUE;
747 }
748
749 // FIXME for now we always return stats for the primary display
750 memset(stats, 0, sizeof(*stats));
751 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
752 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
753 return NO_ERROR;
754}
755
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700756int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800757 if (display == NULL) {
758 ALOGE("%s : display is NULL", __func__);
759 return BAD_VALUE;
760 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700761 sp<DisplayDevice> device(getDisplayDevice(display));
762 if (device != NULL) {
763 return device->getActiveConfig();
764 }
765 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700766}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700767
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700768void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
769 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
770 this);
771 int32_t type = hw->getDisplayType();
772 int currentMode = hw->getActiveConfig();
773
774 if (mode == currentMode) {
775 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
776 return;
777 }
778
779 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
780 ALOGW("Trying to set config for virtual display");
781 return;
782 }
783
784 hw->setActiveConfig(mode);
785 getHwComposer().setActiveConfig(type, mode);
786}
787
788status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
789 class MessageSetActiveConfig: public MessageBase {
790 SurfaceFlinger& mFlinger;
791 sp<IBinder> mDisplay;
792 int mMode;
793 public:
794 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
795 int mode) :
796 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
797 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700798 Vector<DisplayInfo> configs;
799 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700800 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700801 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700802 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700803 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700804 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700805 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
806 if (hw == NULL) {
807 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700808 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700809 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
810 ALOGW("Attempt to set active config = %d for virtual display",
811 mMode);
812 } else {
813 mFlinger.setActiveConfigInternal(hw, mMode);
814 }
815 return true;
816 }
817 };
818 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
819 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700820 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700821}
Michael Wright28f24d02016-07-12 13:30:53 -0700822status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
823 Vector<android_color_mode_t>* outColorModes) {
824 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
825 return BAD_VALUE;
826 }
827
828 if (!display.get()) {
829 return NAME_NOT_FOUND;
830 }
831
832 int32_t type = NAME_NOT_FOUND;
833 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
834 if (display == mBuiltinDisplays[i]) {
835 type = i;
836 break;
837 }
838 }
839
840 if (type < 0) {
841 return type;
842 }
843
844 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
845 outColorModes->clear();
846 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
847
848 return NO_ERROR;
849}
850
851android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
852 sp<DisplayDevice> device(getDisplayDevice(display));
853 if (device != nullptr) {
854 return device->getActiveColorMode();
855 }
856 return static_cast<android_color_mode_t>(BAD_VALUE);
857}
858
859void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
860 android_color_mode_t mode) {
861 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
862 this);
863 int32_t type = hw->getDisplayType();
864 android_color_mode_t currentMode = hw->getActiveColorMode();
865
866 if (mode == currentMode) {
867 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
868 return;
869 }
870
871 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
872 ALOGW("Trying to set config for virtual display");
873 return;
874 }
875
876 hw->setActiveColorMode(mode);
877 getHwComposer().setActiveColorMode(type, mode);
878}
879
880
881status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
882 android_color_mode_t colorMode) {
883 class MessageSetActiveColorMode: public MessageBase {
884 SurfaceFlinger& mFlinger;
885 sp<IBinder> mDisplay;
886 android_color_mode_t mMode;
887 public:
888 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
889 android_color_mode_t mode) :
890 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
891 virtual bool handler() {
892 Vector<android_color_mode_t> modes;
893 mFlinger.getDisplayColorModes(mDisplay, &modes);
894 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
895 if (mMode < 0 || !exists) {
896 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
897 mDisplay.get());
898 return true;
899 }
900 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
901 if (hw == nullptr) {
902 ALOGE("Attempt to set active color mode = %d for null display %p",
903 mMode, mDisplay.get());
904 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
905 ALOGW("Attempt to set active color mode= %d for virtual display",
906 mMode);
907 } else {
908 mFlinger.setActiveColorModeInternal(hw, mMode);
909 }
910 return true;
911 }
912 };
913 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
914 postMessageSync(msg);
915 return NO_ERROR;
916}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700917
Svetoslavd85084b2014-03-20 10:28:31 -0700918status_t SurfaceFlinger::clearAnimationFrameStats() {
919 Mutex::Autolock _l(mStateLock);
920 mAnimFrameTracker.clearStats();
921 return NO_ERROR;
922}
923
924status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
925 Mutex::Autolock _l(mStateLock);
926 mAnimFrameTracker.getStats(outStats);
927 return NO_ERROR;
928}
929
Dan Stozac4f471e2016-03-24 09:31:08 -0700930status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
931 HdrCapabilities* outCapabilities) const {
932 Mutex::Autolock _l(mStateLock);
933
934 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
935 if (displayDevice == nullptr) {
936 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
937 return BAD_VALUE;
938 }
939
940 std::unique_ptr<HdrCapabilities> capabilities =
941 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
942 if (capabilities) {
943 std::swap(*outCapabilities, *capabilities);
944 } else {
945 return BAD_VALUE;
946 }
947
948 return NO_ERROR;
949}
950
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700951status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
952 if (enable == mInjectVSyncs) {
953 return NO_ERROR;
954 }
955
956 if (enable) {
957 mInjectVSyncs = enable;
958 ALOGV("VSync Injections enabled");
959 if (mVSyncInjector.get() == nullptr) {
960 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700961 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700962 }
963 mEventQueue.setEventThread(mInjectorEventThread);
964 } else {
965 mInjectVSyncs = enable;
966 ALOGV("VSync Injections disabled");
967 mEventQueue.setEventThread(mSFEventThread);
968 mVSyncInjector.clear();
969 }
970 return NO_ERROR;
971}
972
973status_t SurfaceFlinger::injectVSync(nsecs_t when) {
974 if (!mInjectVSyncs) {
975 ALOGE("VSync Injections not enabled");
976 return BAD_VALUE;
977 }
978 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
979 ALOGV("Injecting VSync inside SurfaceFlinger");
980 mVSyncInjector->onInjectSyncEvent(when);
981 }
982 return NO_ERROR;
983}
984
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800985// ----------------------------------------------------------------------------
986
987sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800988 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700989}
990
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800991// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800992
993void SurfaceFlinger::waitForEvent() {
994 mEventQueue.waitMessage();
995}
996
997void SurfaceFlinger::signalTransaction() {
998 mEventQueue.invalidate();
999}
1000
1001void SurfaceFlinger::signalLayerUpdate() {
1002 mEventQueue.invalidate();
1003}
1004
1005void SurfaceFlinger::signalRefresh() {
1006 mEventQueue.refresh();
1007}
1008
1009status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001010 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001011 return mEventQueue.postMessage(msg, reltime);
1012}
1013
1014status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001015 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001016 status_t res = mEventQueue.postMessage(msg, reltime);
1017 if (res == NO_ERROR) {
1018 msg->wait();
1019 }
1020 return res;
1021}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001022
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001023void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001024 do {
1025 waitForEvent();
1026 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027}
1028
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029void SurfaceFlinger::enableHardwareVsync() {
1030 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001031 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001032 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001033 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1034 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001035 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001036 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001037}
1038
Jesse Hall948fe0c2013-10-14 12:56:09 -07001039void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001040 Mutex::Autolock _l(mHWVsyncLock);
1041
Jesse Hall948fe0c2013-10-14 12:56:09 -07001042 if (makeAvailable) {
1043 mHWVsyncAvailable = true;
1044 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001045 // Hardware vsync is not currently available, so abort the resync
1046 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001047 return;
1048 }
1049
Dan Stoza9e56aa02015-11-02 13:00:03 -08001050 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1051 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001052
1053 mPrimaryDispSync.reset();
1054 mPrimaryDispSync.setPeriod(period);
1055
1056 if (!mPrimaryHWVsyncEnabled) {
1057 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001058 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1059 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001060 mPrimaryHWVsyncEnabled = true;
1061 }
1062}
1063
Jesse Hall948fe0c2013-10-14 12:56:09 -07001064void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 Mutex::Autolock _l(mHWVsyncLock);
1066 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001067 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1068 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069 mPrimaryDispSync.endResync();
1070 mPrimaryHWVsyncEnabled = false;
1071 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001072 if (makeUnavailable) {
1073 mHWVsyncAvailable = false;
1074 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075}
1076
Tim Murray4a4e4a22016-04-19 16:29:23 +00001077void SurfaceFlinger::resyncWithRateLimit() {
1078 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1079 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001080 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001081 }
1082}
1083
Steven Thomas3cfac282017-02-06 12:29:30 -08001084void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1085 nsecs_t timestamp) {
1086 Mutex::Autolock lock(mStateLock);
1087 // Ignore any vsyncs from the non-active hardware composer.
1088 if (composer != mHwc) {
1089 return;
1090 }
1091
Jamie Gennisd1700752013-10-14 12:22:52 -07001092 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093
Jamie Gennisd1700752013-10-14 12:22:52 -07001094 { // Scope for the lock
1095 Mutex::Autolock _l(mHWVsyncLock);
1096 if (type == 0 && mPrimaryHWVsyncEnabled) {
1097 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001099 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001100
1101 if (needsHwVsync) {
1102 enableHardwareVsync();
1103 } else {
1104 disableHardwareVsync(false);
1105 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001106}
1107
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001108void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1109 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1110 *compositorTiming = mCompositorTiming;
1111}
1112
Dan Stoza9e56aa02015-11-02 13:00:03 -08001113void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1114 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1115 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1116 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001117
Dan Stoza9e56aa02015-11-02 13:00:03 -08001118 // All non-virtual displays are currently considered secure.
1119 bool isSecure = true;
1120
1121 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001122
1123 // When we're using the vr composer, the assumption is that we've
1124 // already created the IBinder object for the primary display.
1125 if (!mHwc->isUsingVrComposer()) {
1126 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1127 }
1128
Dan Stoza9e56aa02015-11-02 13:00:03 -08001129 wp<IBinder> token = mBuiltinDisplays[type];
1130
1131 sp<IGraphicBufferProducer> producer;
1132 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001133 BufferQueue::createBufferQueue(&producer, &consumer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134
1135 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1136 DisplayDevice::DISPLAY_PRIMARY, consumer);
1137 sp<DisplayDevice> hw = new DisplayDevice(this,
1138 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1139 producer, mRenderEngine->getEGLConfig());
1140 mDisplays.add(token, hw);
1141 } else {
1142 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001143 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001144 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001145 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001146 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001147 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1148 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001149 }
1150 setTransactionFlags(eDisplayTransactionNeeded);
1151
Andy McFadden9e9689c2012-10-10 18:17:51 -07001152 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001153 }
Mathias Agopian86303202012-07-24 22:46:10 -07001154}
1155
Steven Thomas3cfac282017-02-06 12:29:30 -08001156void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1157 Mutex::Autolock lock(mStateLock);
1158 if (composer == mHwc) {
1159 repaintEverything();
1160 } else {
1161 // This isn't from our current hardware composer. If it's a callback
1162 // from the real composer, forward the refresh request to vr
1163 // flinger. Otherwise ignore it.
1164 if (!composer->isUsingVrComposer()) {
1165 mVrFlinger->OnHardwareComposerRefresh();
1166 }
1167 }
1168}
1169
Dan Stoza9e56aa02015-11-02 13:00:03 -08001170void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001172 getHwComposer().setVsyncEnabled(disp,
1173 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001174}
1175
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001176void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1177 for (size_t i = 0; i < layers.size(); ++i) {
1178 layers[i]->clearHwcLayers();
1179 }
1180}
1181
1182void SurfaceFlinger::resetHwc() {
1183 disableHardwareVsync(true);
1184 clearHwcLayers(mDrawingState.layersSortedByZ);
1185 clearHwcLayers(mCurrentState.layersSortedByZ);
1186 // Clear the drawing state so that the logic inside of
1187 // handleTransactionLocked will fire. It will determine the delta between
1188 // mCurrentState and mDrawingState and re-apply all changes when we make the
1189 // transition.
1190 mDrawingState.displays.clear();
1191 mDisplays.clear();
1192}
1193
1194void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001195 bool enteringVrMode = mEnterVrMode;
1196 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1197 return;
1198 }
1199 if (enteringVrMode && !mVrHwc) {
1200 // Construct new HWComposer without holding any locks.
1201 mVrHwc = new HWComposer(true);
1202 ALOGV("Vr HWC created");
1203 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001204 {
1205 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001206
1207 if (enteringVrMode) {
1208 // Start vrflinger thread, if it hasn't been started already.
1209 if (!mVrFlinger) {
1210 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1211 int err = mVrFlinger->Run(mHwc->getComposer());
1212 if (err != NO_ERROR) {
1213 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1214 mVrFlinger.reset();
1215 mEnterVrMode = false;
1216 return;
1217 }
1218 }
1219
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001220 resetHwc();
1221
1222 mHwc = mVrHwc;
1223 mVrFlinger->EnterVrMode();
1224 } else {
1225 mVrFlinger->ExitVrMode();
1226
1227 resetHwc();
1228
1229 mHwc = mRealHwc;
1230 enableHardwareVsync();
1231 }
1232
1233 mVisibleRegionsDirty = true;
1234 invalidateHwcGeometry();
1235 android_atomic_or(1, &mRepaintEverything);
1236 setTransactionFlags(eDisplayTransactionNeeded);
1237 }
1238 if (mVrHwc) {
1239 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1240 }
1241}
1242
Mathias Agopian4fec8732012-06-29 14:12:52 -07001243void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001244 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001246 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001247 // TODO(eieio): Tied to a conditional until SELinux issues
1248 // are resolved.
1249 if (mVrModeSupported) {
1250 updateVrMode();
1251 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001252
Dan Stoza50182882016-07-08 12:02:20 -07001253 bool frameMissed = !mHadClientComposition &&
1254 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001255 (mPreviousPresentFence->getSignalTime() ==
1256 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001257 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001258 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001259 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001260 signalLayerUpdate();
1261 break;
1262 }
1263
Dan Stoza6b9454d2014-11-07 16:00:59 -08001264 bool refreshNeeded = handleMessageTransaction();
1265 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001266 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001267 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001268 // Signal a refresh if a transaction modified the window state,
1269 // a new buffer was latched, or if HWC has requested a full
1270 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001271 signalRefresh();
1272 }
1273 break;
1274 }
1275 case MessageQueue::REFRESH: {
1276 handleMessageRefresh();
1277 break;
1278 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279 }
1280}
1281
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001283 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001284 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001285 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001286 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001287 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001289}
1290
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001292 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001293 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001294}
1295
1296void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001297 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001298
Pablo Ceballos40845df2016-01-25 17:41:15 -08001299 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001300
Brian Andersond6927fb2016-07-23 23:37:30 -07001301 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001302 rebuildLayerStacks();
1303 setUpHWComposer();
1304 doDebugFlashRegions();
1305 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001306 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001307
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001308 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001309
1310 mHadClientComposition = false;
1311 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1312 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1313 mHadClientComposition = mHadClientComposition ||
1314 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1315 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001316
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001318}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001319
Mathias Agopiancd60f992012-08-16 16:28:27 -07001320void SurfaceFlinger::doDebugFlashRegions()
1321{
1322 // is debugging enabled
1323 if (CC_LIKELY(!mDebugRegion))
1324 return;
1325
1326 const bool repaintEverything = mRepaintEverything;
1327 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1328 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001329 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001330 // transform the dirty region into this screen's coordinate space
1331 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1332 if (!dirtyRegion.isEmpty()) {
1333 // redraw the whole screen
1334 doComposeSurfaces(hw, Region(hw->bounds()));
1335
1336 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001337 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001338 RenderEngine& engine(getRenderEngine());
1339 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1340
Mathias Agopianda27af92012-09-13 18:17:13 -07001341 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342 }
1343 }
1344 }
1345
1346 postFramebuffer();
1347
1348 if (mDebugRegion > 1) {
1349 usleep(mDebugRegion * 1000);
1350 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001351
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001353 auto& displayDevice = mDisplays[displayId];
1354 if (!displayDevice->isDisplayOn()) {
1355 continue;
1356 }
1357
1358 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1360 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001361 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362}
1363
Brian Andersond6927fb2016-07-23 23:37:30 -07001364void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001366 ATRACE_CALL();
1367 ALOGV("preComposition");
1368
Mathias Agopiancd60f992012-08-16 16:28:27 -07001369 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001370 mDrawingState.traverseInZOrder([&](Layer* layer) {
1371 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 needExtraInvalidate = true;
1373 }
Robert Carr2047fae2016-11-28 14:09:09 -08001374 });
1375
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376 if (needExtraInvalidate) {
1377 signalLayerUpdate();
1378 }
1379}
1380
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001381void SurfaceFlinger::updateCompositorTiming(
1382 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1383 std::shared_ptr<FenceTime>& presentFenceTime) {
1384 // Update queue of past composite+present times and determine the
1385 // most recently known composite to present latency.
1386 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1387 nsecs_t compositeToPresentLatency = -1;
1388 while (!mCompositePresentTimes.empty()) {
1389 CompositePresentTime& cpt = mCompositePresentTimes.front();
1390 // Cached values should have been updated before calling this method,
1391 // which helps avoid duplicate syscalls.
1392 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1393 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1394 break;
1395 }
1396 compositeToPresentLatency = displayTime - cpt.composite;
1397 mCompositePresentTimes.pop();
1398 }
1399
1400 // Don't let mCompositePresentTimes grow unbounded, just in case.
1401 while (mCompositePresentTimes.size() > 16) {
1402 mCompositePresentTimes.pop();
1403 }
1404
1405 // Integer division and modulo round toward 0 not -inf, so we need to
1406 // treat negative and positive offsets differently.
1407 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1408 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1409 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1410
1411 // Snap the latency to a value that removes scheduling jitter from the
1412 // composition and present times, which often have >1ms of jitter.
1413 // Reducing jitter is important if an app attempts to extrapolate
1414 // something (such as user input) to an accurate diasplay time.
1415 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1416 // with (presentLatency % interval).
1417 nsecs_t snappedCompositeToPresentLatency = -1;
1418 if (compositeToPresentLatency >= 0) {
1419 nsecs_t bias = vsyncInterval / 2;
1420 int64_t extraVsyncs =
1421 (compositeToPresentLatency - idealLatency + bias) /
1422 vsyncInterval;
1423 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1424 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1425 }
1426
1427 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1428 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1429 mCompositorTiming.interval = vsyncInterval;
1430 if (snappedCompositeToPresentLatency >= 0) {
1431 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1432 }
1433}
1434
1435void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001437 ATRACE_CALL();
1438 ALOGV("postComposition");
1439
Brian Anderson3546a3f2016-07-14 11:51:14 -07001440 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001441 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001442 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001443 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001444 }
1445
Brian Andersond6927fb2016-07-23 23:37:30 -07001446 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001447
1448 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1449 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1450 glCompositionDoneFenceTime =
1451 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1452 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1453 } else {
1454 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1455 }
1456 mGlCompositionDoneTimeline.updateSignalTimes();
1457
1458 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1459 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1460 mDisplayTimeline.push(displayFenceTime);
1461 mDisplayTimeline.updateSignalTimes();
1462
1463 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1464 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1465 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1466 presentFenceTime = &displayFenceTime;
1467 } else {
1468 retireFenceTime = &displayFenceTime;
1469 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001470
1471 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1472 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1473
1474 // We use the refreshStartTime which might be sampled a little later than
1475 // when we started doing work for this frame, but that should be okay
1476 // since updateCompositorTiming has snapping logic.
1477 updateCompositorTiming(
1478 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1479
Robert Carr2047fae2016-11-28 14:09:09 -08001480 mDrawingState.traverseInZOrder([&](Layer* layer) {
1481 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001483 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001484 recordBufferingStats(layer->getName().string(),
1485 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001486 }
Robert Carr2047fae2016-11-28 14:09:09 -08001487 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001488
Brian Anderson3d4039d2016-09-23 16:31:30 -07001489 if (displayFence->isValid()) {
1490 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001491 enableHardwareVsync();
1492 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001493 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001494 }
1495 }
1496
Andy McFadden5167ec62014-05-22 13:08:43 -07001497 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001498 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001499 enableHardwareVsync();
1500 }
1501 }
1502
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001503 if (mAnimCompositionPending) {
1504 mAnimCompositionPending = false;
1505
Brian Anderson3d4039d2016-09-23 16:31:30 -07001506 if (displayFenceTime->isValid()) {
1507 mAnimFrameTracker.setActualPresentFence(
1508 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001509 } else {
1510 // The HWC doesn't support present fences, so use the refresh
1511 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001512 nsecs_t presentTime =
1513 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001514 mAnimFrameTracker.setActualPresentTime(presentTime);
1515 }
1516 mAnimFrameTracker.advanceFrame();
1517 }
Dan Stozab90cf072015-03-05 11:05:59 -08001518
1519 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1520 return;
1521 }
1522
1523 nsecs_t currentTime = systemTime();
1524 if (mHasPoweredOff) {
1525 mHasPoweredOff = false;
1526 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001527 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001529 if (numPeriods < NUM_BUCKETS - 1) {
1530 mFrameBuckets[numPeriods] += elapsedTime;
1531 } else {
1532 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1533 }
1534 mTotalTime += elapsedTime;
1535 }
1536 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001537}
1538
1539void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001540 ATRACE_CALL();
1541 ALOGV("rebuildLayerStacks");
1542
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001544 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1545 ATRACE_CALL();
1546 mVisibleRegionsDirty = false;
1547 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001548
Jeff Sharkey76488112017-02-27 14:15:18 -07001549 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1550 Region opaqueRegion;
1551 Region dirtyRegion;
1552 Vector<sp<Layer>> layersSortedByZ;
1553 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1554 const Transform& tr(displayDevice->getTransform());
1555 const Rect bounds(displayDevice->getBounds());
1556 if (displayDevice->isDisplayOn()) {
1557 computeVisibleRegions(
1558 displayDevice->getLayerStack(), dirtyRegion,
1559 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001560
Jeff Sharkey76488112017-02-27 14:15:18 -07001561 mDrawingState.traverseInZOrder([&](Layer* layer) {
1562 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1563 Region drawRegion(tr.transform(
1564 layer->visibleNonTransparentRegion));
1565 drawRegion.andSelf(bounds);
1566 if (!drawRegion.isEmpty()) {
1567 layersSortedByZ.add(layer);
1568 } else {
1569 // Clear out the HWC layer if this layer was
1570 // previously visible, but no longer is
1571 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1572 nullptr);
1573 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001574 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001575 // WM changes displayDevice->layerStack upon sleep/awake.
1576 // Here we make sure we delete the HWC layers even if
1577 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001578 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1579 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001580 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001581 });
1582 }
1583 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1584 displayDevice->undefinedRegion.set(bounds);
1585 displayDevice->undefinedRegion.subtractSelf(
1586 tr.transform(opaqueRegion));
1587 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001588 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001589 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001591
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001593 ATRACE_CALL();
1594 ALOGV("setUpHWComposer");
1595
Jesse Hall028dc8f2013-08-20 16:35:32 -07001596 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001597 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1598 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1599 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1600
1601 // If nothing has changed (!dirty), don't recompose.
1602 // If something changed, but we don't currently have any visible layers,
1603 // and didn't when we last did a composition, then skip it this time.
1604 // The second rule does two things:
1605 // - When all layers are removed from a display, we'll emit one black
1606 // frame, then nothing more until we get new layers.
1607 // - When a display is created with a private layer stack, we won't
1608 // emit any black frames until a layer is added to the layer stack.
1609 bool mustRecompose = dirty && !(empty && wasEmpty);
1610
1611 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1612 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1613 mustRecompose ? "doing" : "skipping",
1614 dirty ? "+" : "-",
1615 empty ? "+" : "-",
1616 wasEmpty ? "+" : "-");
1617
Dan Stoza71433162014-02-04 16:22:36 -08001618 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001619
1620 if (mustRecompose) {
1621 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1622 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001623 }
1624
Dan Stoza9e56aa02015-11-02 13:00:03 -08001625 // build the h/w work list
1626 if (CC_UNLIKELY(mGeometryInvalid)) {
1627 mGeometryInvalid = false;
1628 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1629 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1630 const auto hwcId = displayDevice->getHwcDisplayId();
1631 if (hwcId >= 0) {
1632 const Vector<sp<Layer>>& currentLayers(
1633 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001634 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001635 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001636 if (!layer->hasHwcLayer(hwcId)) {
1637 auto hwcLayer = mHwc->createLayer(hwcId);
1638 if (hwcLayer) {
1639 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1640 } else {
1641 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001643 }
1644 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001645
Robert Carrae060832016-11-28 10:51:00 -08001646 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001647 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001649 }
1650 }
1651 }
1652 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 }
Riley Andrews03414a12014-07-01 14:22:59 -07001654
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001655
1656 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1657
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 // Set the per-frame data
1659 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1660 auto& displayDevice = mDisplays[displayId];
1661 const auto hwcId = displayDevice->getHwcDisplayId();
1662 if (hwcId < 0) {
1663 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001664 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001665 if (colorMatrix != mPreviousColorMatrix) {
1666 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1667 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1668 "display %zd: %d", displayId, result);
1669 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1671 layer->setPerFrameData(displayDevice);
1672 }
1673 }
1674
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001675 mPreviousColorMatrix = colorMatrix;
1676
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001678 auto& displayDevice = mDisplays[displayId];
1679 if (!displayDevice->isDisplayOn()) {
1680 continue;
1681 }
1682
1683 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1685 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001686 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001688
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689void SurfaceFlinger::doComposition() {
1690 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001691 ALOGV("doComposition");
1692
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001693 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001694 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001695 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001696 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 // transform the dirty region into this screen's coordinate space
1698 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001699
1700 // repaint the framebuffer (if needed)
1701 doDisplayComposition(hw, dirtyRegion);
1702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 hw->dirtyRegion.clear();
1704 hw->flip(hw->swapRegion);
1705 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001706 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001708 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709}
1710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001711void SurfaceFlinger::postFramebuffer()
1712{
Mathias Agopian841cde52012-03-01 15:44:37 -08001713 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001714 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001715
Mathias Agopiana44b0412011-10-16 18:46:35 -07001716 const nsecs_t now = systemTime();
1717 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001718
Dan Stoza9e56aa02015-11-02 13:00:03 -08001719 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1720 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001721 if (!displayDevice->isDisplayOn()) {
1722 continue;
1723 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001724 const auto hwcId = displayDevice->getHwcDisplayId();
1725 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001726 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001727 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001728 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001729 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1731 sp<Fence> releaseFence = Fence::NO_FENCE;
1732 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1733 releaseFence = displayDevice->getClientTargetAcquireFence();
1734 } else {
1735 auto hwcLayer = layer->getHwcLayer(hwcId);
1736 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001737 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 layer->onLayerDisplayed(releaseFence);
1739 }
1740 if (hwcId >= 0) {
1741 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001742 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001743 }
1744
Mathias Agopiana44b0412011-10-16 18:46:35 -07001745 mLastSwapBufferTime = systemTime() - now;
1746 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001747
1748 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1749 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1750 logFrameStats();
1751 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001752}
1753
Mathias Agopian87baae12012-07-31 12:38:26 -07001754void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001755{
Mathias Agopian841cde52012-03-01 15:44:37 -08001756 ATRACE_CALL();
1757
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001758 // here we keep a copy of the drawing state (that is the state that's
1759 // going to be overwritten by handleTransactionLocked()) outside of
1760 // mStateLock so that the side-effects of the State assignment
1761 // don't happen with mStateLock held (which can cause deadlocks).
1762 State drawingState(mDrawingState);
1763
Mathias Agopianca4d3602011-05-19 15:38:14 -07001764 Mutex::Autolock _l(mStateLock);
1765 const nsecs_t now = systemTime();
1766 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001767
Mathias Agopianca4d3602011-05-19 15:38:14 -07001768 // Here we're guaranteed that some transaction flags are set
1769 // so we can call handleTransactionLocked() unconditionally.
1770 // We call getTransactionFlags(), which will also clear the flags,
1771 // with mStateLock held to guarantee that mCurrentState won't change
1772 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001773
Mathias Agopiane57f2922012-08-09 16:29:12 -07001774 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001775 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001776
Mathias Agopianca4d3602011-05-19 15:38:14 -07001777 mLastTransactionTime = systemTime() - now;
1778 mDebugInTransaction = 0;
1779 invalidateHwcGeometry();
1780 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001781}
1782
Mathias Agopian87baae12012-07-31 12:38:26 -07001783void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001784{
Dan Stoza7dde5992015-05-22 09:51:44 -07001785 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001786 mCurrentState.traverseInZOrder([](Layer* layer) {
1787 layer->notifyAvailableFrames();
1788 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790 /*
1791 * Traversal of the children
1792 * (perform the transaction for each of them if needed)
1793 */
1794
Mathias Agopian3559b072012-08-15 13:46:03 -07001795 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001796 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001798 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001799
1800 const uint32_t flags = layer->doTransaction(0);
1801 if (flags & Layer::eVisibleRegion)
1802 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001803 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 }
1805
1806 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001807 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001808 */
1809
Mathias Agopiane57f2922012-08-09 16:29:12 -07001810 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001811 // here we take advantage of Vector's copy-on-write semantics to
1812 // improve performance by skipping the transaction entirely when
1813 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001814 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1815 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001816 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001817 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001818 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001819 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001820
1821 // find the displays that were removed
1822 // (ie: in drawing state but not in current state)
1823 // also handle displays that changed
1824 // (ie: displays that are in both lists)
1825 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001826 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1827 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001828 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001829 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001830 // Call makeCurrent() on the primary display so we can
1831 // be sure that nothing associated with this display
1832 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001833 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001834 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001835 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1836 if (hw != NULL)
1837 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001838 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001839 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001840 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001841 } else {
1842 ALOGW("trying to remove the main display");
1843 }
1844 } else {
1845 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001846 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001847 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001848 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1849 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001850 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001851 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001852 // recreating the DisplayDevice, so we just remove it
1853 // from the drawing state, so that it get re-added
1854 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001855 sp<DisplayDevice> hw(getDisplayDevice(display));
1856 if (hw != NULL)
1857 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001858 mDisplays.removeItem(display);
1859 mDrawingState.displays.removeItemsAt(i);
1860 dc--; i--;
1861 // at this point we must loop to the next item
1862 continue;
1863 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001864
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001865 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001866 if (disp != NULL) {
1867 if (state.layerStack != draw[i].layerStack) {
1868 disp->setLayerStack(state.layerStack);
1869 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001870 if ((state.orientation != draw[i].orientation)
1871 || (state.viewport != draw[i].viewport)
1872 || (state.frame != draw[i].frame))
1873 {
1874 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001875 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001876 }
Michael Lentine47e45402014-07-18 15:34:25 -07001877 if (state.width != draw[i].width || state.height != draw[i].height) {
1878 disp->setDisplaySize(state.width, state.height);
1879 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001880 }
1881 }
1882 }
1883
1884 // find displays that were added
1885 // (ie: in current state but not in drawing state)
1886 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001887 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001888 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001889
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001890 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001891 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001892 sp<IGraphicBufferProducer> bqProducer;
1893 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001894 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001897 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001898 // Virtual displays without a surface are dormant:
1899 // they have external state (layer stack, projection,
1900 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001901 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001902
Dan Stoza8cf150a2016-08-02 10:27:31 -07001903 if (mUseHwcVirtualDisplays) {
1904 int width = 0;
1905 int status = state.surface->query(
1906 NATIVE_WINDOW_WIDTH, &width);
1907 ALOGE_IF(status != NO_ERROR,
1908 "Unable to query width (%d)", status);
1909 int height = 0;
1910 status = state.surface->query(
1911 NATIVE_WINDOW_HEIGHT, &height);
1912 ALOGE_IF(status != NO_ERROR,
1913 "Unable to query height (%d)", status);
1914 int intFormat = 0;
1915 status = state.surface->query(
1916 NATIVE_WINDOW_FORMAT, &intFormat);
1917 ALOGE_IF(status != NO_ERROR,
1918 "Unable to query format (%d)", status);
1919 auto format = static_cast<android_pixel_format_t>(
1920 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001921
Dan Stoza8cf150a2016-08-02 10:27:31 -07001922 mHwc->allocateVirtualDisplay(width, height, &format,
1923 &hwcId);
1924 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925
Dan Stoza5cf424b2016-05-20 14:02:39 -07001926 // TODO: Plumb requested format back up to consumer
1927
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 sp<VirtualDisplaySurface> vds =
1929 new VirtualDisplaySurface(*mHwc,
1930 hwcId, state.surface, bqProducer,
1931 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001932
1933 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001934 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001935 }
1936 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001937 ALOGE_IF(state.surface!=NULL,
1938 "adding a supported display, but rendering "
1939 "surface is provided (%p), ignoring it",
1940 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001941
1942 hwcId = state.type;
1943 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1944 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001945 }
1946
1947 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001948 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001949 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 state.type, hwcId, state.isSecure, display,
1951 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001952 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001953 hw->setLayerStack(state.layerStack);
1954 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001955 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001956 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001957 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001959 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001960 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001961 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001962 }
1963 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001964 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001966
Mathias Agopian84300952012-11-21 16:02:13 -08001967 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1968 // The transform hint might have changed for some layers
1969 // (either because a display has changed, or because a layer
1970 // as changed).
1971 //
1972 // Walk through all the layers in currentLayers,
1973 // and update their transform hint.
1974 //
1975 // If a layer is visible only on a single display, then that
1976 // display is used to calculate the hint, otherwise we use the
1977 // default display.
1978 //
1979 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1980 // the hint is set before we acquire a buffer from the surface texture.
1981 //
1982 // NOTE: layer transactions have taken place already, so we use their
1983 // drawing state. However, SurfaceFlinger's own transaction has not
1984 // happened yet, so we must use the current state layer list
1985 // (soon to become the drawing state list).
1986 //
1987 sp<const DisplayDevice> disp;
1988 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001989 bool first = true;
1990 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001991 // NOTE: we rely on the fact that layers are sorted by
1992 // layerStack first (so we don't have to traverse the list
1993 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001994 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001995 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001996 currentlayerStack = layerStack;
1997 // figure out if this layerstack is mirrored
1998 // (more than one display) if so, pick the default display,
1999 // if not, pick the only display it's on.
2000 disp.clear();
2001 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2002 sp<const DisplayDevice> hw(mDisplays[dpy]);
2003 if (hw->getLayerStack() == currentlayerStack) {
2004 if (disp == NULL) {
2005 disp = hw;
2006 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002007 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002008 break;
2009 }
2010 }
2011 }
2012 }
Chet Haase91d25932013-04-11 15:24:55 -07002013 if (disp == NULL) {
2014 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2015 // redraw after transform hint changes. See bug 8508397.
2016
2017 // could be null when this layer is using a layerStack
2018 // that is not visible on any display. Also can occur at
2019 // screen off/on times.
2020 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002021 }
Chet Haase91d25932013-04-11 15:24:55 -07002022 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002023
2024 first = false;
2025 });
Mathias Agopian84300952012-11-21 16:02:13 -08002026 }
2027
2028
Mathias Agopian3559b072012-08-15 13:46:03 -07002029 /*
2030 * Perform our own transaction if needed
2031 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002032
2033 if (mLayersAdded) {
2034 mLayersAdded = false;
2035 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002036 mVisibleRegionsDirty = true;
2037 }
2038
2039 // some layers might have been removed, so
2040 // we need to update the regions they're exposing.
2041 if (mLayersRemoved) {
2042 mLayersRemoved = false;
2043 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002044 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002045 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002046 // this layer is not visible anymore
2047 // TODO: we could traverse the tree from front to back and
2048 // compute the actual visible region
2049 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002050 Region visibleReg;
2051 visibleReg.set(layer->computeScreenBounds());
2052 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002053 }
Robert Carr2047fae2016-11-28 14:09:09 -08002054 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 }
2056
2057 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002058
2059 updateCursorAsync();
2060}
2061
2062void SurfaceFlinger::updateCursorAsync()
2063{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2065 auto& displayDevice = mDisplays[displayId];
2066 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002067 continue;
2068 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069
2070 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2071 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002072 }
2073 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002074}
2075
2076void SurfaceFlinger::commitTransaction()
2077{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002078 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002079 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002080 for (const auto& l : mLayersPendingRemoval) {
2081 recordBufferingStats(l->getName().string(),
2082 l->getOccupancyHistory(true));
2083 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084 }
2085 mLayersPendingRemoval.clear();
2086 }
2087
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088 // If this transaction is part of a window animation then the next frame
2089 // we composite should be considered an animation as well.
2090 mAnimCompositionPending = mAnimTransactionPending;
2091
Mathias Agopian4fec8732012-06-29 14:12:52 -07002092 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002093 mDrawingState.traverseInZOrder([](Layer* layer) {
2094 layer->commitChildList();
2095 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002096 mTransactionPending = false;
2097 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099}
2100
Robert Carr2047fae2016-11-28 14:09:09 -08002101void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103{
Mathias Agopian841cde52012-03-01 15:44:37 -08002104 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002107 Region aboveOpaqueLayers;
2108 Region aboveCoveredLayers;
2109 Region dirty;
2110
Mathias Agopian87baae12012-07-31 12:38:26 -07002111 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112
Robert Carr2047fae2016-11-28 14:09:09 -08002113 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002115 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116
Jesse Hall01e29052013-02-19 16:13:35 -08002117 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002118 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002119 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002120
Mathias Agopianab028732010-03-16 16:41:46 -07002121 /*
2122 * opaqueRegion: area of a surface that is fully opaque.
2123 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002125
2126 /*
2127 * visibleRegion: area of a surface that is visible on screen
2128 * and not fully transparent. This is essentially the layer's
2129 * footprint minus the opaque regions above it.
2130 * Areas covered by a translucent surface are considered visible.
2131 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002133
2134 /*
2135 * coveredRegion: area of a surface that is covered by all
2136 * visible regions above it (which includes the translucent areas).
2137 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002139
Jesse Halla8026d22012-09-25 13:25:04 -07002140 /*
2141 * transparentRegion: area of a surface that is hinted to be completely
2142 * transparent. This is only used to tell when the layer has no visible
2143 * non-transparent regions and can be removed from the layer list. It
2144 * does not affect the visibleRegion of this layer or any layers
2145 * beneath it. The hint may not be correct if apps don't respect the
2146 * SurfaceView restrictions (which, sadly, some don't).
2147 */
2148 Region transparentRegion;
2149
Mathias Agopianab028732010-03-16 16:41:46 -07002150
2151 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002152 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002153 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002154 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002156 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002157 if (!visibleRegion.isEmpty()) {
2158 // Remove the transparent area from the visible region
2159 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002160 if (tr.preserveRects()) {
2161 // transform the transparent region
2162 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002163 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002164 // transformation too complex, can't do the
2165 // transparent region optimization.
2166 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002167 }
Mathias Agopianab028732010-03-16 16:41:46 -07002168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169
Mathias Agopianab028732010-03-16 16:41:46 -07002170 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002171 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002173 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2174 // the opaque region is the layer's footprint
2175 opaqueRegion = visibleRegion;
2176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177 }
2178 }
2179
Mathias Agopianab028732010-03-16 16:41:46 -07002180 // Clip the covered region to the visible region
2181 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2182
2183 // Update aboveCoveredLayers for next (lower) layer
2184 aboveCoveredLayers.orSelf(visibleRegion);
2185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186 // subtract the opaque region covered by the layers above us
2187 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188
2189 // compute this layer's dirty region
2190 if (layer->contentDirty) {
2191 // we need to invalidate the whole region
2192 dirty = visibleRegion;
2193 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002194 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002195 layer->contentDirty = false;
2196 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002197 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002198 * the exposed region consists of two components:
2199 * 1) what's VISIBLE now and was COVERED before
2200 * 2) what's EXPOSED now less what was EXPOSED before
2201 *
2202 * note that (1) is conservative, we start with the whole
2203 * visible region but only keep what used to be covered by
2204 * something -- which mean it may have been exposed.
2205 *
2206 * (2) handles areas that were not covered by anything but got
2207 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002208 */
Mathias Agopianab028732010-03-16 16:41:46 -07002209 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002210 const Region oldVisibleRegion = layer->visibleRegion;
2211 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002212 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2213 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214 }
2215 dirty.subtractSelf(aboveOpaqueLayers);
2216
2217 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002218 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219
Mathias Agopianab028732010-03-16 16:41:46 -07002220 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002222
Jesse Halla8026d22012-09-25 13:25:04 -07002223 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224 layer->setVisibleRegion(visibleRegion);
2225 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002226 layer->setVisibleNonTransparentRegion(
2227 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002228 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229
Mathias Agopian87baae12012-07-31 12:38:26 -07002230 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231}
2232
Mathias Agopian87baae12012-07-31 12:38:26 -07002233void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2234 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002235 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002236 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2237 if (hw->getLayerStack() == layerStack) {
2238 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002239 }
2240 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002241}
2242
Dan Stoza6b9454d2014-11-07 16:00:59 -08002243bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002245 ALOGV("handlePageFlip");
2246
Brian Andersond6927fb2016-07-23 23:37:30 -07002247 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248
Mathias Agopian4fec8732012-06-29 14:12:52 -07002249 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002250 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002251
2252 // Store the set of layers that need updates. This set must not change as
2253 // buffers are being latched, as this could result in a deadlock.
2254 // Example: Two producers share the same command stream and:
2255 // 1.) Layer 0 is latched
2256 // 2.) Layer 0 gets a new frame
2257 // 2.) Layer 1 gets a new frame
2258 // 3.) Layer 1 is latched.
2259 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2260 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002261 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002262 if (layer->hasQueuedFrame()) {
2263 frameQueued = true;
2264 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002265 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002266 } else {
2267 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002268 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002269 } else {
2270 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002271 }
Robert Carr2047fae2016-11-28 14:09:09 -08002272 });
2273
Dan Stoza9e56aa02015-11-02 13:00:03 -08002274 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002275 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002276 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002278 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002279
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002280 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002281
2282 // If we will need to wake up at some time in the future to deal with a
2283 // queued frame that shouldn't be displayed during this vsync period, wake
2284 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002285 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286 signalLayerUpdate();
2287 }
2288
2289 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291}
2292
Mathias Agopianad456f92011-01-13 17:53:01 -08002293void SurfaceFlinger::invalidateHwcGeometry()
2294{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002295 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002296}
2297
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002298
Fabien Sanglard830b8472016-11-30 16:35:58 -08002299void SurfaceFlinger::doDisplayComposition(
2300 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002301 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302{
Dan Stoza71433162014-02-04 16:22:36 -08002303 // We only need to actually compose the display if:
2304 // 1) It is being handled by hardware composer, which may need this to
2305 // keep its virtual display state machine in sync, or
2306 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002307 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002308 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002310 return;
2311 }
2312
Dan Stoza9e56aa02015-11-02 13:00:03 -08002313 ALOGV("doDisplayComposition");
2314
Mathias Agopian87baae12012-07-31 12:38:26 -07002315 Region dirtyRegion(inDirtyRegion);
2316
Mathias Agopianb8a55602009-06-26 19:06:36 -07002317 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002318 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Fabien Sanglard830b8472016-11-30 16:35:58 -08002320 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002321 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002322 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2323 // takes a rectangle, we must make sure to update that whole
2324 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002325 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002326 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002327 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002328 // We need to redraw the rectangle that will be updated
2329 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002330 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002331 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002333 } else {
2334 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002335 dirtyRegion.set(displayDevice->bounds());
2336 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 }
2338 }
2339
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002342 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002343 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002344
2345 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002346 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347}
2348
Dan Stoza9e56aa02015-11-02 13:00:03 -08002349bool SurfaceFlinger::doComposeSurfaces(
2350 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002351{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002352 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002353
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002355
2356 mat4 oldColorMatrix;
2357 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2358 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2359 if (applyColorMatrix) {
2360 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2361 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2362 }
2363
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2365 if (hasClientComposition) {
2366 ALOGV("hasClientComposition");
2367
2368 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002369 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002370 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002371 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2372 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2373 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2374 }
2375 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002376 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002377
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002378 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002379 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2380 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002381 // when using overlays, we assume a fully transparent framebuffer
2382 // NOTE: we could reduce how much we need to clear, for instance
2383 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002384 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002385 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002386 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002387 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002388 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002389 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002390
2391 // we remove the scissor part
2392 // we're left with the letterbox region
2393 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002395
2396 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002397 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002398
2399 // but limit it to the dirty region
2400 region.andSelf(dirty);
2401
Mathias Agopianb9494d52012-04-18 02:28:45 -07002402 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002403 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002404 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002406 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002407 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002408
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002410 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002411 // scissor on the main display. It should never be needed
2412 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 const Rect& bounds(displayDevice->getBounds());
2414 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002415 if (scissor != bounds) {
2416 // scissor doesn't match the screen's dimensions, so we
2417 // need to clear everything outside of it and enable
2418 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002419
Mathias Agopianf45c5102012-10-24 16:29:17 -07002420 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 const uint32_t height = displayDevice->getHeight();
2422 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002423 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002424 }
2425 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002426 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002427
Mathias Agopian85d751c2012-08-29 16:59:24 -07002428 /*
2429 * and then, render the layers targeted at the framebuffer
2430 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002431
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 ALOGV("Rendering client layers");
2433 const Transform& displayTransform = displayDevice->getTransform();
2434 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002435 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 bool firstLayer = true;
2437 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2438 const Region clip(dirty.intersect(
2439 displayTransform.transform(layer->visibleRegion)));
2440 ALOGV("Layer: %s", layer->getName().string());
2441 ALOGV(" Composition type: %s",
2442 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002443 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 switch (layer->getCompositionType(hwcId)) {
2445 case HWC2::Composition::Cursor:
2446 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002447 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002449 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2451 layer->isOpaque(state) && (state.alpha == 1.0f)
2452 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002453 // never clear the very first layer since we're
2454 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002455 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002456 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002457 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002458 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 case HWC2::Composition::Client: {
2460 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002461 break;
2462 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002464 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002465 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 } else {
2467 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002468 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002470 }
2471 } else {
2472 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002474 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002476 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002478 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002479 }
2480 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002481
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002482 if (applyColorMatrix) {
2483 getRenderEngine().setupColorTransform(oldColorMatrix);
2484 }
2485
Mathias Agopianf45c5102012-10-24 16:29:17 -07002486 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002488 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489}
2490
Fabien Sanglard830b8472016-11-30 16:35:58 -08002491void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2492 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002493 RenderEngine& engine(getRenderEngine());
2494 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495}
2496
Dan Stoza7d89d062015-04-30 13:29:25 -07002497status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002498 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002499 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002500 const sp<Layer>& lbc,
2501 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002502{
Dan Stoza7d89d062015-04-30 13:29:25 -07002503 // add this layer to the current state list
2504 {
2505 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002506 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002507 return NO_MEMORY;
2508 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 if (parent == nullptr) {
2510 mCurrentState.layersSortedByZ.add(lbc);
2511 } else {
2512 parent->addChild(lbc);
2513 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002514 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515 mLayersAdded = true;
2516 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002517 }
2518
Mathias Agopian96f08192010-06-02 23:28:45 -07002519 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002520 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002521
Dan Stoza7d89d062015-04-30 13:29:25 -07002522 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002523}
2524
Robert Carr9524cb32017-02-13 11:32:32 -08002525status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002526 Mutex::Autolock _l(mStateLock);
2527
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 const auto& p = layer->getParent();
2529 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2530 mCurrentState.layersSortedByZ.remove(layer);
2531
Robert Carr136e2f62017-02-08 17:54:29 -08002532 // As a matter of normal operation, the LayerCleaner will produce a second
2533 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2534 // so we will succeed in promoting it, but it's already been removed
2535 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2536 // otherwise something has gone wrong and we are leaking the layer.
2537 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2539 layer->getName().string(),
2540 (p != nullptr) ? p->getName().string() : "no-parent");
2541 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002542 } else if (index < 0) {
2543 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002544 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545
2546 mLayersPendingRemoval.add(layer);
2547 mLayersRemoved = true;
2548 mNumLayers--;
2549 setTransactionFlags(eTransactionNeeded);
2550 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551}
2552
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002553uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002554 return android_atomic_release_load(&mTransactionFlags);
2555}
2556
Mathias Agopian3f844832013-08-07 21:24:32 -07002557uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2559}
2560
Mathias Agopian3f844832013-08-07 21:24:32 -07002561uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2563 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002564 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 }
2566 return old;
2567}
2568
Mathias Agopian8b33f032012-07-24 20:43:54 -07002569void SurfaceFlinger::setTransactionState(
2570 const Vector<ComposerState>& state,
2571 const Vector<DisplayState>& displays,
2572 uint32_t flags)
2573{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002574 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002575 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002576 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002577
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002578 if (flags & eAnimation) {
2579 // For window updates that are part of an animation we must wait for
2580 // previous animation "frames" to be handled.
2581 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002582 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002583 if (CC_UNLIKELY(err != NO_ERROR)) {
2584 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002585 // caller after a few seconds.
2586 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2587 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002588 mAnimTransactionPending = false;
2589 break;
2590 }
2591 }
2592 }
2593
Mathias Agopiane57f2922012-08-09 16:29:12 -07002594 size_t count = displays.size();
2595 for (size_t i=0 ; i<count ; i++) {
2596 const DisplayState& s(displays[i]);
2597 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002598 }
2599
Mathias Agopiane57f2922012-08-09 16:29:12 -07002600 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002601 for (size_t i=0 ; i<count ; i++) {
2602 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002603 // Here we need to check that the interface we're given is indeed
2604 // one of our own. A malicious client could give us a NULL
2605 // IInterface, or one of its own or even one of our own but a
2606 // different type. All these situations would cause us to crash.
2607 //
2608 // NOTE: it would be better to use RTTI as we could directly check
2609 // that we have a Client*. however, RTTI is disabled in Android.
2610 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002611 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002612 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002613 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002614 sp<Client> client( static_cast<Client *>(s.client.get()) );
2615 transactionFlags |= setClientStateLocked(client, s.state);
2616 }
2617 }
2618 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002619 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002620
Robert Carr2a7dbb42016-05-24 11:41:28 -07002621 // If a synchronous transaction is explicitly requested without any changes,
2622 // force a transaction anyway. This can be used as a flush mechanism for
2623 // previous async transactions.
2624 if (transactionFlags == 0 && (flags & eSynchronous)) {
2625 transactionFlags = eTransactionNeeded;
2626 }
2627
Mathias Agopian386aa982011-11-07 21:58:03 -08002628 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002629 if (mInterceptor.isEnabled()) {
2630 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2631 }
Irvel468051e2016-06-13 16:44:44 -07002632
Mathias Agopian386aa982011-11-07 21:58:03 -08002633 // this triggers the transaction
2634 setTransactionFlags(transactionFlags);
2635
2636 // if this is a synchronous transaction, wait for it to take effect
2637 // before returning.
2638 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002639 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002640 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002641 if (flags & eAnimation) {
2642 mAnimTransactionPending = true;
2643 }
2644 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002645 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2646 if (CC_UNLIKELY(err != NO_ERROR)) {
2647 // just in case something goes wrong in SF, return to the
2648 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002649 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2650 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002651 break;
2652 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 }
2655}
2656
Mathias Agopiane57f2922012-08-09 16:29:12 -07002657uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2658{
Jesse Hall9a143922012-10-04 16:29:19 -07002659 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2660 if (dpyIdx < 0)
2661 return 0;
2662
Mathias Agopiane57f2922012-08-09 16:29:12 -07002663 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002664 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002665 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002666 const uint32_t what = s.what;
2667 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002668 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669 disp.surface = s.surface;
2670 flags |= eDisplayTransactionNeeded;
2671 }
2672 }
2673 if (what & DisplayState::eLayerStackChanged) {
2674 if (disp.layerStack != s.layerStack) {
2675 disp.layerStack = s.layerStack;
2676 flags |= eDisplayTransactionNeeded;
2677 }
2678 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002679 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002680 if (disp.orientation != s.orientation) {
2681 disp.orientation = s.orientation;
2682 flags |= eDisplayTransactionNeeded;
2683 }
2684 if (disp.frame != s.frame) {
2685 disp.frame = s.frame;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 if (disp.viewport != s.viewport) {
2689 disp.viewport = s.viewport;
2690 flags |= eDisplayTransactionNeeded;
2691 }
2692 }
Michael Lentine47e45402014-07-18 15:34:25 -07002693 if (what & DisplayState::eDisplaySizeChanged) {
2694 if (disp.width != s.width) {
2695 disp.width = s.width;
2696 flags |= eDisplayTransactionNeeded;
2697 }
2698 if (disp.height != s.height) {
2699 disp.height = s.height;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002703 }
2704 return flags;
2705}
2706
2707uint32_t SurfaceFlinger::setClientStateLocked(
2708 const sp<Client>& client,
2709 const layer_state_t& s)
2710{
2711 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002712 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713 if (layer != 0) {
2714 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002715 bool geometryAppliesWithResize =
2716 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002717 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002718 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002719 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002720 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002721 }
2722 if (what & layer_state_t::eLayerChanged) {
2723 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 const auto& p = layer->getParent();
2725 if (p == nullptr) {
2726 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2727 if (layer->setLayer(s.z) && idx >= 0) {
2728 mCurrentState.layersSortedByZ.removeAt(idx);
2729 mCurrentState.layersSortedByZ.add(layer);
2730 // we need traversal (state changed)
2731 // AND transaction (list changed)
2732 flags |= eTransactionNeeded|eTraversalNeeded;
2733 }
2734 } else {
2735 if (p->setChildLayer(layer, s.z)) {
2736 flags |= eTransactionNeeded|eTraversalNeeded;
2737 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 }
2739 }
2740 if (what & layer_state_t::eSizeChanged) {
2741 if (layer->setSize(s.w, s.h)) {
2742 flags |= eTraversalNeeded;
2743 }
2744 }
2745 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002747 flags |= eTraversalNeeded;
2748 }
2749 if (what & layer_state_t::eMatrixChanged) {
2750 if (layer->setMatrix(s.matrix))
2751 flags |= eTraversalNeeded;
2752 }
2753 if (what & layer_state_t::eTransparentRegionChanged) {
2754 if (layer->setTransparentRegionHint(s.transparentRegion))
2755 flags |= eTraversalNeeded;
2756 }
Dan Stoza23116082015-06-18 14:58:39 -07002757 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002758 if (layer->setFlags(s.flags, s.mask))
2759 flags |= eTraversalNeeded;
2760 }
2761 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002762 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 flags |= eTraversalNeeded;
2764 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002765 if (what & layer_state_t::eFinalCropChanged) {
2766 if (layer->setFinalCrop(s.finalCrop))
2767 flags |= eTraversalNeeded;
2768 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002769 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002770 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 // We only allow setting layer stacks for top level layers,
2772 // everything else inherits layer stack from its parent.
2773 if (layer->hasParent()) {
2774 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2775 layer->getName().string());
2776 } else if (idx < 0) {
2777 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2778 "that also does not appear in the top level layer list. Something"
2779 " has gone wrong.", layer->getName().string());
2780 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002781 mCurrentState.layersSortedByZ.removeAt(idx);
2782 mCurrentState.layersSortedByZ.add(layer);
2783 // we need traversal (state changed)
2784 // AND transaction (list changed)
2785 flags |= eTransactionNeeded|eTraversalNeeded;
2786 }
2787 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002788 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002789 if (s.barrierHandle != nullptr) {
2790 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2791 } else if (s.barrierGbp != nullptr) {
2792 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2793 if (authenticateSurfaceTextureLocked(gbp)) {
2794 const auto& otherLayer =
2795 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2796 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2797 } else {
2798 ALOGE("Attempt to defer transaction to to an"
2799 " unrecognized GraphicBufferProducer");
2800 }
2801 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002802 // We don't trigger a traversal here because if no other state is
2803 // changed, we don't want this to cause any more work
2804 }
Robert Carr1db73f62016-12-21 12:58:51 -08002805 if (what & layer_state_t::eReparentChildren) {
2806 if (layer->reparentChildren(s.reparentHandle)) {
2807 flags |= eTransactionNeeded|eTraversalNeeded;
2808 }
2809 }
Robert Carr9524cb32017-02-13 11:32:32 -08002810 if (what & layer_state_t::eDetachChildren) {
2811 layer->detachChildren();
2812 }
Robert Carrc3574f72016-03-24 12:19:32 -07002813 if (what & layer_state_t::eOverrideScalingModeChanged) {
2814 layer->setOverrideScalingMode(s.overrideScalingMode);
2815 // We don't trigger a traversal here because if no other state is
2816 // changed, we don't want this to cause any more work
2817 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002818 }
2819 return flags;
2820}
2821
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002822status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002823 const String8& name,
2824 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002825 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002826 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2827 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002829 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002830 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002831 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002832 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002833 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002834
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002835 status_t result = NO_ERROR;
2836
2837 sp<Layer> layer;
2838
Mathias Agopian3165cc22012-08-08 19:42:09 -07002839 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2840 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002841 result = createNormalLayer(client,
2842 name, w, h, flags, format,
2843 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002845 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002846 result = createDimLayer(client,
2847 name, w, h, flags,
2848 handle, gbp, &layer);
2849 break;
2850 default:
2851 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 break;
2853 }
2854
Dan Stoza7d89d062015-04-30 13:29:25 -07002855 if (result != NO_ERROR) {
2856 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002858
Albert Chaulk479c60c2017-01-27 14:21:34 -05002859 layer->setInfo(windowType, ownerUid);
2860
Robert Carr1f0a16a2016-10-24 16:27:39 -07002861 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002862 if (result != NO_ERROR) {
2863 return result;
2864 }
Irvelffc9efc2016-07-27 15:16:37 -07002865 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002866
2867 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002868 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869}
2870
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002871status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2872 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2873 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874{
2875 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002876 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 case PIXEL_FORMAT_TRANSPARENT:
2878 case PIXEL_FORMAT_TRANSLUCENT:
2879 format = PIXEL_FORMAT_RGBA_8888;
2880 break;
2881 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002882 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 break;
2884 }
2885
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002886 *outLayer = new Layer(this, client, name, w, h, flags);
2887 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2888 if (err == NO_ERROR) {
2889 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002890 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002892
2893 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2894 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895}
2896
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002897status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2898 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2899 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002901 *outLayer = new LayerDim(this, client, name, w, h, flags);
2902 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002903 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002904 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002905}
2906
Mathias Agopianac9fa422013-02-11 16:40:36 -08002907status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908{
Robert Carr9524cb32017-02-13 11:32:32 -08002909 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002910 status_t err = NO_ERROR;
2911 sp<Layer> l(client->getLayerUser(handle));
2912 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002913 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002914 err = removeLayer(l);
2915 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2916 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002917 }
2918 return err;
2919}
2920
Mathias Agopian13127d82013-03-05 17:47:11 -08002921status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002922{
Mathias Agopian67106042013-03-14 19:18:13 -07002923 // called by ~LayerCleaner() when all references to the IBinder (handle)
2924 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002925 sp<Layer> l = layer.promote();
2926 if (l == nullptr) {
2927 // The layer has already been removed, carry on
2928 return NO_ERROR;
2929 } if (l->getParent() != nullptr) {
2930 // If we have a parent, then we can continue to live as long as it does.
2931 return NO_ERROR;
2932 }
2933 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934}
2935
Mathias Agopianb60314a2012-04-10 22:09:54 -07002936// ---------------------------------------------------------------------------
2937
Andy McFadden13a082e2012-08-24 10:16:42 -07002938void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002939 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002940 Vector<ComposerState> state;
2941 Vector<DisplayState> displays;
2942 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002943 d.what = DisplayState::eDisplayProjectionChanged |
2944 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002945 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002946 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002947 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002948 d.frame.makeInvalid();
2949 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002950 d.width = 0;
2951 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002952 displays.add(d);
2953 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002954 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002955
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2957 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002958 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002959
2960 {
2961 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2962 mCompositorTiming.interval = period;
2963 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002964}
2965
2966void SurfaceFlinger::initializeDisplays() {
2967 class MessageScreenInitialized : public MessageBase {
2968 SurfaceFlinger* flinger;
2969 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002970 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002971 virtual bool handler() {
2972 flinger->onInitializeDisplays();
2973 return true;
2974 }
2975 };
2976 sp<MessageBase> msg = new MessageScreenInitialized(this);
2977 postMessageAsync(msg); // we may be called from main thread, use async message
2978}
2979
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002980void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2981 int mode) {
2982 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2983 this);
2984 int32_t type = hw->getDisplayType();
2985 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002986
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002987 if (mode == currentMode) {
2988 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002989 return;
2990 }
2991
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002992 hw->setPowerMode(mode);
2993 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2994 ALOGW("Trying to set power mode for virtual display");
2995 return;
2996 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002997
Irvelffc9efc2016-07-27 15:16:37 -07002998 if (mInterceptor.isEnabled()) {
2999 Mutex::Autolock _l(mStateLock);
3000 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3001 if (idx < 0) {
3002 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3003 return;
3004 }
3005 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3006 }
3007
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003008 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003009 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003010 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003011 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3012 // FIXME: eventthread only knows about the main display right now
3013 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003014 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003015 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003017 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003018 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003019 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003020
3021 struct sched_param param = {0};
3022 param.sched_priority = 1;
3023 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3024 ALOGW("Couldn't set SCHED_FIFO on display on");
3025 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003026 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003027 // Turn off the display
3028 struct sched_param param = {0};
3029 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3030 ALOGW("Couldn't set SCHED_OTHER on display off");
3031 }
3032
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003034 disableHardwareVsync(true); // also cancels any in-progress resync
3035
Mathias Agopiancde87a32012-09-13 14:09:01 -07003036 // FIXME: eventthread only knows about the main display right now
3037 mEventThread->onScreenReleased();
3038 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003039
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 getHwComposer().setPowerMode(type, mode);
3041 mVisibleRegionsDirty = true;
3042 // from this point on, SF will stop drawing on this display
3043 } else {
3044 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003045 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003046}
3047
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3049 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003050 SurfaceFlinger& mFlinger;
3051 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003052 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003053 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003054 MessageSetPowerMode(SurfaceFlinger& flinger,
3055 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3056 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003057 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003058 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003059 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003060 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003061 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003062 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003063 ALOGW("Attempt to set power mode = %d for virtual display",
3064 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003065 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003066 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003067 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003068 return true;
3069 }
3070 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003071 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003072 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003073}
3074
3075// ---------------------------------------------------------------------------
3076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3078{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003080
Mathias Agopianbd115332013-04-18 16:41:04 -07003081 IPCThreadState* ipc = IPCThreadState::self();
3082 const int pid = ipc->getCallingPid();
3083 const int uid = ipc->getCallingUid();
3084 if ((uid != AID_SHELL) &&
3085 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003086 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003087 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003089 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003090 // (this would indicate SF is stuck, but we want to be able to
3091 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003092 status_t err = mStateLock.timedLock(s2ns(1));
3093 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003094 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003095 result.appendFormat(
3096 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3097 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003098 }
3099
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003100 bool dumpAll = true;
3101 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003102 size_t numArgs = args.size();
3103 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003104 if ((index < numArgs) &&
3105 (args[index] == String16("--list"))) {
3106 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003107 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003108 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003109 }
3110
3111 if ((index < numArgs) &&
3112 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003113 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003114 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003115 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003116 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003117
3118 if ((index < numArgs) &&
3119 (args[index] == String16("--latency-clear"))) {
3120 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003121 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003122 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003123 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003124
3125 if ((index < numArgs) &&
3126 (args[index] == String16("--dispsync"))) {
3127 index++;
3128 mPrimaryDispSync.dump(result);
3129 dumpAll = false;
3130 }
Dan Stozab90cf072015-03-05 11:05:59 -08003131
3132 if ((index < numArgs) &&
3133 (args[index] == String16("--static-screen"))) {
3134 index++;
3135 dumpStaticScreenStats(result);
3136 dumpAll = false;
3137 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003138
3139 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003140 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003141 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003142 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003143 dumpAll = false;
3144 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003147 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003148 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003149 }
3150
Mathias Agopian9795c422009-08-26 16:36:26 -07003151 if (locked) {
3152 mStateLock.unlock();
3153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
3155 write(fd, result.string(), result.size());
3156 return NO_ERROR;
3157}
3158
Dan Stozac7014012014-02-14 15:03:43 -08003159void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3160 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003161{
Robert Carr2047fae2016-11-28 14:09:09 -08003162 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003163 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003164 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003165}
3166
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003167void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003168 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003169{
3170 String8 name;
3171 if (index < args.size()) {
3172 name = String8(args[index]);
3173 index++;
3174 }
3175
Dan Stoza9e56aa02015-11-02 13:00:03 -08003176 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3177 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003178 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003179
3180 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003181 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003182 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003183 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003184 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003185 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003186 }
Robert Carr2047fae2016-11-28 14:09:09 -08003187 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003188 }
3189}
3190
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003191void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003192 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003193{
3194 String8 name;
3195 if (index < args.size()) {
3196 name = String8(args[index]);
3197 index++;
3198 }
3199
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003201 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003202 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003203 }
Robert Carr2047fae2016-11-28 14:09:09 -08003204 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003205
Svetoslavd85084b2014-03-20 10:28:31 -07003206 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003207}
3208
Jamie Gennis6547ff42013-07-16 20:12:42 -07003209// This should only be called from the main thread. Otherwise it would need
3210// the lock and should use mCurrentState rather than mDrawingState.
3211void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003212 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003213 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003214 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003215
3216 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3217}
3218
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003220{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003221 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003222 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3223
Andy McFadden4803b742012-09-24 19:07:20 -07003224#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003225 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003226#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003227 if (isLayerTripleBufferingDisabled())
3228 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003229 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003230}
3231
Dan Stozab90cf072015-03-05 11:05:59 -08003232void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3233{
3234 result.appendFormat("Static screen stats:\n");
3235 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3236 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3237 float percent = 100.0f *
3238 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3239 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3240 b + 1, bucketTimeSec, percent);
3241 }
3242 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3243 float percent = 100.0f *
3244 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3245 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3246 NUM_BUCKETS - 1, bucketTimeSec, percent);
3247}
3248
Dan Stozae77c7662016-05-13 11:37:28 -07003249void SurfaceFlinger::recordBufferingStats(const char* layerName,
3250 std::vector<OccupancyTracker::Segment>&& history) {
3251 Mutex::Autolock lock(mBufferingStatsMutex);
3252 auto& stats = mBufferingStats[layerName];
3253 for (const auto& segment : history) {
3254 if (!segment.usedThirdBuffer) {
3255 stats.twoBufferTime += segment.totalTime;
3256 }
3257 if (segment.occupancyAverage < 1.0f) {
3258 stats.doubleBufferedTime += segment.totalTime;
3259 } else if (segment.occupancyAverage < 2.0f) {
3260 stats.tripleBufferedTime += segment.totalTime;
3261 }
3262 ++stats.numSegments;
3263 stats.totalTime += segment.totalTime;
3264 }
3265}
3266
Brian Andersond6927fb2016-07-23 23:37:30 -07003267void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3268 result.appendFormat("Layer frame timestamps:\n");
3269
3270 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3271 const size_t count = currentLayers.size();
3272 for (size_t i=0 ; i<count ; i++) {
3273 currentLayers[i]->dumpFrameEvents(result);
3274 }
3275}
3276
Dan Stozae77c7662016-05-13 11:37:28 -07003277void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3278 result.append("Buffering stats:\n");
3279 result.append(" [Layer name] <Active time> <Two buffer> "
3280 "<Double buffered> <Triple buffered>\n");
3281 Mutex::Autolock lock(mBufferingStatsMutex);
3282 typedef std::tuple<std::string, float, float, float> BufferTuple;
3283 std::map<float, BufferTuple, std::greater<float>> sorted;
3284 for (const auto& statsPair : mBufferingStats) {
3285 const char* name = statsPair.first.c_str();
3286 const BufferingStats& stats = statsPair.second;
3287 if (stats.numSegments == 0) {
3288 continue;
3289 }
3290 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3291 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3292 stats.totalTime;
3293 float doubleBufferRatio = static_cast<float>(
3294 stats.doubleBufferedTime) / stats.totalTime;
3295 float tripleBufferRatio = static_cast<float>(
3296 stats.tripleBufferedTime) / stats.totalTime;
3297 sorted.insert({activeTime, {name, twoBufferRatio,
3298 doubleBufferRatio, tripleBufferRatio}});
3299 }
3300 for (const auto& sortedPair : sorted) {
3301 float activeTime = sortedPair.first;
3302 const BufferTuple& values = sortedPair.second;
3303 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3304 std::get<0>(values).c_str(), activeTime,
3305 std::get<1>(values), std::get<2>(values),
3306 std::get<3>(values));
3307 }
3308 result.append("\n");
3309}
3310
3311
Mathias Agopian74d211a2013-04-22 16:55:35 +02003312void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3313 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003315 bool colorize = false;
3316 if (index < args.size()
3317 && (args[index] == String16("--color"))) {
3318 colorize = true;
3319 index++;
3320 }
3321
3322 Colorizer colorizer(colorize);
3323
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003324 // figure out if we're stuck somewhere
3325 const nsecs_t now = systemTime();
3326 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3327 const nsecs_t inTransaction(mDebugInTransaction);
3328 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3329 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3330
3331 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003332 * Dump library configuration.
3333 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003334
3335 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003336 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003337 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003338 appendSfConfigString(result);
3339 appendUiConfigString(result);
3340 appendGuiConfigString(result);
3341 result.append("\n");
3342
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003343 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003344 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003345 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003346 result.append(SyncFeatures::getInstance().toString());
3347 result.append("\n");
3348
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3350
Andy McFadden41d67d72014-04-25 16:58:34 -07003351 colorizer.bold(result);
3352 result.append("DispSync configuration: ");
3353 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003354 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3355 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003356 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3357 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003358 result.append("\n");
3359
Dan Stozab90cf072015-03-05 11:05:59 -08003360 // Dump static screen stats
3361 result.append("\n");
3362 dumpStaticScreenStats(result);
3363 result.append("\n");
3364
Dan Stozae77c7662016-05-13 11:37:28 -07003365 dumpBufferingStats(result);
3366
Andy McFadden4803b742012-09-24 19:07:20 -07003367 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003368 * Dump the visible layer list
3369 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003371 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003372 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003373 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003374 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003375 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003376
3377 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003378 * Dump Display state
3379 */
3380
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003382 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003384 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3385 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003386 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003387 }
3388
3389 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390 * Dump SurfaceFlinger global state
3391 */
3392
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003393 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003394 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003395 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003396
Mathias Agopian888c8222012-08-04 21:10:38 -07003397 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003398 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003399
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003400 colorizer.bold(result);
3401 result.appendFormat("EGL implementation : %s\n",
3402 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3403 colorizer.reset(result);
3404 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003405 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003406
Mathias Agopian875d8e12013-06-07 15:35:48 -07003407 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003408
Mathias Agopian42977342012-08-05 00:40:46 -07003409 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3411 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003412 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413 " last eglSwapBuffers() time: %f us\n"
3414 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003415 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003416 " refresh-rate : %f fps\n"
3417 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003418 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003419 " gpu_to_cpu_unsupported : %d\n"
3420 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421 mLastSwapBufferTime/1000.0,
3422 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003423 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003424 1e9 / activeConfig->getVsyncPeriod(),
3425 activeConfig->getDpiX(),
3426 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003427 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428
Mathias Agopian74d211a2013-04-22 16:55:35 +02003429 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003433 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003434
3435 /*
3436 * VSYNC state
3437 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003438 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003439 result.append("\n");
3440
3441 /*
3442 * HWC layer minidump
3443 */
3444 for (size_t d = 0; d < mDisplays.size(); d++) {
3445 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3446 int32_t hwcId = displayDevice->getHwcDisplayId();
3447 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3448 continue;
3449 }
3450
3451 result.appendFormat("Display %d HWC layers:\n", hwcId);
3452 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003453 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003454 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 });
Dan Stozae22aec72016-08-01 13:20:59 -07003456 result.append("\n");
3457 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458
3459 /*
3460 * Dump HWComposer state
3461 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003462 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003463 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003464 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003465 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003466 result.appendFormat(" h/w composer %s\n",
3467 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469
3470 /*
3471 * Dump gralloc state
3472 */
3473 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3474 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003475}
3476
Mathias Agopian13127d82013-03-05 17:47:11 -08003477const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003478SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003479 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003480 wp<IBinder> dpy;
3481 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3482 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3483 dpy = mDisplays.keyAt(i);
3484 break;
3485 }
3486 }
3487 if (dpy == NULL) {
3488 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3489 // Just use the primary display so we have something to return
3490 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3491 }
3492 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003493}
3494
Keun young Park63f165f2012-08-31 10:53:36 -07003495bool SurfaceFlinger::startDdmConnection()
3496{
3497 void* libddmconnection_dso =
3498 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3499 if (!libddmconnection_dso) {
3500 return false;
3501 }
3502 void (*DdmConnection_start)(const char* name);
3503 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003504 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003505 if (!DdmConnection_start) {
3506 dlclose(libddmconnection_dso);
3507 return false;
3508 }
3509 (*DdmConnection_start)(getServiceName());
3510 return true;
3511}
3512
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003513status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 switch (code) {
3515 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003516 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003518 case CLEAR_ANIMATION_FRAME_STATS:
3519 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003520 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003521 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 {
3523 // codes that require permission check
3524 IPCThreadState* ipc = IPCThreadState::self();
3525 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003526 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003527 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003528 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003529 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003530 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003532 break;
3533 }
Robert Carr1db73f62016-12-21 12:58:51 -08003534 /*
3535 * Calling setTransactionState is safe, because you need to have been
3536 * granted a reference to Client* and Handle* to do anything with it.
3537 *
3538 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3539 */
3540 case SET_TRANSACTION_STATE:
3541 case CREATE_SCOPED_CONNECTION:
3542 {
3543 return OK;
3544 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003545 case CAPTURE_SCREEN:
3546 {
3547 // codes that require permission check
3548 IPCThreadState* ipc = IPCThreadState::self();
3549 const int pid = ipc->getCallingPid();
3550 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003551 if ((uid != AID_GRAPHICS) &&
3552 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003553 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003554 return PERMISSION_DENIED;
3555 }
3556 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
3558 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003559 return OK;
3560}
3561
3562status_t SurfaceFlinger::onTransact(
3563 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3564{
3565 status_t credentialCheck = CheckTransactCodeCredentials(code);
3566 if (credentialCheck != OK) {
3567 return credentialCheck;
3568 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003569
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3571 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003572 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003573 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003574 IPCThreadState* ipc = IPCThreadState::self();
3575 const int pid = ipc->getCallingPid();
3576 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003577 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003578 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 return PERMISSION_DENIED;
3580 }
3581 int n;
3582 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003583 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003584 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 return NO_ERROR;
3586 case 1002: // SHOW_UPDATES
3587 n = data.readInt32();
3588 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003589 invalidateHwcGeometry();
3590 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003593 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003594 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003596 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003597 setTransactionFlags(
3598 eTransactionNeeded|
3599 eDisplayTransactionNeeded|
3600 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003601 return NO_ERROR;
3602 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003603 case 1006:{ // send empty update
3604 signalRefresh();
3605 return NO_ERROR;
3606 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003607 case 1008: // toggle use of hw composer
3608 n = data.readInt32();
3609 mDebugDisableHWC = n ? 1 : 0;
3610 invalidateHwcGeometry();
3611 repaintEverything();
3612 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003613 case 1009: // toggle use of transform hint
3614 n = data.readInt32();
3615 mDebugDisableTransformHint = n ? 1 : 0;
3616 invalidateHwcGeometry();
3617 repaintEverything();
3618 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003620 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621 reply->writeInt32(0);
3622 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003623 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003624 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625 return NO_ERROR;
3626 case 1013: {
3627 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003628 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3629 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003630 return NO_ERROR;
3631 }
3632 case 1014: {
3633 // daltonize
3634 n = data.readInt32();
3635 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003636 case 1:
3637 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3638 break;
3639 case 2:
3640 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3641 break;
3642 case 3:
3643 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3644 break;
3645 default:
3646 mDaltonizer.setType(ColorBlindnessType::None);
3647 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003648 }
3649 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003650 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003651 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003652 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003653 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003654 invalidateHwcGeometry();
3655 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003658 case 1015: {
3659 // apply a color matrix
3660 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003661 if (n) {
3662 // color matrix is sent as mat3 matrix followed by vec3
3663 // offset, then packed into a mat4 where the last row is
3664 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003665 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003666 for (size_t j = 0; j < 4; j++) {
3667 mColorMatrix[i][j] = data.readFloat();
3668 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003669 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003670 } else {
3671 mColorMatrix = mat4();
3672 }
3673 invalidateHwcGeometry();
3674 repaintEverything();
3675 return NO_ERROR;
3676 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003677 // This is an experimental interface
3678 // Needs to be shifted to proper binder interface when we productize
3679 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003680 n = data.readInt32();
3681 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003682 return NO_ERROR;
3683 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003684 case 1017: {
3685 n = data.readInt32();
3686 mForceFullDamage = static_cast<bool>(n);
3687 return NO_ERROR;
3688 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003689 case 1018: { // Modify Choreographer's phase offset
3690 n = data.readInt32();
3691 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3692 return NO_ERROR;
3693 }
3694 case 1019: { // Modify SurfaceFlinger's phase offset
3695 n = data.readInt32();
3696 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3697 return NO_ERROR;
3698 }
Irvel468051e2016-06-13 16:44:44 -07003699 case 1020: { // Layer updates interceptor
3700 n = data.readInt32();
3701 if (n) {
3702 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003703 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003704 }
3705 else{
3706 ALOGV("Interceptor disabled");
3707 mInterceptor.disable();
3708 }
3709 return NO_ERROR;
3710 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003711 case 1021: { // Disable HWC virtual displays
3712 n = data.readInt32();
3713 mUseHwcVirtualDisplays = !n;
3714 return NO_ERROR;
3715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 }
3717 }
3718 return err;
3719}
3720
Mathias Agopian53331da2011-08-22 21:44:41 -07003721void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003722 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003723 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003724}
3725
Mathias Agopian59119e62010-10-11 12:37:43 -07003726// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003727// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003728// ---------------------------------------------------------------------------
3729
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003730/* The code below is here to handle b/8734824
3731 *
3732 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003733 * from the surfaceflinger thread to the calling binder thread, where they
3734 * are executed. This allows the calling thread in the calling process to be
3735 * reused and not depend on having "enough" binder threads to handle the
3736 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003737 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003738class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003739 /* Parts of GraphicProducerWrapper are run on two different threads,
3740 * communicating by sending messages via Looper but also by shared member
3741 * data. Coherence maintenance is subtle and in places implicit (ugh).
3742 *
3743 * Don't rely on Looper's sendMessage/handleMessage providing
3744 * release/acquire semantics for any data not actually in the Message.
3745 * Data going from surfaceflinger to binder threads needs to be
3746 * synchronized explicitly.
3747 *
3748 * Barrier open/wait do provide release/acquire semantics. This provides
3749 * implicit synchronization for data coming back from binder to
3750 * surfaceflinger threads.
3751 */
3752
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753 sp<IGraphicBufferProducer> impl;
3754 sp<Looper> looper;
3755 status_t result;
3756 bool exitPending;
3757 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003758 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003759 uint32_t code;
3760 Parcel const* data;
3761 Parcel* reply;
3762
3763 enum {
3764 MSG_API_CALL,
3765 MSG_EXIT
3766 };
3767
3768 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003769 * Called on surfaceflinger thread. This is called by our "fake"
3770 * BpGraphicBufferProducer. We package the data and reply Parcel and
3771 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003772 */
3773 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003774 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003775 this->code = code;
3776 this->data = &data;
3777 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003778 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003779 // if we've exited, we run the message synchronously right here.
3780 // note (JH): as far as I can tell from looking at the code, this
3781 // never actually happens. if it does, i'm not sure if it happens
3782 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 handleMessage(Message(MSG_API_CALL));
3784 } else {
3785 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003786 // Prevent stores to this->{code, data, reply} from being
3787 // reordered later than the construction of Message.
3788 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003789 looper->sendMessage(this, Message(MSG_API_CALL));
3790 barrier.wait();
3791 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003792 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 }
3794
3795 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003796 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 * call the real BpGraphicBufferProducer.
3798 */
3799 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003800 int what = message.what;
3801 // Prevent reads below from happening before the read from Message
3802 atomic_thread_fence(memory_order_acquire);
3803 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003804 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003805 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003806 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003807 exitRequested = true;
3808 }
3809 }
3810
3811public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003812 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003813 : impl(impl),
3814 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003815 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003816 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003817 exitRequested(false),
3818 code(0),
3819 data(NULL),
3820 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003821 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822
Jesse Hallb154c422014-07-13 12:47:02 -07003823 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 status_t waitForResponse() {
3825 do {
3826 looper->pollOnce(-1);
3827 } while (!exitRequested);
3828 return result;
3829 }
3830
Jesse Hallb154c422014-07-13 12:47:02 -07003831 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003832 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003833 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003834 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003835 // Ensure this->result is visible to the binder thread before it
3836 // handles the message.
3837 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003838 looper->sendMessage(this, Message(MSG_EXIT));
3839 }
3840};
3841
3842
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003843status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3844 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003845 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003846 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003847 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003848
3849 if (CC_UNLIKELY(display == 0))
3850 return BAD_VALUE;
3851
3852 if (CC_UNLIKELY(producer == 0))
3853 return BAD_VALUE;
3854
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003855 // if we have secure windows on this display, never allow the screen capture
3856 // unless the producer interface is local (i.e.: we can take a screenshot for
3857 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003858 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003859
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003860 // Convert to surfaceflinger's internal rotation type.
3861 Transform::orientation_flags rotationFlags;
3862 switch (rotation) {
3863 case ISurfaceComposer::eRotateNone:
3864 rotationFlags = Transform::ROT_0;
3865 break;
3866 case ISurfaceComposer::eRotate90:
3867 rotationFlags = Transform::ROT_90;
3868 break;
3869 case ISurfaceComposer::eRotate180:
3870 rotationFlags = Transform::ROT_180;
3871 break;
3872 case ISurfaceComposer::eRotate270:
3873 rotationFlags = Transform::ROT_270;
3874 break;
3875 default:
3876 rotationFlags = Transform::ROT_0;
3877 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3878 break;
3879 }
3880
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003881 class MessageCaptureScreen : public MessageBase {
3882 SurfaceFlinger* flinger;
3883 sp<IBinder> display;
3884 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003885 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003886 uint32_t reqWidth, reqHeight;
3887 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003888 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003889 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003890 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003891 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003892 public:
3893 MessageCaptureScreen(SurfaceFlinger* flinger,
3894 const sp<IBinder>& display,
3895 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003896 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003897 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003898 bool useIdentityTransform,
3899 Transform::orientation_flags rotation,
3900 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003902 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003904 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003905 rotation(rotation), result(PERMISSION_DENIED),
3906 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 {
3908 }
3909 status_t getResult() const {
3910 return result;
3911 }
3912 virtual bool handler() {
3913 Mutex::Autolock _l(flinger->mStateLock);
3914 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003915 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003916 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003917 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003918 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003919 return true;
3920 }
3921 };
3922
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003923 // this creates a "fake" BBinder which will serve as a "fake" remote
3924 // binder to receive the marshaled calls and forward them to the
3925 // real remote (a BpGraphicBufferProducer)
3926 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3927
3928 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3929 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003931 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003932 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003933 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003934
3935 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003936 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003937 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003938 }
3939 return res;
3940}
3941
Mathias Agopian180f10d2013-04-10 22:55:41 -07003942
3943void SurfaceFlinger::renderScreenImplLocked(
3944 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003945 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003946 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003947 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003948{
3949 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003950 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003951
3952 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003953 const int32_t hw_w = hw->getWidth();
3954 const int32_t hw_h = hw->getHeight();
3955 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003956 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003957
Dan Stozac1879002014-05-22 15:59:05 -07003958 // if a default or invalid sourceCrop is passed in, set reasonable values
3959 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3960 !sourceCrop.isValid()) {
3961 sourceCrop.setLeftTop(Point(0, 0));
3962 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3963 }
3964
3965 // ensure that sourceCrop is inside screen
3966 if (sourceCrop.left < 0) {
3967 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3968 }
Dan Stozabe31f442014-06-11 11:20:54 -07003969 if (sourceCrop.right > hw_w) {
3970 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003971 }
3972 if (sourceCrop.top < 0) {
3973 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3974 }
Dan Stozabe31f442014-06-11 11:20:54 -07003975 if (sourceCrop.bottom > hw_h) {
3976 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003977 }
3978
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003980 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003981
3982 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003983 engine.setViewportAndProjection(
3984 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003985 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003986
3987 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003988 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003989
Robert Carr1f0a16a2016-10-24 16:27:39 -07003990 // We loop through the first level of layers without traversing,
3991 // as we need to interpret min/max layer Z in the top level Z space.
3992 for (const auto& layer : mDrawingState.layersSortedByZ) {
3993 if (layer->getLayerStack() != hw->getLayerStack()) {
3994 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003996 const Layer::State& state(layer->getDrawingState());
3997 if (state.z < minLayerZ || state.z > maxLayerZ) {
3998 continue;
3999 }
4000 layer->traverseInZOrder([&](Layer* layer) {
4001 if (!layer->isVisible()) {
4002 return;
4003 }
4004 if (filtering) layer->setFiltering(true);
4005 layer->draw(hw, useIdentityTransform);
4006 if (filtering) layer->setFiltering(false);
4007 });
4008 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004009
Mathias Agopian931bda12013-08-28 18:11:46 -07004010 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004011}
4012
4013
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004014status_t SurfaceFlinger::captureScreenImplLocked(
4015 const sp<const DisplayDevice>& hw,
4016 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004017 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004018 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004019 bool useIdentityTransform, Transform::orientation_flags rotation,
4020 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021{
4022 ATRACE_CALL();
4023
Mathias Agopian180f10d2013-04-10 22:55:41 -07004024 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004025 uint32_t hw_w = hw->getWidth();
4026 uint32_t hw_h = hw->getHeight();
4027
4028 if (rotation & Transform::ROT_90) {
4029 std::swap(hw_w, hw_h);
4030 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004031
Mathias Agopian180f10d2013-04-10 22:55:41 -07004032 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4033 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4034 reqWidth, reqHeight, hw_w, hw_h);
4035 return BAD_VALUE;
4036 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004037
Mathias Agopian180f10d2013-04-10 22:55:41 -07004038 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4039 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4040
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004041 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004042 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004043 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004044 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4045 (state.z < minLayerZ || state.z > maxLayerZ)) {
4046 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004047 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004048 layer->traverseInZOrder([&](Layer *layer) {
4049 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4050 layer->isSecure());
4051 });
4052 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004053
4054 if (!isLocalScreenshot && secureLayerIsVisible) {
4055 ALOGW("FB is protected: PERMISSION_DENIED");
4056 return PERMISSION_DENIED;
4057 }
4058
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004059 // create a surface (because we're a producer, and we need to
4060 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004061 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004062
4063 // Put the screenshot Surface into async mode so that
4064 // Layer::headFenceHasSignaled will always return true and we'll latch the
4065 // first buffer regardless of whether or not its acquire fence has
4066 // signaled. This is needed to avoid a race condition in the rotation
4067 // animation. See b/30209608
4068 sur->setAsyncMode(true);
4069
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004071
Michael Lentine5a16a622015-05-21 13:48:24 -07004072 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4073 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004074 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4075 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004076
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004077 int err = 0;
4078 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004079 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004080 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4081 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004082
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004083 if (err == NO_ERROR) {
4084 ANativeWindowBuffer* buffer;
4085 /* TODO: Once we have the sync framework everywhere this can use
4086 * server-side waits on the fence that dequeueBuffer returns.
4087 */
4088 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4089 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004090 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004091 // create an EGLImage from the buffer so we can later
4092 // turn it into a texture
4093 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4094 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4095 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004096 // this binds the given EGLImage as a framebuffer for the
4097 // duration of this scope.
4098 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4099 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004100 // this will in fact render into our dequeued buffer
4101 // via an FBO, which means we didn't have to create
4102 // an EGLSurface and therefore we're not
4103 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004104 renderScreenImplLocked(
4105 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4106 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004107
Riley Andrews86639902014-08-15 12:27:24 -07004108 // Attempt to create a sync khr object that can produce a sync point. If that
4109 // isn't available, create a non-dupable sync object in the fallback path and
4110 // wait on it directly.
4111 EGLSyncKHR sync;
4112 if (!DEBUG_SCREENSHOTS) {
4113 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004114 // native fence fd will not be populated until flush() is done.
4115 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004116 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004117 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004118 }
Riley Andrews86639902014-08-15 12:27:24 -07004119 if (sync != EGL_NO_SYNC_KHR) {
4120 // get the sync fd
4121 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4122 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4123 ALOGW("captureScreen: failed to dup sync khr object");
4124 syncFd = -1;
4125 }
4126 eglDestroySyncKHR(mEGLDisplay, sync);
4127 } else {
4128 // fallback path
4129 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4130 if (sync != EGL_NO_SYNC_KHR) {
4131 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4132 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4133 EGLint eglErr = eglGetError();
4134 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4135 ALOGW("captureScreen: fence wait timed out");
4136 } else {
4137 ALOGW_IF(eglErr != EGL_SUCCESS,
4138 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4139 }
4140 eglDestroySyncKHR(mEGLDisplay, sync);
4141 } else {
4142 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4143 }
4144 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004145 if (DEBUG_SCREENSHOTS) {
4146 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4147 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4148 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4149 hw, minLayerZ, maxLayerZ);
4150 delete [] pixels;
4151 }
4152
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004153 } else {
4154 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4155 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004156 window->cancelBuffer(window, buffer, syncFd);
4157 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004158 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004159 // destroy our image
4160 eglDestroyImageKHR(mEGLDisplay, image);
4161 } else {
4162 result = BAD_VALUE;
4163 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004164 if (buffer) {
4165 // queueBuffer takes ownership of syncFd
4166 result = window->queueBuffer(window, buffer, syncFd);
4167 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004168 }
4169 } else {
4170 result = BAD_VALUE;
4171 }
4172 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4173 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004174
Mathias Agopian74c40c02010-09-29 13:02:36 -07004175 return result;
4176}
4177
Mathias Agopiand5556842013-09-19 17:08:37 -07004178void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004179 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004180 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004181 for (size_t y=0 ; y<h ; y++) {
4182 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4183 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004184 if (p[x] != 0xFF000000) return;
4185 }
4186 }
4187 ALOGE("*** we just took a black screenshot ***\n"
4188 "requested minz=%d, maxz=%d, layerStack=%d",
4189 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004190
Robert Carr2047fae2016-11-28 14:09:09 -08004191 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004192 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004193 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004194 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4195 state.z <= maxLayerZ) {
4196 layer->traverseInZOrder([&](Layer* layer) {
4197 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4198 layer->isVisible() ? '+' : '-',
4199 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004200 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 i++;
4202 });
4203 }
4204 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004205 }
4206}
4207
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004208// ---------------------------------------------------------------------------
4209
Robert Carr2047fae2016-11-28 14:09:09 -08004210void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4211 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004212}
4213
Robert Carr2047fae2016-11-28 14:09:09 -08004214void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4215 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004216}
4217
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004219
4220
4221#if defined(__gl_h_)
4222#error "don't include gl/gl.h in this file"
4223#endif
4224
4225#if defined(__gl2_h_)
4226#error "don't include gl2/gl2.h in this file"
4227#endif