blob: 9cf1c928f1677f5acc71c1ebd3f36884a44a6d91 [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>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080076#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
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
167 // debugging stuff...
168 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700169
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800170 // TODO (urbanus): remove once b/35319396 is fixed.
171 property_get("ro.boot.vr", value, "0");
172 mVrModeSupported = atoi(value);
173
Mathias Agopianb4b17302013-03-20 18:36:41 -0700174 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700175 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700176
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 property_get("debug.sf.showupdates", value, "0");
178 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 property_get("debug.sf.ddms", value, "0");
181 mDebugDDMS = atoi(value);
182 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700183 if (!startDdmConnection()) {
184 // start failed, and DDMS debugging not enabled
185 mDebugDDMS = 0;
186 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700187 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700188 ALOGI_IF(mDebugRegion, "showupdates enabled");
189 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700190
191 property_get("debug.sf.disable_backpressure", value, "0");
192 mPropagateBackpressure = !atoi(value);
193 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700194
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800195 property_get("debug.sf.enable_hwc_vds", value, "0");
196 mUseHwcVirtualDisplays = atoi(value);
197 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800198
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800199 property_get("ro.sf.disable_triple_buffer", value, "1");
200 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800201 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202}
203
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800204void SurfaceFlinger::onFirstRef()
205{
206 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207}
208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209SurfaceFlinger::~SurfaceFlinger()
210{
Mathias Agopiana4912602012-07-12 14:25:33 -0700211 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
212 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
213 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800214
215 if (mVrStateCallbacks.get()) {
216 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
217 defaultServiceManager()->checkService(String16("vrmanager")));
218 if (vrManagerService.get()) {
219 vrManagerService->unregisterListener(mVrStateCallbacks);
220 }
221 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222}
223
Dan Stozac7014012014-02-14 15:03:43 -0800224void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800225{
226 // the window manager died on us. prepare its eulogy.
227
Andy McFadden13a082e2012-08-24 10:16:42 -0700228 // restore initial conditions (default device unblank, etc)
229 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230
231 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700232 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
Robert Carr1db73f62016-12-21 12:58:51 -0800235static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700236 status_t err = client->initCheck();
237 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800238 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 }
Robert Carr1db73f62016-12-21 12:58:51 -0800240 return nullptr;
241}
242
243sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
244 return initClient(new Client(this));
245}
246
247sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
248 const sp<IGraphicBufferProducer>& gbp) {
249 if (authenticateSurfaceTexture(gbp) == false) {
250 return nullptr;
251 }
252 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
253 if (layer == nullptr) {
254 return nullptr;
255 }
256
257 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258}
259
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700260sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
261 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700262{
263 class DisplayToken : public BBinder {
264 sp<SurfaceFlinger> flinger;
265 virtual ~DisplayToken() {
266 // no more references, this display must be terminated
267 Mutex::Autolock _l(flinger->mStateLock);
268 flinger->mCurrentState.displays.removeItem(this);
269 flinger->setTransactionFlags(eDisplayTransactionNeeded);
270 }
271 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700272 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700273 : flinger(flinger) {
274 }
275 };
276
277 sp<BBinder> token = new DisplayToken(this);
278
279 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700280 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700281 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700282 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700283 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284 return token;
285}
286
Jesse Hall6c913be2013-08-08 12:15:49 -0700287void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
288 Mutex::Autolock _l(mStateLock);
289
290 ssize_t idx = mCurrentState.displays.indexOfKey(display);
291 if (idx < 0) {
292 ALOGW("destroyDisplay: invalid display token");
293 return;
294 }
295
296 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
297 if (!info.isVirtualDisplay()) {
298 ALOGE("destroyDisplay called for non-virtual display");
299 return;
300 }
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700302 mCurrentState.displays.removeItemsAt(idx);
303 setTransactionFlags(eDisplayTransactionNeeded);
304}
305
Jesse Hall692c7232012-11-08 15:41:56 -0800306void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800307 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800308 ALOGW_IF(mBuiltinDisplays[type],
309 "Overwriting display token for display type %d", type);
310 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800311 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700312 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800313 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700314 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800315}
316
Mathias Agopiane57f2922012-08-09 16:29:12 -0700317sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700318 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700319 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
320 return NULL;
321 }
Jesse Hall692c7232012-11-08 15:41:56 -0800322 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700323}
324
Jamie Gennis9a78c902011-01-12 18:30:40 -0800325sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
326{
327 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
328 return gba;
329}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331void SurfaceFlinger::bootFinished()
332{
Wei Wangb254fa32017-01-31 17:43:23 -0800333 if (mStartBootAnimThread->join() != NO_ERROR) {
334 ALOGE("Join StartBootAnimThread failed!");
335 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 const nsecs_t now = systemTime();
337 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000338 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700339 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700340
341 // wait patiently for the window manager death
342 const String16 name("window");
343 sp<IBinder> window(defaultServiceManager()->getService(name));
344 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700345 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700346 }
347
348 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700349 // formerly we would just kill the process, but we now ask it to exit so it
350 // can choose where to stop the animation.
351 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700352
353 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
354 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
355 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800356
357 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
358 defaultServiceManager()->checkService(String16("vrmanager")));
359 if (vrManagerService.get()) {
360 mVrStateCallbacks = new VrStateCallbacks(*this);
361 vrManagerService->registerListener(mVrStateCallbacks);
362 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Mathias Agopian3f844832013-08-07 21:24:32 -0700365void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700366 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700367 RenderEngine& engine;
368 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700369 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700370 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
371 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700372 }
373 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700374 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700375 return true;
376 }
377 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379}
380
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381class DispSyncSource : public VSyncSource, private DispSync::Callback {
382public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700383 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000384 const char* name) :
385 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700386 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700387 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000388 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
389 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700390 mDispSync(dispSync),
391 mCallbackMutex(),
392 mCallback(),
393 mVsyncMutex(),
394 mPhaseOffset(phaseOffset),
395 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700396
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700397 virtual ~DispSyncSource() {}
398
399 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700400 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000402 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700403 static_cast<DispSync::Callback*>(this));
404 if (err != NO_ERROR) {
405 ALOGE("error registering vsync callback: %s (%d)",
406 strerror(-err), err);
407 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700408 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 } else {
410 status_t err = mDispSync->removeEventListener(
411 static_cast<DispSync::Callback*>(this));
412 if (err != NO_ERROR) {
413 ALOGE("error unregistering vsync callback: %s (%d)",
414 strerror(-err), err);
415 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700416 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700418 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 }
420
421 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700422 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 mCallback = callback;
424 }
425
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700426 virtual void setPhaseOffset(nsecs_t phaseOffset) {
427 Mutex::Autolock lock(mVsyncMutex);
428
429 // Normalize phaseOffset to [0, period)
430 auto period = mDispSync->getPeriod();
431 phaseOffset %= period;
432 if (phaseOffset < 0) {
433 // If we're here, then phaseOffset is in (-period, 0). After this
434 // operation, it will be in (0, period)
435 phaseOffset += period;
436 }
437 mPhaseOffset = phaseOffset;
438
439 // If we're not enabled, we don't need to mess with the listeners
440 if (!mEnabled) {
441 return;
442 }
443
444 // Remove the listener with the old offset
445 status_t err = mDispSync->removeEventListener(
446 static_cast<DispSync::Callback*>(this));
447 if (err != NO_ERROR) {
448 ALOGE("error unregistering vsync callback: %s (%d)",
449 strerror(-err), err);
450 }
451
452 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000453 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error registering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
459 }
460
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461private:
462 virtual void onDispSyncEvent(nsecs_t when) {
463 sp<VSyncSource::Callback> callback;
464 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700465 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 callback = mCallback;
467
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700468 if (mTraceVsync) {
469 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700470 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700471 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 }
473
474 if (callback != NULL) {
475 callback->onVSyncEvent(when);
476 }
477 }
478
Tim Murray4a4e4a22016-04-19 16:29:23 +0000479 const char* const mName;
480
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 int mValue;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700484 const String8 mVsyncOnLabel;
485 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700488
489 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700491
492 Mutex mVsyncMutex; // Protects the following
493 nsecs_t mPhaseOffset;
494 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495};
496
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700497class InjectVSyncSource : public VSyncSource {
498public:
499 InjectVSyncSource() {}
500
501 virtual ~InjectVSyncSource() {}
502
503 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
504 std::lock_guard<std::mutex> lock(mCallbackMutex);
505 mCallback = callback;
506 }
507
508 virtual void onInjectSyncEvent(nsecs_t when) {
509 std::lock_guard<std::mutex> lock(mCallbackMutex);
510 mCallback->onVSyncEvent(when);
511 }
512
513 virtual void setVSyncEnabled(bool) {}
514 virtual void setPhaseOffset(nsecs_t) {}
515
516private:
517 std::mutex mCallbackMutex; // Protects the following
518 sp<VSyncSource::Callback> mCallback;
519};
520
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700522 ALOGI( "SurfaceFlinger's main thread ready to run. "
523 "Initializing graphics H/W...");
524
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900525 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
526
Dan Stoza9e56aa02015-11-02 13:00:03 -0800527 { // Autolock scope
528 Mutex::Autolock _l(mStateLock);
529
530 // initialize EGL for the default display
531 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
532 eglInitialize(mEGLDisplay, NULL, NULL);
533
534 // start the EventThread
535 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
536 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700537 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800538 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
539 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700540 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800541 mEventQueue.setEventThread(mSFEventThread);
542
Tim Murrayacff43d2016-07-29 13:57:24 -0700543 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700544 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700545 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700546 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
547 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
548 }
549
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 // Get a RenderEngine for the given display / config (can't fail)
551 mRenderEngine = RenderEngine::create(mEGLDisplay,
552 HAL_PIXEL_FORMAT_RGBA_8888);
553 }
554
555 // Drop the state lock while we initialize the hardware composer. We drop
556 // the lock because on creation, it will call back into SurfaceFlinger to
557 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800558 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800559 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800560 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
562
Jesse Hall692c7232012-11-08 15:41:56 -0800563 Mutex::Autolock _l(mStateLock);
564
Mathias Agopian875d8e12013-06-07 15:35:48 -0700565 // retrieve the EGL context that was selected/created
566 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700567
Mathias Agopianda27af92012-09-13 18:17:13 -0700568 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
569 "couldn't create EGLContext");
570
Dan Stoza9e56aa02015-11-02 13:00:03 -0800571 // make the GLContext current so that we can create textures when creating
572 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700573 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
574
Jamie Gennisd1700752013-10-14 12:22:52 -0700575 mEventControlThread = new EventControlThread(this);
576 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
577
Mathias Agopian92a979a2012-08-02 18:32:23 -0700578 // initialize our drawing state
579 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700580
Andy McFadden13a082e2012-08-24 10:16:42 -0700581 // set initial conditions (e.g. unblank default device)
582 initializeDisplays();
583
Dan Stoza4e637772016-07-28 13:31:51 -0700584 mRenderEngine->primeCache();
585
Wei Wangb254fa32017-01-31 17:43:23 -0800586 mStartBootAnimThread = new StartBootAnimThread();
587 if (mStartBootAnimThread->Start() != NO_ERROR) {
588 ALOGE("Run StartBootAnimThread failed!");
589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700592}
593
Mathias Agopiana67e4182012-06-19 17:26:12 -0700594void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800595 // Start boot animation service by setting a property mailbox
596 // if property setting thread is already running, Start() will be just a NOP
597 mStartBootAnimThread->Start();
598 // Wait until property was set
599 if (mStartBootAnimThread->join() != NO_ERROR) {
600 ALOGE("Join StartBootAnimThread failed!");
601 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700602}
603
Mathias Agopian875d8e12013-06-07 15:35:48 -0700604size_t SurfaceFlinger::getMaxTextureSize() const {
605 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700606}
607
Mathias Agopian875d8e12013-06-07 15:35:48 -0700608size_t SurfaceFlinger::getMaxViewportDims() const {
609 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700610}
611
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800612// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800613
Jamie Gennis582270d2011-08-17 18:19:00 -0700614bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800615 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800616 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800617 return authenticateSurfaceTextureLocked(bufferProducer);
618}
619
620bool SurfaceFlinger::authenticateSurfaceTextureLocked(
621 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800622 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700623 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800624}
625
Brian Anderson069b3652016-07-22 10:32:47 -0700626status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700627 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700628 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700629 FrameEvent::REQUESTED_PRESENT,
630 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700631 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700632 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700633 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700634 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700635 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700636 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700637 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700638 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700639 };
640 return NO_ERROR;
641}
642
Dan Stoza7f7da322014-05-02 15:26:25 -0700643status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
644 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700645 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700646 return BAD_VALUE;
647 }
648
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500649 if (!display.get())
650 return NAME_NOT_FOUND;
651
Jesse Hall692c7232012-11-08 15:41:56 -0800652 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700653 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800654 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700655 type = i;
656 break;
657 }
658 }
659
660 if (type < 0) {
661 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700662 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700663
Mathias Agopian8b736f12012-08-13 17:54:26 -0700664 // TODO: Not sure if display density should handled by SF any longer
665 class Density {
666 static int getDensityFromProperty(char const* propName) {
667 char property[PROPERTY_VALUE_MAX];
668 int density = 0;
669 if (property_get(propName, property, NULL) > 0) {
670 density = atoi(property);
671 }
672 return density;
673 }
674 public:
675 static int getEmuDensity() {
676 return getDensityFromProperty("qemu.sf.lcd_density"); }
677 static int getBuildDensity() {
678 return getDensityFromProperty("ro.sf.lcd_density"); }
679 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700680
Dan Stoza7f7da322014-05-02 15:26:25 -0700681 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700682
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700684 DisplayInfo info = DisplayInfo();
685
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686 float xdpi = hwConfig->getDpiX();
687 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700688
689 if (type == DisplayDevice::DISPLAY_PRIMARY) {
690 // The density of the device is provided by a build property
691 float density = Density::getBuildDensity() / 160.0f;
692 if (density == 0) {
693 // the build doesn't provide a density -- this is wrong!
694 // use xdpi instead
695 ALOGE("ro.sf.lcd_density must be defined as a build property");
696 density = xdpi / 160.0f;
697 }
698 if (Density::getEmuDensity()) {
699 // if "qemu.sf.lcd_density" is specified, it overrides everything
700 xdpi = ydpi = density = Density::getEmuDensity();
701 density /= 160.0f;
702 }
703 info.density = density;
704
705 // TODO: this needs to go away (currently needed only by webkit)
706 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
707 info.orientation = hw->getOrientation();
708 } else {
709 // TODO: where should this value come from?
710 static const int TV_DENSITY = 213;
711 info.density = TV_DENSITY / 160.0f;
712 info.orientation = 0;
713 }
714
Dan Stoza9e56aa02015-11-02 13:00:03 -0800715 info.w = hwConfig->getWidth();
716 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700717 info.xdpi = xdpi;
718 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900720 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721
Andy McFadden91b2ca82014-06-13 14:04:23 -0700722 // This is how far in advance a buffer must be queued for
723 // presentation at a given time. If you want a buffer to appear
724 // on the screen at time N, you must submit the buffer before
725 // (N - presentationDeadline).
726 //
727 // Normally it's one full refresh period (to give SF a chance to
728 // latch the buffer), but this can be reduced by configuring a
729 // DispSync offset. Any additional delays introduced by the hardware
730 // composer or panel must be accounted for here.
731 //
732 // We add an additional 1ms to allow for processing time and
733 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800735 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700736
737 // All non-virtual displays are currently considered secure.
738 info.secure = true;
739
Michael Wright28f24d02016-07-12 13:30:53 -0700740 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700741 }
742
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 return NO_ERROR;
744}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700745
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800746status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700747 DisplayStatInfo* stats) {
748 if (stats == NULL) {
749 return BAD_VALUE;
750 }
751
752 // FIXME for now we always return stats for the primary display
753 memset(stats, 0, sizeof(*stats));
754 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
755 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
756 return NO_ERROR;
757}
758
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700759int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800760 if (display == NULL) {
761 ALOGE("%s : display is NULL", __func__);
762 return BAD_VALUE;
763 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700764 sp<DisplayDevice> device(getDisplayDevice(display));
765 if (device != NULL) {
766 return device->getActiveConfig();
767 }
768 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700769}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700770
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700771void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
772 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
773 this);
774 int32_t type = hw->getDisplayType();
775 int currentMode = hw->getActiveConfig();
776
777 if (mode == currentMode) {
778 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
779 return;
780 }
781
782 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
783 ALOGW("Trying to set config for virtual display");
784 return;
785 }
786
787 hw->setActiveConfig(mode);
788 getHwComposer().setActiveConfig(type, mode);
789}
790
791status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
792 class MessageSetActiveConfig: public MessageBase {
793 SurfaceFlinger& mFlinger;
794 sp<IBinder> mDisplay;
795 int mMode;
796 public:
797 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
798 int mode) :
799 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
800 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700801 Vector<DisplayInfo> configs;
802 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700803 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700804 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700805 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700806 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700807 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700808 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
809 if (hw == NULL) {
810 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700811 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700812 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
813 ALOGW("Attempt to set active config = %d for virtual display",
814 mMode);
815 } else {
816 mFlinger.setActiveConfigInternal(hw, mMode);
817 }
818 return true;
819 }
820 };
821 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
822 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700823 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700824}
Michael Wright28f24d02016-07-12 13:30:53 -0700825status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
826 Vector<android_color_mode_t>* outColorModes) {
827 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
828 return BAD_VALUE;
829 }
830
831 if (!display.get()) {
832 return NAME_NOT_FOUND;
833 }
834
835 int32_t type = NAME_NOT_FOUND;
836 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
837 if (display == mBuiltinDisplays[i]) {
838 type = i;
839 break;
840 }
841 }
842
843 if (type < 0) {
844 return type;
845 }
846
847 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
848 outColorModes->clear();
849 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
850
851 return NO_ERROR;
852}
853
854android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
855 sp<DisplayDevice> device(getDisplayDevice(display));
856 if (device != nullptr) {
857 return device->getActiveColorMode();
858 }
859 return static_cast<android_color_mode_t>(BAD_VALUE);
860}
861
862void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
863 android_color_mode_t mode) {
864 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
865 this);
866 int32_t type = hw->getDisplayType();
867 android_color_mode_t currentMode = hw->getActiveColorMode();
868
869 if (mode == currentMode) {
870 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
871 return;
872 }
873
874 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
875 ALOGW("Trying to set config for virtual display");
876 return;
877 }
878
879 hw->setActiveColorMode(mode);
880 getHwComposer().setActiveColorMode(type, mode);
881}
882
883
884status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
885 android_color_mode_t colorMode) {
886 class MessageSetActiveColorMode: public MessageBase {
887 SurfaceFlinger& mFlinger;
888 sp<IBinder> mDisplay;
889 android_color_mode_t mMode;
890 public:
891 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
892 android_color_mode_t mode) :
893 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
894 virtual bool handler() {
895 Vector<android_color_mode_t> modes;
896 mFlinger.getDisplayColorModes(mDisplay, &modes);
897 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
898 if (mMode < 0 || !exists) {
899 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
900 mDisplay.get());
901 return true;
902 }
903 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
904 if (hw == nullptr) {
905 ALOGE("Attempt to set active color mode = %d for null display %p",
906 mMode, mDisplay.get());
907 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
908 ALOGW("Attempt to set active color mode= %d for virtual display",
909 mMode);
910 } else {
911 mFlinger.setActiveColorModeInternal(hw, mMode);
912 }
913 return true;
914 }
915 };
916 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
917 postMessageSync(msg);
918 return NO_ERROR;
919}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920
Svetoslavd85084b2014-03-20 10:28:31 -0700921status_t SurfaceFlinger::clearAnimationFrameStats() {
922 Mutex::Autolock _l(mStateLock);
923 mAnimFrameTracker.clearStats();
924 return NO_ERROR;
925}
926
927status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
928 Mutex::Autolock _l(mStateLock);
929 mAnimFrameTracker.getStats(outStats);
930 return NO_ERROR;
931}
932
Dan Stozac4f471e2016-03-24 09:31:08 -0700933status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
934 HdrCapabilities* outCapabilities) const {
935 Mutex::Autolock _l(mStateLock);
936
937 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
938 if (displayDevice == nullptr) {
939 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
940 return BAD_VALUE;
941 }
942
943 std::unique_ptr<HdrCapabilities> capabilities =
944 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
945 if (capabilities) {
946 std::swap(*outCapabilities, *capabilities);
947 } else {
948 return BAD_VALUE;
949 }
950
951 return NO_ERROR;
952}
953
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700954status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
955 if (enable == mInjectVSyncs) {
956 return NO_ERROR;
957 }
958
959 if (enable) {
960 mInjectVSyncs = enable;
961 ALOGV("VSync Injections enabled");
962 if (mVSyncInjector.get() == nullptr) {
963 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700964 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700965 }
966 mEventQueue.setEventThread(mInjectorEventThread);
967 } else {
968 mInjectVSyncs = enable;
969 ALOGV("VSync Injections disabled");
970 mEventQueue.setEventThread(mSFEventThread);
971 mVSyncInjector.clear();
972 }
973 return NO_ERROR;
974}
975
976status_t SurfaceFlinger::injectVSync(nsecs_t when) {
977 if (!mInjectVSyncs) {
978 ALOGE("VSync Injections not enabled");
979 return BAD_VALUE;
980 }
981 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
982 ALOGV("Injecting VSync inside SurfaceFlinger");
983 mVSyncInjector->onInjectSyncEvent(when);
984 }
985 return NO_ERROR;
986}
987
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800988// ----------------------------------------------------------------------------
989
990sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800991 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700992}
993
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800994// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800995
996void SurfaceFlinger::waitForEvent() {
997 mEventQueue.waitMessage();
998}
999
1000void SurfaceFlinger::signalTransaction() {
1001 mEventQueue.invalidate();
1002}
1003
1004void SurfaceFlinger::signalLayerUpdate() {
1005 mEventQueue.invalidate();
1006}
1007
1008void SurfaceFlinger::signalRefresh() {
1009 mEventQueue.refresh();
1010}
1011
1012status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001013 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001014 return mEventQueue.postMessage(msg, reltime);
1015}
1016
1017status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001018 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001019 status_t res = mEventQueue.postMessage(msg, reltime);
1020 if (res == NO_ERROR) {
1021 msg->wait();
1022 }
1023 return res;
1024}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001025
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001026void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001027 do {
1028 waitForEvent();
1029 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030}
1031
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001032void SurfaceFlinger::enableHardwareVsync() {
1033 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001034 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001035 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001036 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1037 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001038 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001039 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001040}
1041
Jesse Hall948fe0c2013-10-14 12:56:09 -07001042void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001043 Mutex::Autolock _l(mHWVsyncLock);
1044
Jesse Hall948fe0c2013-10-14 12:56:09 -07001045 if (makeAvailable) {
1046 mHWVsyncAvailable = true;
1047 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001048 // Hardware vsync is not currently available, so abort the resync
1049 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001050 return;
1051 }
1052
Dan Stoza9e56aa02015-11-02 13:00:03 -08001053 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1054 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055
1056 mPrimaryDispSync.reset();
1057 mPrimaryDispSync.setPeriod(period);
1058
1059 if (!mPrimaryHWVsyncEnabled) {
1060 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001061 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1062 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001063 mPrimaryHWVsyncEnabled = true;
1064 }
1065}
1066
Jesse Hall948fe0c2013-10-14 12:56:09 -07001067void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001068 Mutex::Autolock _l(mHWVsyncLock);
1069 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001070 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1071 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072 mPrimaryDispSync.endResync();
1073 mPrimaryHWVsyncEnabled = false;
1074 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001075 if (makeUnavailable) {
1076 mHWVsyncAvailable = false;
1077 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078}
1079
Tim Murray4a4e4a22016-04-19 16:29:23 +00001080void SurfaceFlinger::resyncWithRateLimit() {
1081 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1082 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001083 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001084 }
1085}
1086
Steven Thomas3cfac282017-02-06 12:29:30 -08001087void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1088 nsecs_t timestamp) {
1089 Mutex::Autolock lock(mStateLock);
1090 // Ignore any vsyncs from the non-active hardware composer.
1091 if (composer != mHwc) {
1092 return;
1093 }
1094
Jamie Gennisd1700752013-10-14 12:22:52 -07001095 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001096
Jamie Gennisd1700752013-10-14 12:22:52 -07001097 { // Scope for the lock
1098 Mutex::Autolock _l(mHWVsyncLock);
1099 if (type == 0 && mPrimaryHWVsyncEnabled) {
1100 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001101 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001102 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001103
1104 if (needsHwVsync) {
1105 enableHardwareVsync();
1106 } else {
1107 disableHardwareVsync(false);
1108 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001109}
1110
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001111void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1112 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1113 *compositorTiming = mCompositorTiming;
1114}
1115
Dan Stoza9e56aa02015-11-02 13:00:03 -08001116void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1117 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1118 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1119 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001120
Dan Stoza9e56aa02015-11-02 13:00:03 -08001121 // All non-virtual displays are currently considered secure.
1122 bool isSecure = true;
1123
1124 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001125
1126 // When we're using the vr composer, the assumption is that we've
1127 // already created the IBinder object for the primary display.
1128 if (!mHwc->isUsingVrComposer()) {
1129 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1130 }
1131
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 wp<IBinder> token = mBuiltinDisplays[type];
1133
1134 sp<IGraphicBufferProducer> producer;
1135 sp<IGraphicBufferConsumer> consumer;
1136 BufferQueue::createBufferQueue(&producer, &consumer,
1137 new GraphicBufferAlloc());
1138
1139 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1140 DisplayDevice::DISPLAY_PRIMARY, consumer);
1141 sp<DisplayDevice> hw = new DisplayDevice(this,
1142 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1143 producer, mRenderEngine->getEGLConfig());
1144 mDisplays.add(token, hw);
1145 } else {
1146 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001147 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001148 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001149 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001150 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001151 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1152 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001153 }
1154 setTransactionFlags(eDisplayTransactionNeeded);
1155
Andy McFadden9e9689c2012-10-10 18:17:51 -07001156 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001157 }
Mathias Agopian86303202012-07-24 22:46:10 -07001158}
1159
Steven Thomas3cfac282017-02-06 12:29:30 -08001160void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1161 Mutex::Autolock lock(mStateLock);
1162 if (composer == mHwc) {
1163 repaintEverything();
1164 } else {
1165 // This isn't from our current hardware composer. If it's a callback
1166 // from the real composer, forward the refresh request to vr
1167 // flinger. Otherwise ignore it.
1168 if (!composer->isUsingVrComposer()) {
1169 mVrFlinger->OnHardwareComposerRefresh();
1170 }
1171 }
1172}
1173
Dan Stoza9e56aa02015-11-02 13:00:03 -08001174void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001176 getHwComposer().setVsyncEnabled(disp,
1177 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001178}
1179
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001180void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1181 for (size_t i = 0; i < layers.size(); ++i) {
1182 layers[i]->clearHwcLayers();
1183 }
1184}
1185
1186void SurfaceFlinger::resetHwc() {
1187 disableHardwareVsync(true);
1188 clearHwcLayers(mDrawingState.layersSortedByZ);
1189 clearHwcLayers(mCurrentState.layersSortedByZ);
1190 // Clear the drawing state so that the logic inside of
1191 // handleTransactionLocked will fire. It will determine the delta between
1192 // mCurrentState and mDrawingState and re-apply all changes when we make the
1193 // transition.
1194 mDrawingState.displays.clear();
1195 mDisplays.clear();
1196}
1197
1198void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001199 bool enteringVrMode = mEnterVrMode;
1200 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1201 return;
1202 }
1203 if (enteringVrMode && !mVrHwc) {
1204 // Construct new HWComposer without holding any locks.
1205 mVrHwc = new HWComposer(true);
1206 ALOGV("Vr HWC created");
1207 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001208 {
1209 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001210
1211 if (enteringVrMode) {
1212 // Start vrflinger thread, if it hasn't been started already.
1213 if (!mVrFlinger) {
1214 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1215 int err = mVrFlinger->Run(mHwc->getComposer());
1216 if (err != NO_ERROR) {
1217 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1218 mVrFlinger.reset();
1219 mEnterVrMode = false;
1220 return;
1221 }
1222 }
1223
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001224 resetHwc();
1225
1226 mHwc = mVrHwc;
1227 mVrFlinger->EnterVrMode();
1228 } else {
1229 mVrFlinger->ExitVrMode();
1230
1231 resetHwc();
1232
1233 mHwc = mRealHwc;
1234 enableHardwareVsync();
1235 }
1236
1237 mVisibleRegionsDirty = true;
1238 invalidateHwcGeometry();
1239 android_atomic_or(1, &mRepaintEverything);
1240 setTransactionFlags(eDisplayTransactionNeeded);
1241 }
1242 if (mVrHwc) {
1243 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1244 }
1245}
1246
Mathias Agopian4fec8732012-06-29 14:12:52 -07001247void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001248 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001250 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001251 // TODO(eieio): Tied to a conditional until SELinux issues
1252 // are resolved.
1253 if (mVrModeSupported) {
1254 updateVrMode();
1255 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001256
Dan Stoza50182882016-07-08 12:02:20 -07001257 bool frameMissed = !mHadClientComposition &&
1258 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001259 (mPreviousPresentFence->getSignalTime() ==
1260 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001261 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001262 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001263 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001264 signalLayerUpdate();
1265 break;
1266 }
1267
Dan Stoza6b9454d2014-11-07 16:00:59 -08001268 bool refreshNeeded = handleMessageTransaction();
1269 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001270 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001271 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001272 // Signal a refresh if a transaction modified the window state,
1273 // a new buffer was latched, or if HWC has requested a full
1274 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001275 signalRefresh();
1276 }
1277 break;
1278 }
1279 case MessageQueue::REFRESH: {
1280 handleMessageRefresh();
1281 break;
1282 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283 }
1284}
1285
Dan Stoza6b9454d2014-11-07 16:00:59 -08001286bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001287 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001288 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001289 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001290 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001291 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001292 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001293}
1294
Dan Stoza6b9454d2014-11-07 16:00:59 -08001295bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001296 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001297 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001298}
1299
1300void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001301 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001302
Pablo Ceballos40845df2016-01-25 17:41:15 -08001303 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001304
Brian Andersond6927fb2016-07-23 23:37:30 -07001305 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001306 rebuildLayerStacks();
1307 setUpHWComposer();
1308 doDebugFlashRegions();
1309 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001310 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001311
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001312 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001313
1314 mHadClientComposition = false;
1315 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1316 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1317 mHadClientComposition = mHadClientComposition ||
1318 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1319 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001320
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001322}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001323
Mathias Agopiancd60f992012-08-16 16:28:27 -07001324void SurfaceFlinger::doDebugFlashRegions()
1325{
1326 // is debugging enabled
1327 if (CC_LIKELY(!mDebugRegion))
1328 return;
1329
1330 const bool repaintEverything = mRepaintEverything;
1331 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1332 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001333 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001334 // transform the dirty region into this screen's coordinate space
1335 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1336 if (!dirtyRegion.isEmpty()) {
1337 // redraw the whole screen
1338 doComposeSurfaces(hw, Region(hw->bounds()));
1339
1340 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001341 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001342 RenderEngine& engine(getRenderEngine());
1343 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1344
Mathias Agopianda27af92012-09-13 18:17:13 -07001345 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001346 }
1347 }
1348 }
1349
1350 postFramebuffer();
1351
1352 if (mDebugRegion > 1) {
1353 usleep(mDebugRegion * 1000);
1354 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001355
Dan Stoza9e56aa02015-11-02 13:00:03 -08001356 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001357 auto& displayDevice = mDisplays[displayId];
1358 if (!displayDevice->isDisplayOn()) {
1359 continue;
1360 }
1361
1362 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001363 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1364 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001365 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001366}
1367
Brian Andersond6927fb2016-07-23 23:37:30 -07001368void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001369{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 ATRACE_CALL();
1371 ALOGV("preComposition");
1372
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001374 mDrawingState.traverseInZOrder([&](Layer* layer) {
1375 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376 needExtraInvalidate = true;
1377 }
Robert Carr2047fae2016-11-28 14:09:09 -08001378 });
1379
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380 if (needExtraInvalidate) {
1381 signalLayerUpdate();
1382 }
1383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::updateCompositorTiming(
1386 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1387 std::shared_ptr<FenceTime>& presentFenceTime) {
1388 // Update queue of past composite+present times and determine the
1389 // most recently known composite to present latency.
1390 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1391 nsecs_t compositeToPresentLatency = -1;
1392 while (!mCompositePresentTimes.empty()) {
1393 CompositePresentTime& cpt = mCompositePresentTimes.front();
1394 // Cached values should have been updated before calling this method,
1395 // which helps avoid duplicate syscalls.
1396 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1397 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1398 break;
1399 }
1400 compositeToPresentLatency = displayTime - cpt.composite;
1401 mCompositePresentTimes.pop();
1402 }
1403
1404 // Don't let mCompositePresentTimes grow unbounded, just in case.
1405 while (mCompositePresentTimes.size() > 16) {
1406 mCompositePresentTimes.pop();
1407 }
1408
1409 // Integer division and modulo round toward 0 not -inf, so we need to
1410 // treat negative and positive offsets differently.
1411 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1412 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1413 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1414
1415 // Snap the latency to a value that removes scheduling jitter from the
1416 // composition and present times, which often have >1ms of jitter.
1417 // Reducing jitter is important if an app attempts to extrapolate
1418 // something (such as user input) to an accurate diasplay time.
1419 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1420 // with (presentLatency % interval).
1421 nsecs_t snappedCompositeToPresentLatency = -1;
1422 if (compositeToPresentLatency >= 0) {
1423 nsecs_t bias = vsyncInterval / 2;
1424 int64_t extraVsyncs =
1425 (compositeToPresentLatency - idealLatency + bias) /
1426 vsyncInterval;
1427 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1428 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1429 }
1430
1431 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1432 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1433 mCompositorTiming.interval = vsyncInterval;
1434 if (snappedCompositeToPresentLatency >= 0) {
1435 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1436 }
1437}
1438
1439void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001441 ATRACE_CALL();
1442 ALOGV("postComposition");
1443
Brian Anderson3546a3f2016-07-14 11:51:14 -07001444 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001445 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001446 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001447 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001448 }
1449
Brian Andersond6927fb2016-07-23 23:37:30 -07001450 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001451
1452 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1453 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1454 glCompositionDoneFenceTime =
1455 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1456 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1457 } else {
1458 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1459 }
1460 mGlCompositionDoneTimeline.updateSignalTimes();
1461
1462 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1463 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1464 mDisplayTimeline.push(displayFenceTime);
1465 mDisplayTimeline.updateSignalTimes();
1466
1467 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1468 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1469 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1470 presentFenceTime = &displayFenceTime;
1471 } else {
1472 retireFenceTime = &displayFenceTime;
1473 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001474
1475 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1476 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1477
1478 // We use the refreshStartTime which might be sampled a little later than
1479 // when we started doing work for this frame, but that should be okay
1480 // since updateCompositorTiming has snapping logic.
1481 updateCompositorTiming(
1482 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1483
Robert Carr2047fae2016-11-28 14:09:09 -08001484 mDrawingState.traverseInZOrder([&](Layer* layer) {
1485 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001487 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001488 recordBufferingStats(layer->getName().string(),
1489 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001490 }
Robert Carr2047fae2016-11-28 14:09:09 -08001491 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001492
Brian Anderson3d4039d2016-09-23 16:31:30 -07001493 if (displayFence->isValid()) {
1494 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001495 enableHardwareVsync();
1496 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001497 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001498 }
1499 }
1500
Andy McFadden5167ec62014-05-22 13:08:43 -07001501 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001502 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001503 enableHardwareVsync();
1504 }
1505 }
1506
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001507 if (mAnimCompositionPending) {
1508 mAnimCompositionPending = false;
1509
Brian Anderson3d4039d2016-09-23 16:31:30 -07001510 if (displayFenceTime->isValid()) {
1511 mAnimFrameTracker.setActualPresentFence(
1512 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001513 } else {
1514 // The HWC doesn't support present fences, so use the refresh
1515 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 nsecs_t presentTime =
1517 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001518 mAnimFrameTracker.setActualPresentTime(presentTime);
1519 }
1520 mAnimFrameTracker.advanceFrame();
1521 }
Dan Stozab90cf072015-03-05 11:05:59 -08001522
1523 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1524 return;
1525 }
1526
1527 nsecs_t currentTime = systemTime();
1528 if (mHasPoweredOff) {
1529 mHasPoweredOff = false;
1530 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001531 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001533 if (numPeriods < NUM_BUCKETS - 1) {
1534 mFrameBuckets[numPeriods] += elapsedTime;
1535 } else {
1536 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1537 }
1538 mTotalTime += elapsedTime;
1539 }
1540 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541}
1542
1543void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 ATRACE_CALL();
1545 ALOGV("rebuildLayerStacks");
1546
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001548 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1549 ATRACE_CALL();
1550 mVisibleRegionsDirty = false;
1551 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001552
Jeff Sharkey76488112017-02-27 14:15:18 -07001553 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1554 Region opaqueRegion;
1555 Region dirtyRegion;
1556 Vector<sp<Layer>> layersSortedByZ;
1557 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1558 const Transform& tr(displayDevice->getTransform());
1559 const Rect bounds(displayDevice->getBounds());
1560 if (displayDevice->isDisplayOn()) {
1561 computeVisibleRegions(
1562 displayDevice->getLayerStack(), dirtyRegion,
1563 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001564
Jeff Sharkey76488112017-02-27 14:15:18 -07001565 mDrawingState.traverseInZOrder([&](Layer* layer) {
1566 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1567 Region drawRegion(tr.transform(
1568 layer->visibleNonTransparentRegion));
1569 drawRegion.andSelf(bounds);
1570 if (!drawRegion.isEmpty()) {
1571 layersSortedByZ.add(layer);
1572 } else {
1573 // Clear out the HWC layer if this layer was
1574 // previously visible, but no longer is
1575 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1576 nullptr);
1577 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001578 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001579 // WM changes displayDevice->layerStack upon sleep/awake.
1580 // Here we make sure we delete the HWC layers even if
1581 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001582 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1583 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001584 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001585 });
1586 }
1587 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1588 displayDevice->undefinedRegion.set(bounds);
1589 displayDevice->undefinedRegion.subtractSelf(
1590 tr.transform(opaqueRegion));
1591 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001592 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001593 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001595
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001597 ATRACE_CALL();
1598 ALOGV("setUpHWComposer");
1599
Jesse Hall028dc8f2013-08-20 16:35:32 -07001600 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001601 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1602 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1603 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1604
1605 // If nothing has changed (!dirty), don't recompose.
1606 // If something changed, but we don't currently have any visible layers,
1607 // and didn't when we last did a composition, then skip it this time.
1608 // The second rule does two things:
1609 // - When all layers are removed from a display, we'll emit one black
1610 // frame, then nothing more until we get new layers.
1611 // - When a display is created with a private layer stack, we won't
1612 // emit any black frames until a layer is added to the layer stack.
1613 bool mustRecompose = dirty && !(empty && wasEmpty);
1614
1615 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1616 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1617 mustRecompose ? "doing" : "skipping",
1618 dirty ? "+" : "-",
1619 empty ? "+" : "-",
1620 wasEmpty ? "+" : "-");
1621
Dan Stoza71433162014-02-04 16:22:36 -08001622 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001623
1624 if (mustRecompose) {
1625 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1626 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001627 }
1628
Dan Stoza9e56aa02015-11-02 13:00:03 -08001629 // build the h/w work list
1630 if (CC_UNLIKELY(mGeometryInvalid)) {
1631 mGeometryInvalid = false;
1632 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1633 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1634 const auto hwcId = displayDevice->getHwcDisplayId();
1635 if (hwcId >= 0) {
1636 const Vector<sp<Layer>>& currentLayers(
1637 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001638 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001639 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 if (!layer->hasHwcLayer(hwcId)) {
1641 auto hwcLayer = mHwc->createLayer(hwcId);
1642 if (hwcLayer) {
1643 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1644 } else {
1645 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001647 }
1648 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001649
Robert Carrae060832016-11-28 10:51:00 -08001650 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001651 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001652 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001653 }
1654 }
1655 }
1656 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 }
Riley Andrews03414a12014-07-01 14:22:59 -07001658
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001659
1660 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1661
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 // Set the per-frame data
1663 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1664 auto& displayDevice = mDisplays[displayId];
1665 const auto hwcId = displayDevice->getHwcDisplayId();
1666 if (hwcId < 0) {
1667 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001668 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001669 if (colorMatrix != mPreviousColorMatrix) {
1670 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1671 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1672 "display %zd: %d", displayId, result);
1673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1675 layer->setPerFrameData(displayDevice);
1676 }
1677 }
1678
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001679 mPreviousColorMatrix = colorMatrix;
1680
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001682 auto& displayDevice = mDisplays[displayId];
1683 if (!displayDevice->isDisplayOn()) {
1684 continue;
1685 }
1686
1687 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001688 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1689 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001690 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001692
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693void SurfaceFlinger::doComposition() {
1694 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 ALOGV("doComposition");
1696
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001697 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001698 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001699 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001700 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701 // transform the dirty region into this screen's coordinate space
1702 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001703
1704 // repaint the framebuffer (if needed)
1705 doDisplayComposition(hw, dirtyRegion);
1706
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707 hw->dirtyRegion.clear();
1708 hw->flip(hw->swapRegion);
1709 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001710 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001712 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713}
1714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001715void SurfaceFlinger::postFramebuffer()
1716{
Mathias Agopian841cde52012-03-01 15:44:37 -08001717 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001719
Mathias Agopiana44b0412011-10-16 18:46:35 -07001720 const nsecs_t now = systemTime();
1721 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001722
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1724 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001725 if (!displayDevice->isDisplayOn()) {
1726 continue;
1727 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 const auto hwcId = displayDevice->getHwcDisplayId();
1729 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001730 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001731 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001732 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001733 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001734 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1735 sp<Fence> releaseFence = Fence::NO_FENCE;
1736 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1737 releaseFence = displayDevice->getClientTargetAcquireFence();
1738 } else {
1739 auto hwcLayer = layer->getHwcLayer(hwcId);
1740 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001741 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 layer->onLayerDisplayed(releaseFence);
1743 }
1744 if (hwcId >= 0) {
1745 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001746 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001747 }
1748
Mathias Agopiana44b0412011-10-16 18:46:35 -07001749 mLastSwapBufferTime = systemTime() - now;
1750 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001751
1752 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1753 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1754 logFrameStats();
1755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001756}
1757
Mathias Agopian87baae12012-07-31 12:38:26 -07001758void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001759{
Mathias Agopian841cde52012-03-01 15:44:37 -08001760 ATRACE_CALL();
1761
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001762 // here we keep a copy of the drawing state (that is the state that's
1763 // going to be overwritten by handleTransactionLocked()) outside of
1764 // mStateLock so that the side-effects of the State assignment
1765 // don't happen with mStateLock held (which can cause deadlocks).
1766 State drawingState(mDrawingState);
1767
Mathias Agopianca4d3602011-05-19 15:38:14 -07001768 Mutex::Autolock _l(mStateLock);
1769 const nsecs_t now = systemTime();
1770 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001771
Mathias Agopianca4d3602011-05-19 15:38:14 -07001772 // Here we're guaranteed that some transaction flags are set
1773 // so we can call handleTransactionLocked() unconditionally.
1774 // We call getTransactionFlags(), which will also clear the flags,
1775 // with mStateLock held to guarantee that mCurrentState won't change
1776 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001777
Mathias Agopiane57f2922012-08-09 16:29:12 -07001778 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001779 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001780
Mathias Agopianca4d3602011-05-19 15:38:14 -07001781 mLastTransactionTime = systemTime() - now;
1782 mDebugInTransaction = 0;
1783 invalidateHwcGeometry();
1784 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001785}
1786
Mathias Agopian87baae12012-07-31 12:38:26 -07001787void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001788{
Dan Stoza7dde5992015-05-22 09:51:44 -07001789 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001790 mCurrentState.traverseInZOrder([](Layer* layer) {
1791 layer->notifyAvailableFrames();
1792 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001794 /*
1795 * Traversal of the children
1796 * (perform the transaction for each of them if needed)
1797 */
1798
Mathias Agopian3559b072012-08-15 13:46:03 -07001799 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001800 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001802 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001803
1804 const uint32_t flags = layer->doTransaction(0);
1805 if (flags & Layer::eVisibleRegion)
1806 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001807 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001808 }
1809
1810 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001811 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812 */
1813
Mathias Agopiane57f2922012-08-09 16:29:12 -07001814 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001815 // here we take advantage of Vector's copy-on-write semantics to
1816 // improve performance by skipping the transaction entirely when
1817 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001818 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1819 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001820 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001822 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001823 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001824
1825 // find the displays that were removed
1826 // (ie: in drawing state but not in current state)
1827 // also handle displays that changed
1828 // (ie: displays that are in both lists)
1829 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001830 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1831 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001833 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001834 // Call makeCurrent() on the primary display so we can
1835 // be sure that nothing associated with this display
1836 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001837 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001838 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001839 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1840 if (hw != NULL)
1841 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001842 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001843 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001844 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001845 } else {
1846 ALOGW("trying to remove the main display");
1847 }
1848 } else {
1849 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001850 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001851 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001852 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1853 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001854 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001855 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001856 // recreating the DisplayDevice, so we just remove it
1857 // from the drawing state, so that it get re-added
1858 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001859 sp<DisplayDevice> hw(getDisplayDevice(display));
1860 if (hw != NULL)
1861 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001862 mDisplays.removeItem(display);
1863 mDrawingState.displays.removeItemsAt(i);
1864 dc--; i--;
1865 // at this point we must loop to the next item
1866 continue;
1867 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001868
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001869 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001870 if (disp != NULL) {
1871 if (state.layerStack != draw[i].layerStack) {
1872 disp->setLayerStack(state.layerStack);
1873 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001874 if ((state.orientation != draw[i].orientation)
1875 || (state.viewport != draw[i].viewport)
1876 || (state.frame != draw[i].frame))
1877 {
1878 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001879 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001880 }
Michael Lentine47e45402014-07-18 15:34:25 -07001881 if (state.width != draw[i].width || state.height != draw[i].height) {
1882 disp->setDisplaySize(state.width, state.height);
1883 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001884 }
1885 }
1886 }
1887
1888 // find displays that were added
1889 // (ie: in current state but not in drawing state)
1890 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001891 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001892 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001893
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001894 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001895 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001896 sp<IGraphicBufferProducer> bqProducer;
1897 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001898 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1899 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001902 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001903 // Virtual displays without a surface are dormant:
1904 // they have external state (layer stack, projection,
1905 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001906 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001907
Dan Stoza8cf150a2016-08-02 10:27:31 -07001908 if (mUseHwcVirtualDisplays) {
1909 int width = 0;
1910 int status = state.surface->query(
1911 NATIVE_WINDOW_WIDTH, &width);
1912 ALOGE_IF(status != NO_ERROR,
1913 "Unable to query width (%d)", status);
1914 int height = 0;
1915 status = state.surface->query(
1916 NATIVE_WINDOW_HEIGHT, &height);
1917 ALOGE_IF(status != NO_ERROR,
1918 "Unable to query height (%d)", status);
1919 int intFormat = 0;
1920 status = state.surface->query(
1921 NATIVE_WINDOW_FORMAT, &intFormat);
1922 ALOGE_IF(status != NO_ERROR,
1923 "Unable to query format (%d)", status);
1924 auto format = static_cast<android_pixel_format_t>(
1925 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001926
Dan Stoza8cf150a2016-08-02 10:27:31 -07001927 mHwc->allocateVirtualDisplay(width, height, &format,
1928 &hwcId);
1929 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930
Dan Stoza5cf424b2016-05-20 14:02:39 -07001931 // TODO: Plumb requested format back up to consumer
1932
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 sp<VirtualDisplaySurface> vds =
1934 new VirtualDisplaySurface(*mHwc,
1935 hwcId, state.surface, bqProducer,
1936 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001937
1938 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001939 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001940 }
1941 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001942 ALOGE_IF(state.surface!=NULL,
1943 "adding a supported display, but rendering "
1944 "surface is provided (%p), ignoring it",
1945 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001946
1947 hwcId = state.type;
1948 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1949 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001950 }
1951
1952 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001953 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001954 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 state.type, hwcId, state.isSecure, display,
1956 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001957 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001958 hw->setLayerStack(state.layerStack);
1959 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001960 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001961 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001962 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001964 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001965 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001966 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001967 }
1968 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001970 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971
Mathias Agopian84300952012-11-21 16:02:13 -08001972 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1973 // The transform hint might have changed for some layers
1974 // (either because a display has changed, or because a layer
1975 // as changed).
1976 //
1977 // Walk through all the layers in currentLayers,
1978 // and update their transform hint.
1979 //
1980 // If a layer is visible only on a single display, then that
1981 // display is used to calculate the hint, otherwise we use the
1982 // default display.
1983 //
1984 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1985 // the hint is set before we acquire a buffer from the surface texture.
1986 //
1987 // NOTE: layer transactions have taken place already, so we use their
1988 // drawing state. However, SurfaceFlinger's own transaction has not
1989 // happened yet, so we must use the current state layer list
1990 // (soon to become the drawing state list).
1991 //
1992 sp<const DisplayDevice> disp;
1993 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001994 bool first = true;
1995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001996 // NOTE: we rely on the fact that layers are sorted by
1997 // layerStack first (so we don't have to traverse the list
1998 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001999 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002000 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002001 currentlayerStack = layerStack;
2002 // figure out if this layerstack is mirrored
2003 // (more than one display) if so, pick the default display,
2004 // if not, pick the only display it's on.
2005 disp.clear();
2006 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2007 sp<const DisplayDevice> hw(mDisplays[dpy]);
2008 if (hw->getLayerStack() == currentlayerStack) {
2009 if (disp == NULL) {
2010 disp = hw;
2011 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002012 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002013 break;
2014 }
2015 }
2016 }
2017 }
Chet Haase91d25932013-04-11 15:24:55 -07002018 if (disp == NULL) {
2019 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2020 // redraw after transform hint changes. See bug 8508397.
2021
2022 // could be null when this layer is using a layerStack
2023 // that is not visible on any display. Also can occur at
2024 // screen off/on times.
2025 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002026 }
Chet Haase91d25932013-04-11 15:24:55 -07002027 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002028
2029 first = false;
2030 });
Mathias Agopian84300952012-11-21 16:02:13 -08002031 }
2032
2033
Mathias Agopian3559b072012-08-15 13:46:03 -07002034 /*
2035 * Perform our own transaction if needed
2036 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002037
2038 if (mLayersAdded) {
2039 mLayersAdded = false;
2040 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002041 mVisibleRegionsDirty = true;
2042 }
2043
2044 // some layers might have been removed, so
2045 // we need to update the regions they're exposing.
2046 if (mLayersRemoved) {
2047 mLayersRemoved = false;
2048 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002049 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002050 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002051 // this layer is not visible anymore
2052 // TODO: we could traverse the tree from front to back and
2053 // compute the actual visible region
2054 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002055 Region visibleReg;
2056 visibleReg.set(layer->computeScreenBounds());
2057 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002058 }
Robert Carr2047fae2016-11-28 14:09:09 -08002059 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060 }
2061
2062 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002063
2064 updateCursorAsync();
2065}
2066
2067void SurfaceFlinger::updateCursorAsync()
2068{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2070 auto& displayDevice = mDisplays[displayId];
2071 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002072 continue;
2073 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074
2075 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2076 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002077 }
2078 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002079}
2080
2081void SurfaceFlinger::commitTransaction()
2082{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002083 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002085 for (const auto& l : mLayersPendingRemoval) {
2086 recordBufferingStats(l->getName().string(),
2087 l->getOccupancyHistory(true));
2088 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002089 }
2090 mLayersPendingRemoval.clear();
2091 }
2092
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002093 // If this transaction is part of a window animation then the next frame
2094 // we composite should be considered an animation as well.
2095 mAnimCompositionPending = mAnimTransactionPending;
2096
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002098 mDrawingState.traverseInZOrder([](Layer* layer) {
2099 layer->commitChildList();
2100 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002101 mTransactionPending = false;
2102 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104}
2105
Robert Carr2047fae2016-11-28 14:09:09 -08002106void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002107 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108{
Mathias Agopian841cde52012-03-01 15:44:37 -08002109 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112 Region aboveOpaqueLayers;
2113 Region aboveCoveredLayers;
2114 Region dirty;
2115
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117
Robert Carr2047fae2016-11-28 14:09:09 -08002118 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002120 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121
Jesse Hall01e29052013-02-19 16:13:35 -08002122 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002123 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002124 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002125
Mathias Agopianab028732010-03-16 16:41:46 -07002126 /*
2127 * opaqueRegion: area of a surface that is fully opaque.
2128 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002130
2131 /*
2132 * visibleRegion: area of a surface that is visible on screen
2133 * and not fully transparent. This is essentially the layer's
2134 * footprint minus the opaque regions above it.
2135 * Areas covered by a translucent surface are considered visible.
2136 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002138
2139 /*
2140 * coveredRegion: area of a surface that is covered by all
2141 * visible regions above it (which includes the translucent areas).
2142 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002144
Jesse Halla8026d22012-09-25 13:25:04 -07002145 /*
2146 * transparentRegion: area of a surface that is hinted to be completely
2147 * transparent. This is only used to tell when the layer has no visible
2148 * non-transparent regions and can be removed from the layer list. It
2149 * does not affect the visibleRegion of this layer or any layers
2150 * beneath it. The hint may not be correct if apps don't respect the
2151 * SurfaceView restrictions (which, sadly, some don't).
2152 */
2153 Region transparentRegion;
2154
Mathias Agopianab028732010-03-16 16:41:46 -07002155
2156 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002157 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002158 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002159 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002161 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002162 if (!visibleRegion.isEmpty()) {
2163 // Remove the transparent area from the visible region
2164 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002165 if (tr.preserveRects()) {
2166 // transform the transparent region
2167 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002168 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002169 // transformation too complex, can't do the
2170 // transparent region optimization.
2171 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002172 }
Mathias Agopianab028732010-03-16 16:41:46 -07002173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174
Mathias Agopianab028732010-03-16 16:41:46 -07002175 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002178 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2179 // the opaque region is the layer's footprint
2180 opaqueRegion = visibleRegion;
2181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002182 }
2183 }
2184
Mathias Agopianab028732010-03-16 16:41:46 -07002185 // Clip the covered region to the visible region
2186 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2187
2188 // Update aboveCoveredLayers for next (lower) layer
2189 aboveCoveredLayers.orSelf(visibleRegion);
2190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191 // subtract the opaque region covered by the layers above us
2192 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
2194 // compute this layer's dirty region
2195 if (layer->contentDirty) {
2196 // we need to invalidate the whole region
2197 dirty = visibleRegion;
2198 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002199 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 layer->contentDirty = false;
2201 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002202 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002203 * the exposed region consists of two components:
2204 * 1) what's VISIBLE now and was COVERED before
2205 * 2) what's EXPOSED now less what was EXPOSED before
2206 *
2207 * note that (1) is conservative, we start with the whole
2208 * visible region but only keep what used to be covered by
2209 * something -- which mean it may have been exposed.
2210 *
2211 * (2) handles areas that were not covered by anything but got
2212 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002213 */
Mathias Agopianab028732010-03-16 16:41:46 -07002214 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002215 const Region oldVisibleRegion = layer->visibleRegion;
2216 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002217 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2218 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219 }
2220 dirty.subtractSelf(aboveOpaqueLayers);
2221
2222 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002223 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224
Mathias Agopianab028732010-03-16 16:41:46 -07002225 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002227
Jesse Halla8026d22012-09-25 13:25:04 -07002228 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229 layer->setVisibleRegion(visibleRegion);
2230 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002231 layer->setVisibleNonTransparentRegion(
2232 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002233 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopian87baae12012-07-31 12:38:26 -07002235 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236}
2237
Mathias Agopian87baae12012-07-31 12:38:26 -07002238void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2239 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002240 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002241 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2242 if (hw->getLayerStack() == layerStack) {
2243 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002244 }
2245 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002246}
2247
Dan Stoza6b9454d2014-11-07 16:00:59 -08002248bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002249{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002250 ALOGV("handlePageFlip");
2251
Brian Andersond6927fb2016-07-23 23:37:30 -07002252 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopian4fec8732012-06-29 14:12:52 -07002254 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002255 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002256
2257 // Store the set of layers that need updates. This set must not change as
2258 // buffers are being latched, as this could result in a deadlock.
2259 // Example: Two producers share the same command stream and:
2260 // 1.) Layer 0 is latched
2261 // 2.) Layer 0 gets a new frame
2262 // 2.) Layer 1 gets a new frame
2263 // 3.) Layer 1 is latched.
2264 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2265 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002266 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267 if (layer->hasQueuedFrame()) {
2268 frameQueued = true;
2269 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002270 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002271 } else {
2272 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002273 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002274 } else {
2275 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002276 }
Robert Carr2047fae2016-11-28 14:09:09 -08002277 });
2278
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002280 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002281 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002283 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002284
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002285 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286
2287 // If we will need to wake up at some time in the future to deal with a
2288 // queued frame that shouldn't be displayed during this vsync period, wake
2289 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002291 signalLayerUpdate();
2292 }
2293
2294 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002295 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Mathias Agopianad456f92011-01-13 17:53:01 -08002298void SurfaceFlinger::invalidateHwcGeometry()
2299{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002300 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002301}
2302
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002303
Fabien Sanglard830b8472016-11-30 16:35:58 -08002304void SurfaceFlinger::doDisplayComposition(
2305 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002306 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307{
Dan Stoza71433162014-02-04 16:22:36 -08002308 // We only need to actually compose the display if:
2309 // 1) It is being handled by hardware composer, which may need this to
2310 // keep its virtual display state machine in sync, or
2311 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002312 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002313 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002315 return;
2316 }
2317
Dan Stoza9e56aa02015-11-02 13:00:03 -08002318 ALOGV("doDisplayComposition");
2319
Mathias Agopian87baae12012-07-31 12:38:26 -07002320 Region dirtyRegion(inDirtyRegion);
2321
Mathias Agopianb8a55602009-06-26 19:06:36 -07002322 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002323 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324
Fabien Sanglard830b8472016-11-30 16:35:58 -08002325 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002326 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002327 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2328 // takes a rectangle, we must make sure to update that whole
2329 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002330 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002331 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002332 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002333 // We need to redraw the rectangle that will be updated
2334 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002335 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002336 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002338 } else {
2339 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 dirtyRegion.set(displayDevice->bounds());
2341 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 }
2343 }
2344
Fabien Sanglard830b8472016-11-30 16:35:58 -08002345 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002347 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002348 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002349
2350 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002351 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352}
2353
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354bool SurfaceFlinger::doComposeSurfaces(
2355 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002356{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002358
Dan Stoza9e56aa02015-11-02 13:00:03 -08002359 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002360
2361 mat4 oldColorMatrix;
2362 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2363 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2364 if (applyColorMatrix) {
2365 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2366 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2367 }
2368
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2370 if (hasClientComposition) {
2371 ALOGV("hasClientComposition");
2372
2373 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002374 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002376 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2377 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2378 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2379 }
2380 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002381 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002382
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002383 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002384 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2385 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002386 // when using overlays, we assume a fully transparent framebuffer
2387 // NOTE: we could reduce how much we need to clear, for instance
2388 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002389 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002390 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002392 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002393 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002395
2396 // we remove the scissor part
2397 // we're left with the letterbox region
2398 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002399 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002400
2401 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002402 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002403
2404 // but limit it to the dirty region
2405 region.andSelf(dirty);
2406
Mathias Agopianb9494d52012-04-18 02:28:45 -07002407 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002408 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002411 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002412 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002413
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002415 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002416 // scissor on the main display. It should never be needed
2417 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 const Rect& bounds(displayDevice->getBounds());
2419 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002420 if (scissor != bounds) {
2421 // scissor doesn't match the screen's dimensions, so we
2422 // need to clear everything outside of it and enable
2423 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002424
Mathias Agopianf45c5102012-10-24 16:29:17 -07002425 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 const uint32_t height = displayDevice->getHeight();
2427 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002428 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002429 }
2430 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002431 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002432
Mathias Agopian85d751c2012-08-29 16:59:24 -07002433 /*
2434 * and then, render the layers targeted at the framebuffer
2435 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002436
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("Rendering client layers");
2438 const Transform& displayTransform = displayDevice->getTransform();
2439 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002440 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 bool firstLayer = true;
2442 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2443 const Region clip(dirty.intersect(
2444 displayTransform.transform(layer->visibleRegion)));
2445 ALOGV("Layer: %s", layer->getName().string());
2446 ALOGV(" Composition type: %s",
2447 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002448 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002449 switch (layer->getCompositionType(hwcId)) {
2450 case HWC2::Composition::Cursor:
2451 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002452 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002454 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2456 layer->isOpaque(state) && (state.alpha == 1.0f)
2457 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002458 // never clear the very first layer since we're
2459 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002460 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002461 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002462 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002463 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 case HWC2::Composition::Client: {
2465 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002466 break;
2467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002469 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 } else {
2472 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 }
2476 } else {
2477 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002479 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002483 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002484 }
2485 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002486
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002487 if (applyColorMatrix) {
2488 getRenderEngine().setupColorTransform(oldColorMatrix);
2489 }
2490
Mathias Agopianf45c5102012-10-24 16:29:17 -07002491 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002493 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494}
2495
Fabien Sanglard830b8472016-11-30 16:35:58 -08002496void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2497 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002498 RenderEngine& engine(getRenderEngine());
2499 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500}
2501
Dan Stoza7d89d062015-04-30 13:29:25 -07002502status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002503 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002504 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002505 const sp<Layer>& lbc,
2506 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002507{
Dan Stoza7d89d062015-04-30 13:29:25 -07002508 // add this layer to the current state list
2509 {
2510 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002512 return NO_MEMORY;
2513 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 if (parent == nullptr) {
2515 mCurrentState.layersSortedByZ.add(lbc);
2516 } else {
2517 parent->addChild(lbc);
2518 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002519 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 mLayersAdded = true;
2521 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002522 }
2523
Mathias Agopian96f08192010-06-02 23:28:45 -07002524 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002525 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002526
Dan Stoza7d89d062015-04-30 13:29:25 -07002527 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002528}
2529
Robert Carr9524cb32017-02-13 11:32:32 -08002530status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002531 const auto& p = layer->getParent();
2532 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2533 mCurrentState.layersSortedByZ.remove(layer);
2534
Robert Carr136e2f62017-02-08 17:54:29 -08002535 // As a matter of normal operation, the LayerCleaner will produce a second
2536 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2537 // so we will succeed in promoting it, but it's already been removed
2538 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2539 // otherwise something has gone wrong and we are leaking the layer.
2540 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002541 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2542 layer->getName().string(),
2543 (p != nullptr) ? p->getName().string() : "no-parent");
2544 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002545 } else if (index < 0) {
2546 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002547 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548
2549 mLayersPendingRemoval.add(layer);
2550 mLayersRemoved = true;
2551 mNumLayers--;
2552 setTransactionFlags(eTransactionNeeded);
2553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554}
2555
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002556uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002557 return android_atomic_release_load(&mTransactionFlags);
2558}
2559
Mathias Agopian3f844832013-08-07 21:24:32 -07002560uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2562}
2563
Mathias Agopian3f844832013-08-07 21:24:32 -07002564uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2566 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002567 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 }
2569 return old;
2570}
2571
Mathias Agopian8b33f032012-07-24 20:43:54 -07002572void SurfaceFlinger::setTransactionState(
2573 const Vector<ComposerState>& state,
2574 const Vector<DisplayState>& displays,
2575 uint32_t flags)
2576{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002577 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002578 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002579 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002580
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002581 if (flags & eAnimation) {
2582 // For window updates that are part of an animation we must wait for
2583 // previous animation "frames" to be handled.
2584 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002585 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002586 if (CC_UNLIKELY(err != NO_ERROR)) {
2587 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002588 // caller after a few seconds.
2589 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2590 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002591 mAnimTransactionPending = false;
2592 break;
2593 }
2594 }
2595 }
2596
Mathias Agopiane57f2922012-08-09 16:29:12 -07002597 size_t count = displays.size();
2598 for (size_t i=0 ; i<count ; i++) {
2599 const DisplayState& s(displays[i]);
2600 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002601 }
2602
Mathias Agopiane57f2922012-08-09 16:29:12 -07002603 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002604 for (size_t i=0 ; i<count ; i++) {
2605 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002606 // Here we need to check that the interface we're given is indeed
2607 // one of our own. A malicious client could give us a NULL
2608 // IInterface, or one of its own or even one of our own but a
2609 // different type. All these situations would cause us to crash.
2610 //
2611 // NOTE: it would be better to use RTTI as we could directly check
2612 // that we have a Client*. however, RTTI is disabled in Android.
2613 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002614 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002615 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002616 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002617 sp<Client> client( static_cast<Client *>(s.client.get()) );
2618 transactionFlags |= setClientStateLocked(client, s.state);
2619 }
2620 }
2621 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002622 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002623
Robert Carr2a7dbb42016-05-24 11:41:28 -07002624 // If a synchronous transaction is explicitly requested without any changes,
2625 // force a transaction anyway. This can be used as a flush mechanism for
2626 // previous async transactions.
2627 if (transactionFlags == 0 && (flags & eSynchronous)) {
2628 transactionFlags = eTransactionNeeded;
2629 }
2630
Mathias Agopian386aa982011-11-07 21:58:03 -08002631 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002632 if (mInterceptor.isEnabled()) {
2633 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2634 }
Irvel468051e2016-06-13 16:44:44 -07002635
Mathias Agopian386aa982011-11-07 21:58:03 -08002636 // this triggers the transaction
2637 setTransactionFlags(transactionFlags);
2638
2639 // if this is a synchronous transaction, wait for it to take effect
2640 // before returning.
2641 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002642 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002643 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002644 if (flags & eAnimation) {
2645 mAnimTransactionPending = true;
2646 }
2647 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002648 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2649 if (CC_UNLIKELY(err != NO_ERROR)) {
2650 // just in case something goes wrong in SF, return to the
2651 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002652 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2653 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002654 break;
2655 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
2658}
2659
Mathias Agopiane57f2922012-08-09 16:29:12 -07002660uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2661{
Jesse Hall9a143922012-10-04 16:29:19 -07002662 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2663 if (dpyIdx < 0)
2664 return 0;
2665
Mathias Agopiane57f2922012-08-09 16:29:12 -07002666 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002667 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002668 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669 const uint32_t what = s.what;
2670 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002671 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002672 disp.surface = s.surface;
2673 flags |= eDisplayTransactionNeeded;
2674 }
2675 }
2676 if (what & DisplayState::eLayerStackChanged) {
2677 if (disp.layerStack != s.layerStack) {
2678 disp.layerStack = s.layerStack;
2679 flags |= eDisplayTransactionNeeded;
2680 }
2681 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002682 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 if (disp.orientation != s.orientation) {
2684 disp.orientation = s.orientation;
2685 flags |= eDisplayTransactionNeeded;
2686 }
2687 if (disp.frame != s.frame) {
2688 disp.frame = s.frame;
2689 flags |= eDisplayTransactionNeeded;
2690 }
2691 if (disp.viewport != s.viewport) {
2692 disp.viewport = s.viewport;
2693 flags |= eDisplayTransactionNeeded;
2694 }
2695 }
Michael Lentine47e45402014-07-18 15:34:25 -07002696 if (what & DisplayState::eDisplaySizeChanged) {
2697 if (disp.width != s.width) {
2698 disp.width = s.width;
2699 flags |= eDisplayTransactionNeeded;
2700 }
2701 if (disp.height != s.height) {
2702 disp.height = s.height;
2703 flags |= eDisplayTransactionNeeded;
2704 }
2705 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002706 }
2707 return flags;
2708}
2709
2710uint32_t SurfaceFlinger::setClientStateLocked(
2711 const sp<Client>& client,
2712 const layer_state_t& s)
2713{
2714 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002715 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002716 if (layer != 0) {
2717 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002718 bool geometryAppliesWithResize =
2719 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002720 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002721 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002722 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002723 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002724 }
2725 if (what & layer_state_t::eLayerChanged) {
2726 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727 const auto& p = layer->getParent();
2728 if (p == nullptr) {
2729 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2730 if (layer->setLayer(s.z) && idx >= 0) {
2731 mCurrentState.layersSortedByZ.removeAt(idx);
2732 mCurrentState.layersSortedByZ.add(layer);
2733 // we need traversal (state changed)
2734 // AND transaction (list changed)
2735 flags |= eTransactionNeeded|eTraversalNeeded;
2736 }
2737 } else {
2738 if (p->setChildLayer(layer, s.z)) {
2739 flags |= eTransactionNeeded|eTraversalNeeded;
2740 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 }
2742 }
2743 if (what & layer_state_t::eSizeChanged) {
2744 if (layer->setSize(s.w, s.h)) {
2745 flags |= eTraversalNeeded;
2746 }
2747 }
2748 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002750 flags |= eTraversalNeeded;
2751 }
2752 if (what & layer_state_t::eMatrixChanged) {
2753 if (layer->setMatrix(s.matrix))
2754 flags |= eTraversalNeeded;
2755 }
2756 if (what & layer_state_t::eTransparentRegionChanged) {
2757 if (layer->setTransparentRegionHint(s.transparentRegion))
2758 flags |= eTraversalNeeded;
2759 }
Dan Stoza23116082015-06-18 14:58:39 -07002760 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002761 if (layer->setFlags(s.flags, s.mask))
2762 flags |= eTraversalNeeded;
2763 }
2764 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002765 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002766 flags |= eTraversalNeeded;
2767 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002768 if (what & layer_state_t::eFinalCropChanged) {
2769 if (layer->setFinalCrop(s.finalCrop))
2770 flags |= eTraversalNeeded;
2771 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002772 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 // We only allow setting layer stacks for top level layers,
2775 // everything else inherits layer stack from its parent.
2776 if (layer->hasParent()) {
2777 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2778 layer->getName().string());
2779 } else if (idx < 0) {
2780 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2781 "that also does not appear in the top level layer list. Something"
2782 " has gone wrong.", layer->getName().string());
2783 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002784 mCurrentState.layersSortedByZ.removeAt(idx);
2785 mCurrentState.layersSortedByZ.add(layer);
2786 // we need traversal (state changed)
2787 // AND transaction (list changed)
2788 flags |= eTransactionNeeded|eTraversalNeeded;
2789 }
2790 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002791 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002792 if (s.barrierHandle != nullptr) {
2793 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2794 } else if (s.barrierGbp != nullptr) {
2795 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2796 if (authenticateSurfaceTextureLocked(gbp)) {
2797 const auto& otherLayer =
2798 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2799 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2800 } else {
2801 ALOGE("Attempt to defer transaction to to an"
2802 " unrecognized GraphicBufferProducer");
2803 }
2804 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002805 // We don't trigger a traversal here because if no other state is
2806 // changed, we don't want this to cause any more work
2807 }
Robert Carr1db73f62016-12-21 12:58:51 -08002808 if (what & layer_state_t::eReparentChildren) {
2809 if (layer->reparentChildren(s.reparentHandle)) {
2810 flags |= eTransactionNeeded|eTraversalNeeded;
2811 }
2812 }
Robert Carr9524cb32017-02-13 11:32:32 -08002813 if (what & layer_state_t::eDetachChildren) {
2814 layer->detachChildren();
2815 }
Robert Carrc3574f72016-03-24 12:19:32 -07002816 if (what & layer_state_t::eOverrideScalingModeChanged) {
2817 layer->setOverrideScalingMode(s.overrideScalingMode);
2818 // We don't trigger a traversal here because if no other state is
2819 // changed, we don't want this to cause any more work
2820 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002821 }
2822 return flags;
2823}
2824
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002825status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002826 const String8& name,
2827 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002828 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002829 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2830 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002832 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002833 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002834 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002835 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002836 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002837
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002838 status_t result = NO_ERROR;
2839
2840 sp<Layer> layer;
2841
Mathias Agopian3165cc22012-08-08 19:42:09 -07002842 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2843 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002844 result = createNormalLayer(client,
2845 name, w, h, flags, format,
2846 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002848 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002849 result = createDimLayer(client,
2850 name, w, h, flags,
2851 handle, gbp, &layer);
2852 break;
2853 default:
2854 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 break;
2856 }
2857
Dan Stoza7d89d062015-04-30 13:29:25 -07002858 if (result != NO_ERROR) {
2859 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002861
Albert Chaulk479c60c2017-01-27 14:21:34 -05002862 layer->setInfo(windowType, ownerUid);
2863
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002865 if (result != NO_ERROR) {
2866 return result;
2867 }
Irvelffc9efc2016-07-27 15:16:37 -07002868 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002869
2870 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002871 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002874status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2875 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2876 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877{
2878 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002879 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 case PIXEL_FORMAT_TRANSPARENT:
2881 case PIXEL_FORMAT_TRANSLUCENT:
2882 format = PIXEL_FORMAT_RGBA_8888;
2883 break;
2884 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002885 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 break;
2887 }
2888
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002889 *outLayer = new Layer(this, client, name, w, h, flags);
2890 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2891 if (err == NO_ERROR) {
2892 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002893 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002895
2896 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2897 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898}
2899
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002900status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2901 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2902 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002904 *outLayer = new LayerDim(this, client, name, w, h, flags);
2905 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002906 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002907 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002908}
2909
Mathias Agopianac9fa422013-02-11 16:40:36 -08002910status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911{
Robert Carr9524cb32017-02-13 11:32:32 -08002912 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002913 status_t err = NO_ERROR;
2914 sp<Layer> l(client->getLayerUser(handle));
2915 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002916 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002917 err = removeLayer(l);
2918 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2919 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002920 }
2921 return err;
2922}
2923
Mathias Agopian13127d82013-03-05 17:47:11 -08002924status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002925{
Mathias Agopian67106042013-03-14 19:18:13 -07002926 // called by ~LayerCleaner() when all references to the IBinder (handle)
2927 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002928 sp<Layer> l = layer.promote();
2929 if (l == nullptr) {
2930 // The layer has already been removed, carry on
2931 return NO_ERROR;
2932 } if (l->getParent() != nullptr) {
2933 // If we have a parent, then we can continue to live as long as it does.
2934 return NO_ERROR;
2935 }
2936 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937}
2938
Mathias Agopianb60314a2012-04-10 22:09:54 -07002939// ---------------------------------------------------------------------------
2940
Andy McFadden13a082e2012-08-24 10:16:42 -07002941void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002942 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002943 Vector<ComposerState> state;
2944 Vector<DisplayState> displays;
2945 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002946 d.what = DisplayState::eDisplayProjectionChanged |
2947 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002948 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002949 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002950 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002951 d.frame.makeInvalid();
2952 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002953 d.width = 0;
2954 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002955 displays.add(d);
2956 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002957 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002958
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2960 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002961 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002962
2963 {
2964 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2965 mCompositorTiming.interval = period;
2966 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002967}
2968
2969void SurfaceFlinger::initializeDisplays() {
2970 class MessageScreenInitialized : public MessageBase {
2971 SurfaceFlinger* flinger;
2972 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002973 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002974 virtual bool handler() {
2975 flinger->onInitializeDisplays();
2976 return true;
2977 }
2978 };
2979 sp<MessageBase> msg = new MessageScreenInitialized(this);
2980 postMessageAsync(msg); // we may be called from main thread, use async message
2981}
2982
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002983void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2984 int mode) {
2985 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2986 this);
2987 int32_t type = hw->getDisplayType();
2988 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002989
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002990 if (mode == currentMode) {
2991 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002992 return;
2993 }
2994
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002995 hw->setPowerMode(mode);
2996 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2997 ALOGW("Trying to set power mode for virtual display");
2998 return;
2999 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003000
Irvelffc9efc2016-07-27 15:16:37 -07003001 if (mInterceptor.isEnabled()) {
3002 Mutex::Autolock _l(mStateLock);
3003 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3004 if (idx < 0) {
3005 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3006 return;
3007 }
3008 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3009 }
3010
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003011 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003012 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003013 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003014 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3015 // FIXME: eventthread only knows about the main display right now
3016 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003017 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003020 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003021 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003022 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003023
3024 struct sched_param param = {0};
3025 param.sched_priority = 1;
3026 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3027 ALOGW("Couldn't set SCHED_FIFO on display on");
3028 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003030 // Turn off the display
3031 struct sched_param param = {0};
3032 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3033 ALOGW("Couldn't set SCHED_OTHER on display off");
3034 }
3035
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003036 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003037 disableHardwareVsync(true); // also cancels any in-progress resync
3038
Mathias Agopiancde87a32012-09-13 14:09:01 -07003039 // FIXME: eventthread only knows about the main display right now
3040 mEventThread->onScreenReleased();
3041 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003042
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 getHwComposer().setPowerMode(type, mode);
3044 mVisibleRegionsDirty = true;
3045 // from this point on, SF will stop drawing on this display
3046 } else {
3047 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003048 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003049}
3050
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3052 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003053 SurfaceFlinger& mFlinger;
3054 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003055 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003057 MessageSetPowerMode(SurfaceFlinger& flinger,
3058 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3059 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003060 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003061 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003062 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003063 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003064 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003065 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003066 ALOGW("Attempt to set power mode = %d for virtual display",
3067 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003068 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003069 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003070 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003071 return true;
3072 }
3073 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003075 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003076}
3077
3078// ---------------------------------------------------------------------------
3079
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3081{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003083
Mathias Agopianbd115332013-04-18 16:41:04 -07003084 IPCThreadState* ipc = IPCThreadState::self();
3085 const int pid = ipc->getCallingPid();
3086 const int uid = ipc->getCallingUid();
3087 if ((uid != AID_SHELL) &&
3088 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003089 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003090 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003092 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003093 // (this would indicate SF is stuck, but we want to be able to
3094 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003095 status_t err = mStateLock.timedLock(s2ns(1));
3096 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003097 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003098 result.appendFormat(
3099 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3100 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003101 }
3102
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003103 bool dumpAll = true;
3104 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003105 size_t numArgs = args.size();
3106 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003107 if ((index < numArgs) &&
3108 (args[index] == String16("--list"))) {
3109 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003111 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112 }
3113
3114 if ((index < numArgs) &&
3115 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003116 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003117 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003118 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003119 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--latency-clear"))) {
3123 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003124 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003125 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003126 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003127
3128 if ((index < numArgs) &&
3129 (args[index] == String16("--dispsync"))) {
3130 index++;
3131 mPrimaryDispSync.dump(result);
3132 dumpAll = false;
3133 }
Dan Stozab90cf072015-03-05 11:05:59 -08003134
3135 if ((index < numArgs) &&
3136 (args[index] == String16("--static-screen"))) {
3137 index++;
3138 dumpStaticScreenStats(result);
3139 dumpAll = false;
3140 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003141
3142 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003143 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003144 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003145 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003146 dumpAll = false;
3147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003151 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003152 }
3153
Mathias Agopian9795c422009-08-26 16:36:26 -07003154 if (locked) {
3155 mStateLock.unlock();
3156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 write(fd, result.string(), result.size());
3159 return NO_ERROR;
3160}
3161
Dan Stozac7014012014-02-14 15:03:43 -08003162void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3163 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003164{
Robert Carr2047fae2016-11-28 14:09:09 -08003165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003166 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003167 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003168}
3169
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003171 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003172{
3173 String8 name;
3174 if (index < args.size()) {
3175 name = String8(args[index]);
3176 index++;
3177 }
3178
Dan Stoza9e56aa02015-11-02 13:00:03 -08003179 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3180 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003181 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003182
3183 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003184 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003185 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003187 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003188 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003189 }
Robert Carr2047fae2016-11-28 14:09:09 -08003190 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003191 }
3192}
3193
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003194void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003195 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003196{
3197 String8 name;
3198 if (index < args.size()) {
3199 name = String8(args[index]);
3200 index++;
3201 }
3202
Robert Carr2047fae2016-11-28 14:09:09 -08003203 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003204 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003205 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003206 }
Robert Carr2047fae2016-11-28 14:09:09 -08003207 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003208
Svetoslavd85084b2014-03-20 10:28:31 -07003209 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003210}
3211
Jamie Gennis6547ff42013-07-16 20:12:42 -07003212// This should only be called from the main thread. Otherwise it would need
3213// the lock and should use mCurrentState rather than mDrawingState.
3214void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003215 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003216 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003218
3219 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3220}
3221
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003222void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003223{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003224 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003225#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003226 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003227#endif
3228#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003229 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003230#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003231 if (isLayerTripleBufferingDisabled())
3232 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003233 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003234}
3235
Dan Stozab90cf072015-03-05 11:05:59 -08003236void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3237{
3238 result.appendFormat("Static screen stats:\n");
3239 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3240 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3241 float percent = 100.0f *
3242 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3243 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3244 b + 1, bucketTimeSec, percent);
3245 }
3246 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3247 float percent = 100.0f *
3248 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3249 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3250 NUM_BUCKETS - 1, bucketTimeSec, percent);
3251}
3252
Dan Stozae77c7662016-05-13 11:37:28 -07003253void SurfaceFlinger::recordBufferingStats(const char* layerName,
3254 std::vector<OccupancyTracker::Segment>&& history) {
3255 Mutex::Autolock lock(mBufferingStatsMutex);
3256 auto& stats = mBufferingStats[layerName];
3257 for (const auto& segment : history) {
3258 if (!segment.usedThirdBuffer) {
3259 stats.twoBufferTime += segment.totalTime;
3260 }
3261 if (segment.occupancyAverage < 1.0f) {
3262 stats.doubleBufferedTime += segment.totalTime;
3263 } else if (segment.occupancyAverage < 2.0f) {
3264 stats.tripleBufferedTime += segment.totalTime;
3265 }
3266 ++stats.numSegments;
3267 stats.totalTime += segment.totalTime;
3268 }
3269}
3270
Brian Andersond6927fb2016-07-23 23:37:30 -07003271void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3272 result.appendFormat("Layer frame timestamps:\n");
3273
3274 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3275 const size_t count = currentLayers.size();
3276 for (size_t i=0 ; i<count ; i++) {
3277 currentLayers[i]->dumpFrameEvents(result);
3278 }
3279}
3280
Dan Stozae77c7662016-05-13 11:37:28 -07003281void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3282 result.append("Buffering stats:\n");
3283 result.append(" [Layer name] <Active time> <Two buffer> "
3284 "<Double buffered> <Triple buffered>\n");
3285 Mutex::Autolock lock(mBufferingStatsMutex);
3286 typedef std::tuple<std::string, float, float, float> BufferTuple;
3287 std::map<float, BufferTuple, std::greater<float>> sorted;
3288 for (const auto& statsPair : mBufferingStats) {
3289 const char* name = statsPair.first.c_str();
3290 const BufferingStats& stats = statsPair.second;
3291 if (stats.numSegments == 0) {
3292 continue;
3293 }
3294 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3295 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3296 stats.totalTime;
3297 float doubleBufferRatio = static_cast<float>(
3298 stats.doubleBufferedTime) / stats.totalTime;
3299 float tripleBufferRatio = static_cast<float>(
3300 stats.tripleBufferedTime) / stats.totalTime;
3301 sorted.insert({activeTime, {name, twoBufferRatio,
3302 doubleBufferRatio, tripleBufferRatio}});
3303 }
3304 for (const auto& sortedPair : sorted) {
3305 float activeTime = sortedPair.first;
3306 const BufferTuple& values = sortedPair.second;
3307 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3308 std::get<0>(values).c_str(), activeTime,
3309 std::get<1>(values), std::get<2>(values),
3310 std::get<3>(values));
3311 }
3312 result.append("\n");
3313}
3314
3315
Mathias Agopian74d211a2013-04-22 16:55:35 +02003316void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3317 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003318{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003319 bool colorize = false;
3320 if (index < args.size()
3321 && (args[index] == String16("--color"))) {
3322 colorize = true;
3323 index++;
3324 }
3325
3326 Colorizer colorizer(colorize);
3327
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003328 // figure out if we're stuck somewhere
3329 const nsecs_t now = systemTime();
3330 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3331 const nsecs_t inTransaction(mDebugInTransaction);
3332 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3333 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3334
3335 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003336 * Dump library configuration.
3337 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003338
3339 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003340 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003341 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003342 appendSfConfigString(result);
3343 appendUiConfigString(result);
3344 appendGuiConfigString(result);
3345 result.append("\n");
3346
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003347 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003348 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003349 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003350 result.append(SyncFeatures::getInstance().toString());
3351 result.append("\n");
3352
Dan Stoza9e56aa02015-11-02 13:00:03 -08003353 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3354
Andy McFadden41d67d72014-04-25 16:58:34 -07003355 colorizer.bold(result);
3356 result.append("DispSync configuration: ");
3357 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003358 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3359 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003360 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3361 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003362 result.append("\n");
3363
Dan Stozab90cf072015-03-05 11:05:59 -08003364 // Dump static screen stats
3365 result.append("\n");
3366 dumpStaticScreenStats(result);
3367 result.append("\n");
3368
Dan Stozae77c7662016-05-13 11:37:28 -07003369 dumpBufferingStats(result);
3370
Andy McFadden4803b742012-09-24 19:07:20 -07003371 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003372 * Dump the visible layer list
3373 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003374 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003375 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003376 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003377 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003378 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003379 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003380
3381 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003382 * Dump Display state
3383 */
3384
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003386 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003387 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003388 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3389 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003390 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003391 }
3392
3393 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003394 * Dump SurfaceFlinger global state
3395 */
3396
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003398 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003399 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003400
Mathias Agopian888c8222012-08-04 21:10:38 -07003401 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003402 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003403
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003404 colorizer.bold(result);
3405 result.appendFormat("EGL implementation : %s\n",
3406 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3407 colorizer.reset(result);
3408 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003409 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003410
Mathias Agopian875d8e12013-06-07 15:35:48 -07003411 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412
Mathias Agopian42977342012-08-05 00:40:46 -07003413 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003414 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3415 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003416 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003417 " last eglSwapBuffers() time: %f us\n"
3418 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003419 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420 " refresh-rate : %f fps\n"
3421 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003422 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003423 " gpu_to_cpu_unsupported : %d\n"
3424 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425 mLastSwapBufferTime/1000.0,
3426 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003427 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003428 1e9 / activeConfig->getVsyncPeriod(),
3429 activeConfig->getDpiX(),
3430 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003431 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003432
Mathias Agopian74d211a2013-04-22 16:55:35 +02003433 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003434 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003435
Mathias Agopian74d211a2013-04-22 16:55:35 +02003436 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003437 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438
3439 /*
3440 * VSYNC state
3441 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003442 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003443 result.append("\n");
3444
3445 /*
3446 * HWC layer minidump
3447 */
3448 for (size_t d = 0; d < mDisplays.size(); d++) {
3449 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3450 int32_t hwcId = displayDevice->getHwcDisplayId();
3451 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3452 continue;
3453 }
3454
3455 result.appendFormat("Display %d HWC layers:\n", hwcId);
3456 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003457 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003458 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003459 });
Dan Stozae22aec72016-08-01 13:20:59 -07003460 result.append("\n");
3461 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003462
3463 /*
3464 * Dump HWComposer state
3465 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003466 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003467 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003468 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003469 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003470 result.appendFormat(" h/w composer %s\n",
3471 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003472 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003473
3474 /*
3475 * Dump gralloc state
3476 */
3477 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3478 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003479}
3480
Mathias Agopian13127d82013-03-05 17:47:11 -08003481const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003482SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003483 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003484 wp<IBinder> dpy;
3485 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3486 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3487 dpy = mDisplays.keyAt(i);
3488 break;
3489 }
3490 }
3491 if (dpy == NULL) {
3492 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3493 // Just use the primary display so we have something to return
3494 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3495 }
3496 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003497}
3498
Keun young Park63f165f2012-08-31 10:53:36 -07003499bool SurfaceFlinger::startDdmConnection()
3500{
3501 void* libddmconnection_dso =
3502 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3503 if (!libddmconnection_dso) {
3504 return false;
3505 }
3506 void (*DdmConnection_start)(const char* name);
3507 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003508 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003509 if (!DdmConnection_start) {
3510 dlclose(libddmconnection_dso);
3511 return false;
3512 }
3513 (*DdmConnection_start)(getServiceName());
3514 return true;
3515}
3516
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003517status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 switch (code) {
3519 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003520 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003522 case CLEAR_ANIMATION_FRAME_STATS:
3523 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003524 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003525 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 {
3527 // codes that require permission check
3528 IPCThreadState* ipc = IPCThreadState::self();
3529 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003530 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003531 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003532 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003533 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003534 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003536 break;
3537 }
Robert Carr1db73f62016-12-21 12:58:51 -08003538 /*
3539 * Calling setTransactionState is safe, because you need to have been
3540 * granted a reference to Client* and Handle* to do anything with it.
3541 *
3542 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3543 */
3544 case SET_TRANSACTION_STATE:
3545 case CREATE_SCOPED_CONNECTION:
3546 {
3547 return OK;
3548 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003549 case CAPTURE_SCREEN:
3550 {
3551 // codes that require permission check
3552 IPCThreadState* ipc = IPCThreadState::self();
3553 const int pid = ipc->getCallingPid();
3554 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003555 if ((uid != AID_GRAPHICS) &&
3556 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003557 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003558 return PERMISSION_DENIED;
3559 }
3560 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 }
3562 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003563 return OK;
3564}
3565
3566status_t SurfaceFlinger::onTransact(
3567 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3568{
3569 status_t credentialCheck = CheckTransactCodeCredentials(code);
3570 if (credentialCheck != OK) {
3571 return credentialCheck;
3572 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003573
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3575 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003576 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003577 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003578 IPCThreadState* ipc = IPCThreadState::self();
3579 const int pid = ipc->getCallingPid();
3580 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003581 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003582 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 return PERMISSION_DENIED;
3584 }
3585 int n;
3586 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003587 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003588 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 return NO_ERROR;
3590 case 1002: // SHOW_UPDATES
3591 n = data.readInt32();
3592 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003593 invalidateHwcGeometry();
3594 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003597 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003598 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003600 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003601 setTransactionFlags(
3602 eTransactionNeeded|
3603 eDisplayTransactionNeeded|
3604 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003605 return NO_ERROR;
3606 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003607 case 1006:{ // send empty update
3608 signalRefresh();
3609 return NO_ERROR;
3610 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003611 case 1008: // toggle use of hw composer
3612 n = data.readInt32();
3613 mDebugDisableHWC = n ? 1 : 0;
3614 invalidateHwcGeometry();
3615 repaintEverything();
3616 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003617 case 1009: // toggle use of transform hint
3618 n = data.readInt32();
3619 mDebugDisableTransformHint = n ? 1 : 0;
3620 invalidateHwcGeometry();
3621 repaintEverything();
3622 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003624 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625 reply->writeInt32(0);
3626 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003627 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003628 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629 return NO_ERROR;
3630 case 1013: {
3631 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003632 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3633 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003634 return NO_ERROR;
3635 }
3636 case 1014: {
3637 // daltonize
3638 n = data.readInt32();
3639 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003640 case 1:
3641 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3642 break;
3643 case 2:
3644 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3645 break;
3646 case 3:
3647 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3648 break;
3649 default:
3650 mDaltonizer.setType(ColorBlindnessType::None);
3651 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003652 }
3653 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003654 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003655 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003656 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003657 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003658 invalidateHwcGeometry();
3659 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003660 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003662 case 1015: {
3663 // apply a color matrix
3664 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003665 if (n) {
3666 // color matrix is sent as mat3 matrix followed by vec3
3667 // offset, then packed into a mat4 where the last row is
3668 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003669 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003670 for (size_t j = 0; j < 4; j++) {
3671 mColorMatrix[i][j] = data.readFloat();
3672 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003673 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003674 } else {
3675 mColorMatrix = mat4();
3676 }
3677 invalidateHwcGeometry();
3678 repaintEverything();
3679 return NO_ERROR;
3680 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003681 // This is an experimental interface
3682 // Needs to be shifted to proper binder interface when we productize
3683 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003684 n = data.readInt32();
3685 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003686 return NO_ERROR;
3687 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003688 case 1017: {
3689 n = data.readInt32();
3690 mForceFullDamage = static_cast<bool>(n);
3691 return NO_ERROR;
3692 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003693 case 1018: { // Modify Choreographer's phase offset
3694 n = data.readInt32();
3695 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3696 return NO_ERROR;
3697 }
3698 case 1019: { // Modify SurfaceFlinger's phase offset
3699 n = data.readInt32();
3700 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3701 return NO_ERROR;
3702 }
Irvel468051e2016-06-13 16:44:44 -07003703 case 1020: { // Layer updates interceptor
3704 n = data.readInt32();
3705 if (n) {
3706 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003707 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003708 }
3709 else{
3710 ALOGV("Interceptor disabled");
3711 mInterceptor.disable();
3712 }
3713 return NO_ERROR;
3714 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003715 case 1021: { // Disable HWC virtual displays
3716 n = data.readInt32();
3717 mUseHwcVirtualDisplays = !n;
3718 return NO_ERROR;
3719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 }
3721 }
3722 return err;
3723}
3724
Mathias Agopian53331da2011-08-22 21:44:41 -07003725void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003726 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003727 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003728}
3729
Mathias Agopian59119e62010-10-11 12:37:43 -07003730// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003731// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003732// ---------------------------------------------------------------------------
3733
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003734/* The code below is here to handle b/8734824
3735 *
3736 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003737 * from the surfaceflinger thread to the calling binder thread, where they
3738 * are executed. This allows the calling thread in the calling process to be
3739 * reused and not depend on having "enough" binder threads to handle the
3740 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003741 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003742class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003743 /* Parts of GraphicProducerWrapper are run on two different threads,
3744 * communicating by sending messages via Looper but also by shared member
3745 * data. Coherence maintenance is subtle and in places implicit (ugh).
3746 *
3747 * Don't rely on Looper's sendMessage/handleMessage providing
3748 * release/acquire semantics for any data not actually in the Message.
3749 * Data going from surfaceflinger to binder threads needs to be
3750 * synchronized explicitly.
3751 *
3752 * Barrier open/wait do provide release/acquire semantics. This provides
3753 * implicit synchronization for data coming back from binder to
3754 * surfaceflinger threads.
3755 */
3756
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003757 sp<IGraphicBufferProducer> impl;
3758 sp<Looper> looper;
3759 status_t result;
3760 bool exitPending;
3761 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003762 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003763 uint32_t code;
3764 Parcel const* data;
3765 Parcel* reply;
3766
3767 enum {
3768 MSG_API_CALL,
3769 MSG_EXIT
3770 };
3771
3772 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003773 * Called on surfaceflinger thread. This is called by our "fake"
3774 * BpGraphicBufferProducer. We package the data and reply Parcel and
3775 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003776 */
3777 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003778 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003779 this->code = code;
3780 this->data = &data;
3781 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003782 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003783 // if we've exited, we run the message synchronously right here.
3784 // note (JH): as far as I can tell from looking at the code, this
3785 // never actually happens. if it does, i'm not sure if it happens
3786 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 handleMessage(Message(MSG_API_CALL));
3788 } else {
3789 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003790 // Prevent stores to this->{code, data, reply} from being
3791 // reordered later than the construction of Message.
3792 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 looper->sendMessage(this, Message(MSG_API_CALL));
3794 barrier.wait();
3795 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003796 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 }
3798
3799 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003800 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003801 * call the real BpGraphicBufferProducer.
3802 */
3803 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003804 int what = message.what;
3805 // Prevent reads below from happening before the read from Message
3806 atomic_thread_fence(memory_order_acquire);
3807 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003808 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003809 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003810 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003811 exitRequested = true;
3812 }
3813 }
3814
3815public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003816 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003817 : impl(impl),
3818 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003819 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003820 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003821 exitRequested(false),
3822 code(0),
3823 data(NULL),
3824 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003825 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003826
Jesse Hallb154c422014-07-13 12:47:02 -07003827 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 status_t waitForResponse() {
3829 do {
3830 looper->pollOnce(-1);
3831 } while (!exitRequested);
3832 return result;
3833 }
3834
Jesse Hallb154c422014-07-13 12:47:02 -07003835 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003836 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003837 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003838 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003839 // Ensure this->result is visible to the binder thread before it
3840 // handles the message.
3841 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003842 looper->sendMessage(this, Message(MSG_EXIT));
3843 }
3844};
3845
3846
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003847status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3848 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003849 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003850 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003851 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003852
3853 if (CC_UNLIKELY(display == 0))
3854 return BAD_VALUE;
3855
3856 if (CC_UNLIKELY(producer == 0))
3857 return BAD_VALUE;
3858
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003859 // if we have secure windows on this display, never allow the screen capture
3860 // unless the producer interface is local (i.e.: we can take a screenshot for
3861 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003862 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003863
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003864 // Convert to surfaceflinger's internal rotation type.
3865 Transform::orientation_flags rotationFlags;
3866 switch (rotation) {
3867 case ISurfaceComposer::eRotateNone:
3868 rotationFlags = Transform::ROT_0;
3869 break;
3870 case ISurfaceComposer::eRotate90:
3871 rotationFlags = Transform::ROT_90;
3872 break;
3873 case ISurfaceComposer::eRotate180:
3874 rotationFlags = Transform::ROT_180;
3875 break;
3876 case ISurfaceComposer::eRotate270:
3877 rotationFlags = Transform::ROT_270;
3878 break;
3879 default:
3880 rotationFlags = Transform::ROT_0;
3881 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3882 break;
3883 }
3884
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003885 class MessageCaptureScreen : public MessageBase {
3886 SurfaceFlinger* flinger;
3887 sp<IBinder> display;
3888 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003889 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003890 uint32_t reqWidth, reqHeight;
3891 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003892 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003893 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003894 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003895 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003896 public:
3897 MessageCaptureScreen(SurfaceFlinger* flinger,
3898 const sp<IBinder>& display,
3899 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003900 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003901 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003902 bool useIdentityTransform,
3903 Transform::orientation_flags rotation,
3904 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003905 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003906 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003908 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003909 rotation(rotation), result(PERMISSION_DENIED),
3910 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003911 {
3912 }
3913 status_t getResult() const {
3914 return result;
3915 }
3916 virtual bool handler() {
3917 Mutex::Autolock _l(flinger->mStateLock);
3918 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003919 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003920 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003921 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003922 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003923 return true;
3924 }
3925 };
3926
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 // this creates a "fake" BBinder which will serve as a "fake" remote
3928 // binder to receive the marshaled calls and forward them to the
3929 // real remote (a BpGraphicBufferProducer)
3930 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3931
3932 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3933 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003934 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003935 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003936 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003937 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938
3939 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003940 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003941 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003942 }
3943 return res;
3944}
3945
Mathias Agopian180f10d2013-04-10 22:55:41 -07003946
3947void SurfaceFlinger::renderScreenImplLocked(
3948 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003949 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003950 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003951 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003952{
3953 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003954 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003955
3956 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003957 const int32_t hw_w = hw->getWidth();
3958 const int32_t hw_h = hw->getHeight();
3959 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003960 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003961
Dan Stozac1879002014-05-22 15:59:05 -07003962 // if a default or invalid sourceCrop is passed in, set reasonable values
3963 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3964 !sourceCrop.isValid()) {
3965 sourceCrop.setLeftTop(Point(0, 0));
3966 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3967 }
3968
3969 // ensure that sourceCrop is inside screen
3970 if (sourceCrop.left < 0) {
3971 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3972 }
Dan Stozabe31f442014-06-11 11:20:54 -07003973 if (sourceCrop.right > hw_w) {
3974 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003975 }
3976 if (sourceCrop.top < 0) {
3977 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3978 }
Dan Stozabe31f442014-06-11 11:20:54 -07003979 if (sourceCrop.bottom > hw_h) {
3980 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003981 }
3982
Mathias Agopian180f10d2013-04-10 22:55:41 -07003983 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003984 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003985
3986 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003987 engine.setViewportAndProjection(
3988 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003989 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003990
3991 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003992 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003993
Robert Carr1f0a16a2016-10-24 16:27:39 -07003994 // We loop through the first level of layers without traversing,
3995 // as we need to interpret min/max layer Z in the top level Z space.
3996 for (const auto& layer : mDrawingState.layersSortedByZ) {
3997 if (layer->getLayerStack() != hw->getLayerStack()) {
3998 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003999 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004000 const Layer::State& state(layer->getDrawingState());
4001 if (state.z < minLayerZ || state.z > maxLayerZ) {
4002 continue;
4003 }
4004 layer->traverseInZOrder([&](Layer* layer) {
4005 if (!layer->isVisible()) {
4006 return;
4007 }
4008 if (filtering) layer->setFiltering(true);
4009 layer->draw(hw, useIdentityTransform);
4010 if (filtering) layer->setFiltering(false);
4011 });
4012 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004013
Mathias Agopian931bda12013-08-28 18:11:46 -07004014 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004015}
4016
4017
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004018status_t SurfaceFlinger::captureScreenImplLocked(
4019 const sp<const DisplayDevice>& hw,
4020 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004021 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004022 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004023 bool useIdentityTransform, Transform::orientation_flags rotation,
4024 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004025{
4026 ATRACE_CALL();
4027
Mathias Agopian180f10d2013-04-10 22:55:41 -07004028 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004029 uint32_t hw_w = hw->getWidth();
4030 uint32_t hw_h = hw->getHeight();
4031
4032 if (rotation & Transform::ROT_90) {
4033 std::swap(hw_w, hw_h);
4034 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004035
Mathias Agopian180f10d2013-04-10 22:55:41 -07004036 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4037 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4038 reqWidth, reqHeight, hw_w, hw_h);
4039 return BAD_VALUE;
4040 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004041
Mathias Agopian180f10d2013-04-10 22:55:41 -07004042 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4043 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4044
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004045 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004046 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004047 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004048 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4049 (state.z < minLayerZ || state.z > maxLayerZ)) {
4050 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004051 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004052 layer->traverseInZOrder([&](Layer *layer) {
4053 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4054 layer->isSecure());
4055 });
4056 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004057
4058 if (!isLocalScreenshot && secureLayerIsVisible) {
4059 ALOGW("FB is protected: PERMISSION_DENIED");
4060 return PERMISSION_DENIED;
4061 }
4062
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004063 // create a surface (because we're a producer, and we need to
4064 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004065 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004066
4067 // Put the screenshot Surface into async mode so that
4068 // Layer::headFenceHasSignaled will always return true and we'll latch the
4069 // first buffer regardless of whether or not its acquire fence has
4070 // signaled. This is needed to avoid a race condition in the rotation
4071 // animation. See b/30209608
4072 sur->setAsyncMode(true);
4073
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004075
Michael Lentine5a16a622015-05-21 13:48:24 -07004076 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4077 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004078 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4079 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004080
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 int err = 0;
4082 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004083 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004084 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4085 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004086
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004087 if (err == NO_ERROR) {
4088 ANativeWindowBuffer* buffer;
4089 /* TODO: Once we have the sync framework everywhere this can use
4090 * server-side waits on the fence that dequeueBuffer returns.
4091 */
4092 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4093 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004094 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004095 // create an EGLImage from the buffer so we can later
4096 // turn it into a texture
4097 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4098 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4099 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004100 // this binds the given EGLImage as a framebuffer for the
4101 // duration of this scope.
4102 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4103 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004104 // this will in fact render into our dequeued buffer
4105 // via an FBO, which means we didn't have to create
4106 // an EGLSurface and therefore we're not
4107 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004108 renderScreenImplLocked(
4109 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4110 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004111
Riley Andrews86639902014-08-15 12:27:24 -07004112 // Attempt to create a sync khr object that can produce a sync point. If that
4113 // isn't available, create a non-dupable sync object in the fallback path and
4114 // wait on it directly.
4115 EGLSyncKHR sync;
4116 if (!DEBUG_SCREENSHOTS) {
4117 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004118 // native fence fd will not be populated until flush() is done.
4119 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004120 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004121 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004122 }
Riley Andrews86639902014-08-15 12:27:24 -07004123 if (sync != EGL_NO_SYNC_KHR) {
4124 // get the sync fd
4125 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4126 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4127 ALOGW("captureScreen: failed to dup sync khr object");
4128 syncFd = -1;
4129 }
4130 eglDestroySyncKHR(mEGLDisplay, sync);
4131 } else {
4132 // fallback path
4133 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4134 if (sync != EGL_NO_SYNC_KHR) {
4135 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4136 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4137 EGLint eglErr = eglGetError();
4138 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4139 ALOGW("captureScreen: fence wait timed out");
4140 } else {
4141 ALOGW_IF(eglErr != EGL_SUCCESS,
4142 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4143 }
4144 eglDestroySyncKHR(mEGLDisplay, sync);
4145 } else {
4146 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4147 }
4148 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004149 if (DEBUG_SCREENSHOTS) {
4150 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4151 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4152 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4153 hw, minLayerZ, maxLayerZ);
4154 delete [] pixels;
4155 }
4156
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004157 } else {
4158 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4159 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004160 window->cancelBuffer(window, buffer, syncFd);
4161 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004162 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004163 // destroy our image
4164 eglDestroyImageKHR(mEGLDisplay, image);
4165 } else {
4166 result = BAD_VALUE;
4167 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004168 if (buffer) {
4169 // queueBuffer takes ownership of syncFd
4170 result = window->queueBuffer(window, buffer, syncFd);
4171 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004172 }
4173 } else {
4174 result = BAD_VALUE;
4175 }
4176 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4177 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004178
Mathias Agopian74c40c02010-09-29 13:02:36 -07004179 return result;
4180}
4181
Mathias Agopiand5556842013-09-19 17:08:37 -07004182void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004183 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004184 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004185 for (size_t y=0 ; y<h ; y++) {
4186 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4187 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004188 if (p[x] != 0xFF000000) return;
4189 }
4190 }
4191 ALOGE("*** we just took a black screenshot ***\n"
4192 "requested minz=%d, maxz=%d, layerStack=%d",
4193 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004194
Robert Carr2047fae2016-11-28 14:09:09 -08004195 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004196 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004197 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004198 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4199 state.z <= maxLayerZ) {
4200 layer->traverseInZOrder([&](Layer* layer) {
4201 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4202 layer->isVisible() ? '+' : '-',
4203 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004204 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205 i++;
4206 });
4207 }
4208 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004209 }
4210}
4211
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004212// ---------------------------------------------------------------------------
4213
Robert Carr2047fae2016-11-28 14:09:09 -08004214void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4215 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004216}
4217
Robert Carr2047fae2016-11-28 14:09:09 -08004218void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4219 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004220}
4221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004223
4224
4225#if defined(__gl_h_)
4226#error "don't include gl/gl.h in this file"
4227#endif
4228
4229#if defined(__gl2_h_)
4230#error "don't include gl2/gl2.h in this file"
4231#endif