blob: cfde375d0a447b552d183591e827342560004eb8 [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>
Romain Guyf8b4ca52017-03-16 18:39:20 +000047#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
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Mathias Agopian99b49842011-06-27 16:05:52 -0700120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700122 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700124 mTransactionPending(false),
125 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700126 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700127 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700128 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800129 mHwc(nullptr),
130 mRealHwc(nullptr),
131 mVrHwc(nullptr),
132 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800134 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800136 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800137 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800138 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700140 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700141 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700142 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700143 mDebugInSwapBuffers(0),
144 mLastSwapBufferTime(0),
145 mDebugInTransaction(0),
146 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700147 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700148 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800149 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000150 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700151 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700152 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800153 mHasColorMatrix(false),
154 mHasPoweredOff(false),
155 mFrameBuckets(),
156 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700157 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800158 mNumLayers(0)
159#ifdef USE_HWC2
160 ,mEnterVrMode(false)
161#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800163
164 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
165 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
166
167 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
169
Steve Blocka19954a2012-01-04 20:05:49 +0000170 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700172 useContextPriority = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::useContextPriority>(false);
174
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700175 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
177
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700178 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
180
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800181 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 // debugging stuff...
185 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800187 // TODO (urbanus): remove once b/35319396 is fixed.
188 property_get("ro.boot.vr", value, "0");
189 mVrModeSupported = atoi(value);
190
Mathias Agopianb4b17302013-03-20 18:36:41 -0700191 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700192 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 property_get("debug.sf.showupdates", value, "0");
195 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700197 property_get("debug.sf.ddms", value, "0");
198 mDebugDDMS = atoi(value);
199 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700200 if (!startDdmConnection()) {
201 // start failed, and DDMS debugging not enabled
202 mDebugDDMS = 0;
203 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700205 ALOGI_IF(mDebugRegion, "showupdates enabled");
206 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700207
208 property_get("debug.sf.disable_backpressure", value, "0");
209 mPropagateBackpressure = !atoi(value);
210 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700211
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800212 property_get("debug.sf.enable_hwc_vds", value, "0");
213 mUseHwcVirtualDisplays = atoi(value);
214 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800215
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800216 property_get("ro.sf.disable_triple_buffer", value, "1");
217 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800218 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219}
220
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800221void SurfaceFlinger::onFirstRef()
222{
223 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224}
225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226SurfaceFlinger::~SurfaceFlinger()
227{
Mathias Agopiana4912602012-07-12 14:25:33 -0700228 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
229 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
230 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800231
232 if (mVrStateCallbacks.get()) {
233 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
234 defaultServiceManager()->checkService(String16("vrmanager")));
235 if (vrManagerService.get()) {
236 vrManagerService->unregisterListener(mVrStateCallbacks);
237 }
238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239}
240
Dan Stozac7014012014-02-14 15:03:43 -0800241void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242{
243 // the window manager died on us. prepare its eulogy.
244
Andy McFadden13a082e2012-08-24 10:16:42 -0700245 // restore initial conditions (default device unblank, etc)
246 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247
248 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700249 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250}
251
Robert Carr1db73f62016-12-21 12:58:51 -0800252static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700253 status_t err = client->initCheck();
254 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return nullptr;
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
261 return initClient(new Client(this));
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
265 const sp<IGraphicBufferProducer>& gbp) {
266 if (authenticateSurfaceTexture(gbp) == false) {
267 return nullptr;
268 }
269 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
270 if (layer == nullptr) {
271 return nullptr;
272 }
273
274 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700277sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
278 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279{
280 class DisplayToken : public BBinder {
281 sp<SurfaceFlinger> flinger;
282 virtual ~DisplayToken() {
283 // no more references, this display must be terminated
284 Mutex::Autolock _l(flinger->mStateLock);
285 flinger->mCurrentState.displays.removeItem(this);
286 flinger->setTransactionFlags(eDisplayTransactionNeeded);
287 }
288 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700289 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 : flinger(flinger) {
291 }
292 };
293
294 sp<BBinder> token = new DisplayToken(this);
295
296 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700297 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700298 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 return token;
302}
303
Jesse Hall6c913be2013-08-08 12:15:49 -0700304void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
305 Mutex::Autolock _l(mStateLock);
306
307 ssize_t idx = mCurrentState.displays.indexOfKey(display);
308 if (idx < 0) {
309 ALOGW("destroyDisplay: invalid display token");
310 return;
311 }
312
313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
314 if (!info.isVirtualDisplay()) {
315 ALOGE("destroyDisplay called for non-virtual display");
316 return;
317 }
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700319 mCurrentState.displays.removeItemsAt(idx);
320 setTransactionFlags(eDisplayTransactionNeeded);
321}
322
Jesse Hall692c7232012-11-08 15:41:56 -0800323void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800324 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 ALOGW_IF(mBuiltinDisplays[type],
326 "Overwriting display token for display type %d", type);
327 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800328 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700329 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700331 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800332}
333
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700335 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
337 return NULL;
338 }
Jesse Hall692c7232012-11-08 15:41:56 -0800339 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340}
341
Romain Guyf8b4ca52017-03-16 18:39:20 +0000342sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
343{
344 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
345 return gba;
346}
347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348void SurfaceFlinger::bootFinished()
349{
Wei Wangb254fa32017-01-31 17:43:23 -0800350 if (mStartBootAnimThread->join() != NO_ERROR) {
351 ALOGE("Join StartBootAnimThread failed!");
352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353 const nsecs_t now = systemTime();
354 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000355 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700356 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357
358 // wait patiently for the window manager death
359 const String16 name("window");
360 sp<IBinder> window(defaultServiceManager()->getService(name));
361 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700362 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 }
364
365 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700366 // formerly we would just kill the process, but we now ask it to exit so it
367 // can choose where to stop the animation.
368 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700369
370 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
371 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
372 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800373
374 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
375 defaultServiceManager()->checkService(String16("vrmanager")));
376 if (vrManagerService.get()) {
377 mVrStateCallbacks = new VrStateCallbacks(*this);
378 vrManagerService->registerListener(mVrStateCallbacks);
379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380}
381
Mathias Agopian3f844832013-08-07 21:24:32 -0700382void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700384 RenderEngine& engine;
385 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
388 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 }
390 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700391 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 return true;
393 }
394 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700395 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700396}
397
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700398class DispSyncSource : public VSyncSource, private DispSync::Callback {
399public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700400 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000401 const char* name) :
402 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700403 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700404 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000405 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
406 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700407 mDispSync(dispSync),
408 mCallbackMutex(),
409 mCallback(),
410 mVsyncMutex(),
411 mPhaseOffset(phaseOffset),
412 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700413
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 virtual ~DispSyncSource() {}
415
416 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700417 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 static_cast<DispSync::Callback*>(this));
421 if (err != NO_ERROR) {
422 ALOGE("error registering vsync callback: %s (%d)",
423 strerror(-err), err);
424 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700425 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 } else {
427 status_t err = mDispSync->removeEventListener(
428 static_cast<DispSync::Callback*>(this));
429 if (err != NO_ERROR) {
430 ALOGE("error unregistering vsync callback: %s (%d)",
431 strerror(-err), err);
432 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700433 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 }
437
438 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 mCallback = callback;
441 }
442
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700443 virtual void setPhaseOffset(nsecs_t phaseOffset) {
444 Mutex::Autolock lock(mVsyncMutex);
445
446 // Normalize phaseOffset to [0, period)
447 auto period = mDispSync->getPeriod();
448 phaseOffset %= period;
449 if (phaseOffset < 0) {
450 // If we're here, then phaseOffset is in (-period, 0). After this
451 // operation, it will be in (0, period)
452 phaseOffset += period;
453 }
454 mPhaseOffset = phaseOffset;
455
456 // If we're not enabled, we don't need to mess with the listeners
457 if (!mEnabled) {
458 return;
459 }
460
461 // Remove the listener with the old offset
462 status_t err = mDispSync->removeEventListener(
463 static_cast<DispSync::Callback*>(this));
464 if (err != NO_ERROR) {
465 ALOGE("error unregistering vsync callback: %s (%d)",
466 strerror(-err), err);
467 }
468
469 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000470 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 static_cast<DispSync::Callback*>(this));
472 if (err != NO_ERROR) {
473 ALOGE("error registering vsync callback: %s (%d)",
474 strerror(-err), err);
475 }
476 }
477
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478private:
479 virtual void onDispSyncEvent(nsecs_t when) {
480 sp<VSyncSource::Callback> callback;
481 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700482 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 callback = mCallback;
484
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700485 if (mTraceVsync) {
486 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700487 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 }
490
491 if (callback != NULL) {
492 callback->onVSyncEvent(when);
493 }
494 }
495
Tim Murray4a4e4a22016-04-19 16:29:23 +0000496 const char* const mName;
497
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 int mValue;
499
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700501 const String8 mVsyncOnLabel;
502 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700504 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505
506 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508
509 Mutex mVsyncMutex; // Protects the following
510 nsecs_t mPhaseOffset;
511 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512};
513
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700514class InjectVSyncSource : public VSyncSource {
515public:
516 InjectVSyncSource() {}
517
518 virtual ~InjectVSyncSource() {}
519
520 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
521 std::lock_guard<std::mutex> lock(mCallbackMutex);
522 mCallback = callback;
523 }
524
525 virtual void onInjectSyncEvent(nsecs_t when) {
526 std::lock_guard<std::mutex> lock(mCallbackMutex);
527 mCallback->onVSyncEvent(when);
528 }
529
530 virtual void setVSyncEnabled(bool) {}
531 virtual void setPhaseOffset(nsecs_t) {}
532
533private:
534 std::mutex mCallbackMutex; // Protects the following
535 sp<VSyncSource::Callback> mCallback;
536};
537
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700539 ALOGI( "SurfaceFlinger's main thread ready to run. "
540 "Initializing graphics H/W...");
541
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900542 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
543
Dan Stoza9e56aa02015-11-02 13:00:03 -0800544 { // Autolock scope
545 Mutex::Autolock _l(mStateLock);
546
547 // initialize EGL for the default display
548 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
549 eglInitialize(mEGLDisplay, NULL, NULL);
550
551 // start the EventThread
552 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
553 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700554 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800555 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
556 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700557 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 mEventQueue.setEventThread(mSFEventThread);
559
Tim Murrayacff43d2016-07-29 13:57:24 -0700560 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700561 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700562 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700563 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
564 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
565 }
566
Dan Stoza9e56aa02015-11-02 13:00:03 -0800567 // Get a RenderEngine for the given display / config (can't fail)
568 mRenderEngine = RenderEngine::create(mEGLDisplay,
569 HAL_PIXEL_FORMAT_RGBA_8888);
570 }
571
572 // Drop the state lock while we initialize the hardware composer. We drop
573 // the lock because on creation, it will call back into SurfaceFlinger to
574 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800575 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800576 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800577 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
579
Jesse Hall692c7232012-11-08 15:41:56 -0800580 Mutex::Autolock _l(mStateLock);
581
Mathias Agopian875d8e12013-06-07 15:35:48 -0700582 // retrieve the EGL context that was selected/created
583 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700584
Mathias Agopianda27af92012-09-13 18:17:13 -0700585 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
586 "couldn't create EGLContext");
587
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588 // make the GLContext current so that we can create textures when creating
589 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700590 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
591
Jamie Gennisd1700752013-10-14 12:22:52 -0700592 mEventControlThread = new EventControlThread(this);
593 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
594
Mathias Agopian92a979a2012-08-02 18:32:23 -0700595 // initialize our drawing state
596 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700597
Andy McFadden13a082e2012-08-24 10:16:42 -0700598 // set initial conditions (e.g. unblank default device)
599 initializeDisplays();
600
Dan Stoza4e637772016-07-28 13:31:51 -0700601 mRenderEngine->primeCache();
602
Wei Wangb254fa32017-01-31 17:43:23 -0800603 mStartBootAnimThread = new StartBootAnimThread();
604 if (mStartBootAnimThread->Start() != NO_ERROR) {
605 ALOGE("Run StartBootAnimThread failed!");
606 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800607
Dan Stoza9e56aa02015-11-02 13:00:03 -0800608 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700609}
610
Mathias Agopiana67e4182012-06-19 17:26:12 -0700611void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800612 // Start boot animation service by setting a property mailbox
613 // if property setting thread is already running, Start() will be just a NOP
614 mStartBootAnimThread->Start();
615 // Wait until property was set
616 if (mStartBootAnimThread->join() != NO_ERROR) {
617 ALOGE("Join StartBootAnimThread failed!");
618 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700619}
620
Mathias Agopian875d8e12013-06-07 15:35:48 -0700621size_t SurfaceFlinger::getMaxTextureSize() const {
622 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700623}
624
Mathias Agopian875d8e12013-06-07 15:35:48 -0700625size_t SurfaceFlinger::getMaxViewportDims() const {
626 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700627}
628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800629// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800630
Jamie Gennis582270d2011-08-17 18:19:00 -0700631bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800632 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800633 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800634 return authenticateSurfaceTextureLocked(bufferProducer);
635}
636
637bool SurfaceFlinger::authenticateSurfaceTextureLocked(
638 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800639 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700640 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800641}
642
Brian Anderson069b3652016-07-22 10:32:47 -0700643status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700644 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700645 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::REQUESTED_PRESENT,
647 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700648 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700649 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700650 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700651 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700652 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700653 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700654 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700655 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700656 };
657 return NO_ERROR;
658}
659
Dan Stoza7f7da322014-05-02 15:26:25 -0700660status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
661 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700662 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700663 return BAD_VALUE;
664 }
665
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500666 if (!display.get())
667 return NAME_NOT_FOUND;
668
Jesse Hall692c7232012-11-08 15:41:56 -0800669 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700670 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800671 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700672 type = i;
673 break;
674 }
675 }
676
677 if (type < 0) {
678 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700679 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700680
Mathias Agopian8b736f12012-08-13 17:54:26 -0700681 // TODO: Not sure if display density should handled by SF any longer
682 class Density {
683 static int getDensityFromProperty(char const* propName) {
684 char property[PROPERTY_VALUE_MAX];
685 int density = 0;
686 if (property_get(propName, property, NULL) > 0) {
687 density = atoi(property);
688 }
689 return density;
690 }
691 public:
692 static int getEmuDensity() {
693 return getDensityFromProperty("qemu.sf.lcd_density"); }
694 static int getBuildDensity() {
695 return getDensityFromProperty("ro.sf.lcd_density"); }
696 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700697
Dan Stoza7f7da322014-05-02 15:26:25 -0700698 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700699
Dan Stoza9e56aa02015-11-02 13:00:03 -0800700 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700701 DisplayInfo info = DisplayInfo();
702
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 float xdpi = hwConfig->getDpiX();
704 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700705
706 if (type == DisplayDevice::DISPLAY_PRIMARY) {
707 // The density of the device is provided by a build property
708 float density = Density::getBuildDensity() / 160.0f;
709 if (density == 0) {
710 // the build doesn't provide a density -- this is wrong!
711 // use xdpi instead
712 ALOGE("ro.sf.lcd_density must be defined as a build property");
713 density = xdpi / 160.0f;
714 }
715 if (Density::getEmuDensity()) {
716 // if "qemu.sf.lcd_density" is specified, it overrides everything
717 xdpi = ydpi = density = Density::getEmuDensity();
718 density /= 160.0f;
719 }
720 info.density = density;
721
722 // TODO: this needs to go away (currently needed only by webkit)
723 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
724 info.orientation = hw->getOrientation();
725 } else {
726 // TODO: where should this value come from?
727 static const int TV_DENSITY = 213;
728 info.density = TV_DENSITY / 160.0f;
729 info.orientation = 0;
730 }
731
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732 info.w = hwConfig->getWidth();
733 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700734 info.xdpi = xdpi;
735 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800736 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900737 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738
Andy McFadden91b2ca82014-06-13 14:04:23 -0700739 // This is how far in advance a buffer must be queued for
740 // presentation at a given time. If you want a buffer to appear
741 // on the screen at time N, you must submit the buffer before
742 // (N - presentationDeadline).
743 //
744 // Normally it's one full refresh period (to give SF a chance to
745 // latch the buffer), but this can be reduced by configuring a
746 // DispSync offset. Any additional delays introduced by the hardware
747 // composer or panel must be accounted for here.
748 //
749 // We add an additional 1ms to allow for processing time and
750 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800752 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700753
754 // All non-virtual displays are currently considered secure.
755 info.secure = true;
756
Michael Wright28f24d02016-07-12 13:30:53 -0700757 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 }
759
Dan Stoza7f7da322014-05-02 15:26:25 -0700760 return NO_ERROR;
761}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700762
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800763status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700764 DisplayStatInfo* stats) {
765 if (stats == NULL) {
766 return BAD_VALUE;
767 }
768
769 // FIXME for now we always return stats for the primary display
770 memset(stats, 0, sizeof(*stats));
771 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
772 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
773 return NO_ERROR;
774}
775
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700776int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800777 if (display == NULL) {
778 ALOGE("%s : display is NULL", __func__);
779 return BAD_VALUE;
780 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700781 sp<DisplayDevice> device(getDisplayDevice(display));
782 if (device != NULL) {
783 return device->getActiveConfig();
784 }
785 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700786}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700787
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700788void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
789 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
790 this);
791 int32_t type = hw->getDisplayType();
792 int currentMode = hw->getActiveConfig();
793
794 if (mode == currentMode) {
795 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
796 return;
797 }
798
799 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
800 ALOGW("Trying to set config for virtual display");
801 return;
802 }
803
804 hw->setActiveConfig(mode);
805 getHwComposer().setActiveConfig(type, mode);
806}
807
808status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
809 class MessageSetActiveConfig: public MessageBase {
810 SurfaceFlinger& mFlinger;
811 sp<IBinder> mDisplay;
812 int mMode;
813 public:
814 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
815 int mode) :
816 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
817 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700818 Vector<DisplayInfo> configs;
819 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700820 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700821 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700822 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700823 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700824 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700825 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
826 if (hw == NULL) {
827 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700828 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700829 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
830 ALOGW("Attempt to set active config = %d for virtual display",
831 mMode);
832 } else {
833 mFlinger.setActiveConfigInternal(hw, mMode);
834 }
835 return true;
836 }
837 };
838 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
839 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700840 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841}
Michael Wright28f24d02016-07-12 13:30:53 -0700842status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
843 Vector<android_color_mode_t>* outColorModes) {
844 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
845 return BAD_VALUE;
846 }
847
848 if (!display.get()) {
849 return NAME_NOT_FOUND;
850 }
851
852 int32_t type = NAME_NOT_FOUND;
853 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
854 if (display == mBuiltinDisplays[i]) {
855 type = i;
856 break;
857 }
858 }
859
860 if (type < 0) {
861 return type;
862 }
863
864 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
865 outColorModes->clear();
866 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
867
868 return NO_ERROR;
869}
870
871android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
872 sp<DisplayDevice> device(getDisplayDevice(display));
873 if (device != nullptr) {
874 return device->getActiveColorMode();
875 }
876 return static_cast<android_color_mode_t>(BAD_VALUE);
877}
878
879void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
880 android_color_mode_t mode) {
881 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
882 this);
883 int32_t type = hw->getDisplayType();
884 android_color_mode_t currentMode = hw->getActiveColorMode();
885
886 if (mode == currentMode) {
887 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
888 return;
889 }
890
891 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
892 ALOGW("Trying to set config for virtual display");
893 return;
894 }
895
896 hw->setActiveColorMode(mode);
897 getHwComposer().setActiveColorMode(type, mode);
898}
899
900
901status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
902 android_color_mode_t colorMode) {
903 class MessageSetActiveColorMode: public MessageBase {
904 SurfaceFlinger& mFlinger;
905 sp<IBinder> mDisplay;
906 android_color_mode_t mMode;
907 public:
908 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
909 android_color_mode_t mode) :
910 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
911 virtual bool handler() {
912 Vector<android_color_mode_t> modes;
913 mFlinger.getDisplayColorModes(mDisplay, &modes);
914 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
915 if (mMode < 0 || !exists) {
916 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
917 mDisplay.get());
918 return true;
919 }
920 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
921 if (hw == nullptr) {
922 ALOGE("Attempt to set active color mode = %d for null display %p",
923 mMode, mDisplay.get());
924 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
925 ALOGW("Attempt to set active color mode= %d for virtual display",
926 mMode);
927 } else {
928 mFlinger.setActiveColorModeInternal(hw, mMode);
929 }
930 return true;
931 }
932 };
933 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
934 postMessageSync(msg);
935 return NO_ERROR;
936}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700937
Svetoslavd85084b2014-03-20 10:28:31 -0700938status_t SurfaceFlinger::clearAnimationFrameStats() {
939 Mutex::Autolock _l(mStateLock);
940 mAnimFrameTracker.clearStats();
941 return NO_ERROR;
942}
943
944status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
945 Mutex::Autolock _l(mStateLock);
946 mAnimFrameTracker.getStats(outStats);
947 return NO_ERROR;
948}
949
Dan Stozac4f471e2016-03-24 09:31:08 -0700950status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
951 HdrCapabilities* outCapabilities) const {
952 Mutex::Autolock _l(mStateLock);
953
954 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
955 if (displayDevice == nullptr) {
956 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
957 return BAD_VALUE;
958 }
959
960 std::unique_ptr<HdrCapabilities> capabilities =
961 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
962 if (capabilities) {
963 std::swap(*outCapabilities, *capabilities);
964 } else {
965 return BAD_VALUE;
966 }
967
968 return NO_ERROR;
969}
970
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700971status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
972 if (enable == mInjectVSyncs) {
973 return NO_ERROR;
974 }
975
976 if (enable) {
977 mInjectVSyncs = enable;
978 ALOGV("VSync Injections enabled");
979 if (mVSyncInjector.get() == nullptr) {
980 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700981 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700982 }
983 mEventQueue.setEventThread(mInjectorEventThread);
984 } else {
985 mInjectVSyncs = enable;
986 ALOGV("VSync Injections disabled");
987 mEventQueue.setEventThread(mSFEventThread);
988 mVSyncInjector.clear();
989 }
990 return NO_ERROR;
991}
992
993status_t SurfaceFlinger::injectVSync(nsecs_t when) {
994 if (!mInjectVSyncs) {
995 ALOGE("VSync Injections not enabled");
996 return BAD_VALUE;
997 }
998 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
999 ALOGV("Injecting VSync inside SurfaceFlinger");
1000 mVSyncInjector->onInjectSyncEvent(when);
1001 }
1002 return NO_ERROR;
1003}
1004
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001005// ----------------------------------------------------------------------------
1006
1007sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001008 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001009}
1010
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001011// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001012
1013void SurfaceFlinger::waitForEvent() {
1014 mEventQueue.waitMessage();
1015}
1016
1017void SurfaceFlinger::signalTransaction() {
1018 mEventQueue.invalidate();
1019}
1020
1021void SurfaceFlinger::signalLayerUpdate() {
1022 mEventQueue.invalidate();
1023}
1024
1025void SurfaceFlinger::signalRefresh() {
1026 mEventQueue.refresh();
1027}
1028
1029status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001030 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001031 return mEventQueue.postMessage(msg, reltime);
1032}
1033
1034status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001035 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001036 status_t res = mEventQueue.postMessage(msg, reltime);
1037 if (res == NO_ERROR) {
1038 msg->wait();
1039 }
1040 return res;
1041}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001043void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001044 do {
1045 waitForEvent();
1046 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047}
1048
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049void SurfaceFlinger::enableHardwareVsync() {
1050 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001051 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001052 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001053 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1054 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001056 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057}
1058
Jesse Hall948fe0c2013-10-14 12:56:09 -07001059void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001060 Mutex::Autolock _l(mHWVsyncLock);
1061
Jesse Hall948fe0c2013-10-14 12:56:09 -07001062 if (makeAvailable) {
1063 mHWVsyncAvailable = true;
1064 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001065 // Hardware vsync is not currently available, so abort the resync
1066 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001067 return;
1068 }
1069
Dan Stoza9e56aa02015-11-02 13:00:03 -08001070 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1071 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072
1073 mPrimaryDispSync.reset();
1074 mPrimaryDispSync.setPeriod(period);
1075
1076 if (!mPrimaryHWVsyncEnabled) {
1077 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001078 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1079 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 mPrimaryHWVsyncEnabled = true;
1081 }
1082}
1083
Jesse Hall948fe0c2013-10-14 12:56:09 -07001084void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001085 Mutex::Autolock _l(mHWVsyncLock);
1086 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001087 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1088 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089 mPrimaryDispSync.endResync();
1090 mPrimaryHWVsyncEnabled = false;
1091 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001092 if (makeUnavailable) {
1093 mHWVsyncAvailable = false;
1094 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001095}
1096
Tim Murray4a4e4a22016-04-19 16:29:23 +00001097void SurfaceFlinger::resyncWithRateLimit() {
1098 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1099 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001100 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001101 }
1102}
1103
Steven Thomas3cfac282017-02-06 12:29:30 -08001104void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1105 nsecs_t timestamp) {
1106 Mutex::Autolock lock(mStateLock);
1107 // Ignore any vsyncs from the non-active hardware composer.
1108 if (composer != mHwc) {
1109 return;
1110 }
1111
Jamie Gennisd1700752013-10-14 12:22:52 -07001112 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113
Jamie Gennisd1700752013-10-14 12:22:52 -07001114 { // Scope for the lock
1115 Mutex::Autolock _l(mHWVsyncLock);
1116 if (type == 0 && mPrimaryHWVsyncEnabled) {
1117 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001118 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001119 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001120
1121 if (needsHwVsync) {
1122 enableHardwareVsync();
1123 } else {
1124 disableHardwareVsync(false);
1125 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001126}
1127
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001128void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1129 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1130 *compositorTiming = mCompositorTiming;
1131}
1132
Dan Stoza9e56aa02015-11-02 13:00:03 -08001133void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1134 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1135 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1136 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001137
Dan Stoza9e56aa02015-11-02 13:00:03 -08001138 // All non-virtual displays are currently considered secure.
1139 bool isSecure = true;
1140
1141 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001142
1143 // When we're using the vr composer, the assumption is that we've
1144 // already created the IBinder object for the primary display.
1145 if (!mHwc->isUsingVrComposer()) {
1146 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1147 }
1148
Dan Stoza9e56aa02015-11-02 13:00:03 -08001149 wp<IBinder> token = mBuiltinDisplays[type];
1150
1151 sp<IGraphicBufferProducer> producer;
1152 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001153 BufferQueue::createBufferQueue(&producer, &consumer,
1154 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001155
1156 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1157 DisplayDevice::DISPLAY_PRIMARY, consumer);
1158 sp<DisplayDevice> hw = new DisplayDevice(this,
1159 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1160 producer, mRenderEngine->getEGLConfig());
1161 mDisplays.add(token, hw);
1162 } else {
1163 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001164 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001165 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001166 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001167 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001168 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1169 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001170 }
1171 setTransactionFlags(eDisplayTransactionNeeded);
1172
Andy McFadden9e9689c2012-10-10 18:17:51 -07001173 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001174 }
Mathias Agopian86303202012-07-24 22:46:10 -07001175}
1176
Steven Thomas3cfac282017-02-06 12:29:30 -08001177void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1178 Mutex::Autolock lock(mStateLock);
1179 if (composer == mHwc) {
1180 repaintEverything();
1181 } else {
1182 // This isn't from our current hardware composer. If it's a callback
1183 // from the real composer, forward the refresh request to vr
1184 // flinger. Otherwise ignore it.
1185 if (!composer->isUsingVrComposer()) {
1186 mVrFlinger->OnHardwareComposerRefresh();
1187 }
1188 }
1189}
1190
Dan Stoza9e56aa02015-11-02 13:00:03 -08001191void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193 getHwComposer().setVsyncEnabled(disp,
1194 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001195}
1196
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001197void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1198 for (size_t i = 0; i < layers.size(); ++i) {
1199 layers[i]->clearHwcLayers();
1200 }
1201}
1202
1203void SurfaceFlinger::resetHwc() {
1204 disableHardwareVsync(true);
1205 clearHwcLayers(mDrawingState.layersSortedByZ);
1206 clearHwcLayers(mCurrentState.layersSortedByZ);
1207 // Clear the drawing state so that the logic inside of
1208 // handleTransactionLocked will fire. It will determine the delta between
1209 // mCurrentState and mDrawingState and re-apply all changes when we make the
1210 // transition.
1211 mDrawingState.displays.clear();
1212 mDisplays.clear();
1213}
1214
1215void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001216 bool enteringVrMode = mEnterVrMode;
1217 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1218 return;
1219 }
1220 if (enteringVrMode && !mVrHwc) {
1221 // Construct new HWComposer without holding any locks.
1222 mVrHwc = new HWComposer(true);
1223 ALOGV("Vr HWC created");
1224 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001225 {
1226 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001227
1228 if (enteringVrMode) {
1229 // Start vrflinger thread, if it hasn't been started already.
1230 if (!mVrFlinger) {
1231 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1232 int err = mVrFlinger->Run(mHwc->getComposer());
1233 if (err != NO_ERROR) {
1234 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1235 mVrFlinger.reset();
1236 mEnterVrMode = false;
1237 return;
1238 }
1239 }
1240
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001241 resetHwc();
1242
1243 mHwc = mVrHwc;
1244 mVrFlinger->EnterVrMode();
1245 } else {
1246 mVrFlinger->ExitVrMode();
1247
1248 resetHwc();
1249
1250 mHwc = mRealHwc;
1251 enableHardwareVsync();
1252 }
1253
1254 mVisibleRegionsDirty = true;
1255 invalidateHwcGeometry();
1256 android_atomic_or(1, &mRepaintEverything);
1257 setTransactionFlags(eDisplayTransactionNeeded);
1258 }
1259 if (mVrHwc) {
1260 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1261 }
1262}
1263
Mathias Agopian4fec8732012-06-29 14:12:52 -07001264void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001265 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001267 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001268 // TODO(eieio): Tied to a conditional until SELinux issues
1269 // are resolved.
1270 if (mVrModeSupported) {
1271 updateVrMode();
1272 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001273
Dan Stoza50182882016-07-08 12:02:20 -07001274 bool frameMissed = !mHadClientComposition &&
1275 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276 (mPreviousPresentFence->getSignalTime() ==
1277 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001278 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001279 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001280 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001281 signalLayerUpdate();
1282 break;
1283 }
1284
Dan Stoza6b9454d2014-11-07 16:00:59 -08001285 bool refreshNeeded = handleMessageTransaction();
1286 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001287 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001289 // Signal a refresh if a transaction modified the window state,
1290 // a new buffer was latched, or if HWC has requested a full
1291 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001292 signalRefresh();
1293 }
1294 break;
1295 }
1296 case MessageQueue::REFRESH: {
1297 handleMessageRefresh();
1298 break;
1299 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001300 }
1301}
1302
Dan Stoza6b9454d2014-11-07 16:00:59 -08001303bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001304 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001305 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001306 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001307 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001308 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001309 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001310}
1311
Dan Stoza6b9454d2014-11-07 16:00:59 -08001312bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001313 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001314 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001315}
1316
1317void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001318 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001319
Pablo Ceballos40845df2016-01-25 17:41:15 -08001320 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001321
Brian Andersond6927fb2016-07-23 23:37:30 -07001322 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001323 rebuildLayerStacks();
1324 setUpHWComposer();
1325 doDebugFlashRegions();
1326 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001327 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001328
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001329 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001330
1331 mHadClientComposition = false;
1332 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1333 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1334 mHadClientComposition = mHadClientComposition ||
1335 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1336 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001337
Dan Stoza9e56aa02015-11-02 13:00:03 -08001338 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001339}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001340
Mathias Agopiancd60f992012-08-16 16:28:27 -07001341void SurfaceFlinger::doDebugFlashRegions()
1342{
1343 // is debugging enabled
1344 if (CC_LIKELY(!mDebugRegion))
1345 return;
1346
1347 const bool repaintEverything = mRepaintEverything;
1348 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1349 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001350 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001351 // transform the dirty region into this screen's coordinate space
1352 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1353 if (!dirtyRegion.isEmpty()) {
1354 // redraw the whole screen
1355 doComposeSurfaces(hw, Region(hw->bounds()));
1356
1357 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001358 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001359 RenderEngine& engine(getRenderEngine());
1360 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1361
Mathias Agopianda27af92012-09-13 18:17:13 -07001362 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001363 }
1364 }
1365 }
1366
1367 postFramebuffer();
1368
1369 if (mDebugRegion > 1) {
1370 usleep(mDebugRegion * 1000);
1371 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001372
Dan Stoza9e56aa02015-11-02 13:00:03 -08001373 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001374 auto& displayDevice = mDisplays[displayId];
1375 if (!displayDevice->isDisplayOn()) {
1376 continue;
1377 }
1378
1379 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1381 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001382 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383}
1384
Brian Andersond6927fb2016-07-23 23:37:30 -07001385void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001387 ATRACE_CALL();
1388 ALOGV("preComposition");
1389
Mathias Agopiancd60f992012-08-16 16:28:27 -07001390 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001391 mDrawingState.traverseInZOrder([&](Layer* layer) {
1392 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 needExtraInvalidate = true;
1394 }
Robert Carr2047fae2016-11-28 14:09:09 -08001395 });
1396
Mathias Agopiancd60f992012-08-16 16:28:27 -07001397 if (needExtraInvalidate) {
1398 signalLayerUpdate();
1399 }
1400}
1401
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001402void SurfaceFlinger::updateCompositorTiming(
1403 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1404 std::shared_ptr<FenceTime>& presentFenceTime) {
1405 // Update queue of past composite+present times and determine the
1406 // most recently known composite to present latency.
1407 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1408 nsecs_t compositeToPresentLatency = -1;
1409 while (!mCompositePresentTimes.empty()) {
1410 CompositePresentTime& cpt = mCompositePresentTimes.front();
1411 // Cached values should have been updated before calling this method,
1412 // which helps avoid duplicate syscalls.
1413 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1414 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1415 break;
1416 }
1417 compositeToPresentLatency = displayTime - cpt.composite;
1418 mCompositePresentTimes.pop();
1419 }
1420
1421 // Don't let mCompositePresentTimes grow unbounded, just in case.
1422 while (mCompositePresentTimes.size() > 16) {
1423 mCompositePresentTimes.pop();
1424 }
1425
1426 // Integer division and modulo round toward 0 not -inf, so we need to
1427 // treat negative and positive offsets differently.
1428 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1429 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1430 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1431
1432 // Snap the latency to a value that removes scheduling jitter from the
1433 // composition and present times, which often have >1ms of jitter.
1434 // Reducing jitter is important if an app attempts to extrapolate
1435 // something (such as user input) to an accurate diasplay time.
1436 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1437 // with (presentLatency % interval).
1438 nsecs_t snappedCompositeToPresentLatency = -1;
1439 if (compositeToPresentLatency >= 0) {
1440 nsecs_t bias = vsyncInterval / 2;
1441 int64_t extraVsyncs =
1442 (compositeToPresentLatency - idealLatency + bias) /
1443 vsyncInterval;
1444 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1445 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1446 }
1447
1448 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1449 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1450 mCompositorTiming.interval = vsyncInterval;
1451 if (snappedCompositeToPresentLatency >= 0) {
1452 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1453 }
1454}
1455
1456void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001457{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001458 ATRACE_CALL();
1459 ALOGV("postComposition");
1460
Brian Anderson3546a3f2016-07-14 11:51:14 -07001461 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001462 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001463 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001464 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001465 }
1466
Brian Andersond6927fb2016-07-23 23:37:30 -07001467 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001468
1469 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1470 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1471 glCompositionDoneFenceTime =
1472 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1473 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1474 } else {
1475 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1476 }
1477 mGlCompositionDoneTimeline.updateSignalTimes();
1478
1479 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1480 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1481 mDisplayTimeline.push(displayFenceTime);
1482 mDisplayTimeline.updateSignalTimes();
1483
1484 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1485 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1486 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1487 presentFenceTime = &displayFenceTime;
1488 } else {
1489 retireFenceTime = &displayFenceTime;
1490 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001491
1492 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1493 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1494
1495 // We use the refreshStartTime which might be sampled a little later than
1496 // when we started doing work for this frame, but that should be okay
1497 // since updateCompositorTiming has snapping logic.
1498 updateCompositorTiming(
1499 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1500
Robert Carr2047fae2016-11-28 14:09:09 -08001501 mDrawingState.traverseInZOrder([&](Layer* layer) {
1502 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001503 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001504 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001505 recordBufferingStats(layer->getName().string(),
1506 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001507 }
Robert Carr2047fae2016-11-28 14:09:09 -08001508 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001509
Brian Anderson3d4039d2016-09-23 16:31:30 -07001510 if (displayFence->isValid()) {
1511 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001512 enableHardwareVsync();
1513 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001514 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001515 }
1516 }
1517
Andy McFadden5167ec62014-05-22 13:08:43 -07001518 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001519 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001520 enableHardwareVsync();
1521 }
1522 }
1523
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001524 if (mAnimCompositionPending) {
1525 mAnimCompositionPending = false;
1526
Brian Anderson3d4039d2016-09-23 16:31:30 -07001527 if (displayFenceTime->isValid()) {
1528 mAnimFrameTracker.setActualPresentFence(
1529 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001530 } else {
1531 // The HWC doesn't support present fences, so use the refresh
1532 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 nsecs_t presentTime =
1534 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001535 mAnimFrameTracker.setActualPresentTime(presentTime);
1536 }
1537 mAnimFrameTracker.advanceFrame();
1538 }
Dan Stozab90cf072015-03-05 11:05:59 -08001539
1540 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1541 return;
1542 }
1543
1544 nsecs_t currentTime = systemTime();
1545 if (mHasPoweredOff) {
1546 mHasPoweredOff = false;
1547 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001548 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001549 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001550 if (numPeriods < NUM_BUCKETS - 1) {
1551 mFrameBuckets[numPeriods] += elapsedTime;
1552 } else {
1553 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1554 }
1555 mTotalTime += elapsedTime;
1556 }
1557 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558}
1559
1560void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001561 ATRACE_CALL();
1562 ALOGV("rebuildLayerStacks");
1563
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001565 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1566 ATRACE_CALL();
1567 mVisibleRegionsDirty = false;
1568 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001569
Jeff Sharkey76488112017-02-27 14:15:18 -07001570 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1571 Region opaqueRegion;
1572 Region dirtyRegion;
1573 Vector<sp<Layer>> layersSortedByZ;
1574 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1575 const Transform& tr(displayDevice->getTransform());
1576 const Rect bounds(displayDevice->getBounds());
1577 if (displayDevice->isDisplayOn()) {
1578 computeVisibleRegions(
1579 displayDevice->getLayerStack(), dirtyRegion,
1580 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001581
Jeff Sharkey76488112017-02-27 14:15:18 -07001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
1583 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1584 Region drawRegion(tr.transform(
1585 layer->visibleNonTransparentRegion));
1586 drawRegion.andSelf(bounds);
1587 if (!drawRegion.isEmpty()) {
1588 layersSortedByZ.add(layer);
1589 } else {
1590 // Clear out the HWC layer if this layer was
1591 // previously visible, but no longer is
1592 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1593 nullptr);
1594 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001595 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001596 // WM changes displayDevice->layerStack upon sleep/awake.
1597 // Here we make sure we delete the HWC layers even if
1598 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001599 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1600 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001601 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001602 });
1603 }
1604 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1605 displayDevice->undefinedRegion.set(bounds);
1606 displayDevice->undefinedRegion.subtractSelf(
1607 tr.transform(opaqueRegion));
1608 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001609 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001610 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001612
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001614 ATRACE_CALL();
1615 ALOGV("setUpHWComposer");
1616
Jesse Hall028dc8f2013-08-20 16:35:32 -07001617 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001618 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1619 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1620 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1621
1622 // If nothing has changed (!dirty), don't recompose.
1623 // If something changed, but we don't currently have any visible layers,
1624 // and didn't when we last did a composition, then skip it this time.
1625 // The second rule does two things:
1626 // - When all layers are removed from a display, we'll emit one black
1627 // frame, then nothing more until we get new layers.
1628 // - When a display is created with a private layer stack, we won't
1629 // emit any black frames until a layer is added to the layer stack.
1630 bool mustRecompose = dirty && !(empty && wasEmpty);
1631
1632 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1633 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1634 mustRecompose ? "doing" : "skipping",
1635 dirty ? "+" : "-",
1636 empty ? "+" : "-",
1637 wasEmpty ? "+" : "-");
1638
Dan Stoza71433162014-02-04 16:22:36 -08001639 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001640
1641 if (mustRecompose) {
1642 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1643 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001644 }
1645
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 // build the h/w work list
1647 if (CC_UNLIKELY(mGeometryInvalid)) {
1648 mGeometryInvalid = false;
1649 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1650 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1651 const auto hwcId = displayDevice->getHwcDisplayId();
1652 if (hwcId >= 0) {
1653 const Vector<sp<Layer>>& currentLayers(
1654 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001655 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001656 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 if (!layer->hasHwcLayer(hwcId)) {
1658 auto hwcLayer = mHwc->createLayer(hwcId);
1659 if (hwcLayer) {
1660 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1661 } else {
1662 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001664 }
1665 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001666
Robert Carrae060832016-11-28 10:51:00 -08001667 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001668 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001670 }
1671 }
1672 }
1673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 }
Riley Andrews03414a12014-07-01 14:22:59 -07001675
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001676
1677 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1678
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679 // Set the per-frame data
1680 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1681 auto& displayDevice = mDisplays[displayId];
1682 const auto hwcId = displayDevice->getHwcDisplayId();
1683 if (hwcId < 0) {
1684 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001685 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001686 if (colorMatrix != mPreviousColorMatrix) {
1687 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1688 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1689 "display %zd: %d", displayId, result);
1690 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001691 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1692 layer->setPerFrameData(displayDevice);
1693 }
1694 }
1695
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001696 mPreviousColorMatrix = colorMatrix;
1697
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001699 auto& displayDevice = mDisplays[displayId];
1700 if (!displayDevice->isDisplayOn()) {
1701 continue;
1702 }
1703
1704 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1706 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001707 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001709
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710void SurfaceFlinger::doComposition() {
1711 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712 ALOGV("doComposition");
1713
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001714 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001715 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001716 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001717 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718 // transform the dirty region into this screen's coordinate space
1719 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001720
1721 // repaint the framebuffer (if needed)
1722 doDisplayComposition(hw, dirtyRegion);
1723
Mathias Agopiancd60f992012-08-16 16:28:27 -07001724 hw->dirtyRegion.clear();
1725 hw->flip(hw->swapRegion);
1726 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001727 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001728 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001729 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001730}
1731
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001732void SurfaceFlinger::postFramebuffer()
1733{
Mathias Agopian841cde52012-03-01 15:44:37 -08001734 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001736
Mathias Agopiana44b0412011-10-16 18:46:35 -07001737 const nsecs_t now = systemTime();
1738 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001739
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1741 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001742 if (!displayDevice->isDisplayOn()) {
1743 continue;
1744 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 const auto hwcId = displayDevice->getHwcDisplayId();
1746 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001747 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001748 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001749 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001750 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1752 sp<Fence> releaseFence = Fence::NO_FENCE;
1753 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1754 releaseFence = displayDevice->getClientTargetAcquireFence();
1755 } else {
1756 auto hwcLayer = layer->getHwcLayer(hwcId);
1757 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001758 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 layer->onLayerDisplayed(releaseFence);
1760 }
1761 if (hwcId >= 0) {
1762 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001763 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001764 }
1765
Mathias Agopiana44b0412011-10-16 18:46:35 -07001766 mLastSwapBufferTime = systemTime() - now;
1767 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001768
1769 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1770 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1771 logFrameStats();
1772 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773}
1774
Mathias Agopian87baae12012-07-31 12:38:26 -07001775void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001776{
Mathias Agopian841cde52012-03-01 15:44:37 -08001777 ATRACE_CALL();
1778
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001779 // here we keep a copy of the drawing state (that is the state that's
1780 // going to be overwritten by handleTransactionLocked()) outside of
1781 // mStateLock so that the side-effects of the State assignment
1782 // don't happen with mStateLock held (which can cause deadlocks).
1783 State drawingState(mDrawingState);
1784
Mathias Agopianca4d3602011-05-19 15:38:14 -07001785 Mutex::Autolock _l(mStateLock);
1786 const nsecs_t now = systemTime();
1787 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788
Mathias Agopianca4d3602011-05-19 15:38:14 -07001789 // Here we're guaranteed that some transaction flags are set
1790 // so we can call handleTransactionLocked() unconditionally.
1791 // We call getTransactionFlags(), which will also clear the flags,
1792 // with mStateLock held to guarantee that mCurrentState won't change
1793 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001794
Mathias Agopiane57f2922012-08-09 16:29:12 -07001795 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001796 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001797
Mathias Agopianca4d3602011-05-19 15:38:14 -07001798 mLastTransactionTime = systemTime() - now;
1799 mDebugInTransaction = 0;
1800 invalidateHwcGeometry();
1801 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001802}
1803
Mathias Agopian87baae12012-07-31 12:38:26 -07001804void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001805{
Dan Stoza7dde5992015-05-22 09:51:44 -07001806 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001807 mCurrentState.traverseInZOrder([](Layer* layer) {
1808 layer->notifyAvailableFrames();
1809 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001810
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811 /*
1812 * Traversal of the children
1813 * (perform the transaction for each of them if needed)
1814 */
1815
Mathias Agopian3559b072012-08-15 13:46:03 -07001816 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001817 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001818 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001819 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820
1821 const uint32_t flags = layer->doTransaction(0);
1822 if (flags & Layer::eVisibleRegion)
1823 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001824 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001825 }
1826
1827 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001828 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001829 */
1830
Mathias Agopiane57f2922012-08-09 16:29:12 -07001831 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 // here we take advantage of Vector's copy-on-write semantics to
1833 // improve performance by skipping the transaction entirely when
1834 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001835 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1836 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001837 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001838 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001840 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001841
1842 // find the displays that were removed
1843 // (ie: in drawing state but not in current state)
1844 // also handle displays that changed
1845 // (ie: displays that are in both lists)
1846 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001847 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1848 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001849 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001850 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001851 // Call makeCurrent() on the primary display so we can
1852 // be sure that nothing associated with this display
1853 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001854 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001855 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001856 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1857 if (hw != NULL)
1858 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001859 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001860 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001861 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001862 } else {
1863 ALOGW("trying to remove the main display");
1864 }
1865 } else {
1866 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001867 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001868 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001869 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1870 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001871 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001872 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001873 // recreating the DisplayDevice, so we just remove it
1874 // from the drawing state, so that it get re-added
1875 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001876 sp<DisplayDevice> hw(getDisplayDevice(display));
1877 if (hw != NULL)
1878 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001879 mDisplays.removeItem(display);
1880 mDrawingState.displays.removeItemsAt(i);
1881 dc--; i--;
1882 // at this point we must loop to the next item
1883 continue;
1884 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001885
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001886 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001887 if (disp != NULL) {
1888 if (state.layerStack != draw[i].layerStack) {
1889 disp->setLayerStack(state.layerStack);
1890 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001891 if ((state.orientation != draw[i].orientation)
1892 || (state.viewport != draw[i].viewport)
1893 || (state.frame != draw[i].frame))
1894 {
1895 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001896 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001897 }
Michael Lentine47e45402014-07-18 15:34:25 -07001898 if (state.width != draw[i].width || state.height != draw[i].height) {
1899 disp->setDisplaySize(state.width, state.height);
1900 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001901 }
1902 }
1903 }
1904
1905 // find displays that were added
1906 // (ie: in current state but not in drawing state)
1907 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001908 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001909 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001910
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001911 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001912 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001913 sp<IGraphicBufferProducer> bqProducer;
1914 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001915 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1916 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001917
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001919 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001920 // Virtual displays without a surface are dormant:
1921 // they have external state (layer stack, projection,
1922 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001923 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001924
Dan Stoza8cf150a2016-08-02 10:27:31 -07001925 if (mUseHwcVirtualDisplays) {
1926 int width = 0;
1927 int status = state.surface->query(
1928 NATIVE_WINDOW_WIDTH, &width);
1929 ALOGE_IF(status != NO_ERROR,
1930 "Unable to query width (%d)", status);
1931 int height = 0;
1932 status = state.surface->query(
1933 NATIVE_WINDOW_HEIGHT, &height);
1934 ALOGE_IF(status != NO_ERROR,
1935 "Unable to query height (%d)", status);
1936 int intFormat = 0;
1937 status = state.surface->query(
1938 NATIVE_WINDOW_FORMAT, &intFormat);
1939 ALOGE_IF(status != NO_ERROR,
1940 "Unable to query format (%d)", status);
1941 auto format = static_cast<android_pixel_format_t>(
1942 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001943
Dan Stoza8cf150a2016-08-02 10:27:31 -07001944 mHwc->allocateVirtualDisplay(width, height, &format,
1945 &hwcId);
1946 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947
Dan Stoza5cf424b2016-05-20 14:02:39 -07001948 // TODO: Plumb requested format back up to consumer
1949
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 sp<VirtualDisplaySurface> vds =
1951 new VirtualDisplaySurface(*mHwc,
1952 hwcId, state.surface, bqProducer,
1953 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001954
1955 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001956 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001957 }
1958 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001959 ALOGE_IF(state.surface!=NULL,
1960 "adding a supported display, but rendering "
1961 "surface is provided (%p), ignoring it",
1962 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001963
1964 hwcId = state.type;
1965 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1966 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001967 }
1968
1969 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001970 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001971 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 state.type, hwcId, state.isSecure, display,
1973 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001974 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001975 hw->setLayerStack(state.layerStack);
1976 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001977 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001978 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001979 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001981 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001982 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001983 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001984 }
1985 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001987 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988
Mathias Agopian84300952012-11-21 16:02:13 -08001989 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1990 // The transform hint might have changed for some layers
1991 // (either because a display has changed, or because a layer
1992 // as changed).
1993 //
1994 // Walk through all the layers in currentLayers,
1995 // and update their transform hint.
1996 //
1997 // If a layer is visible only on a single display, then that
1998 // display is used to calculate the hint, otherwise we use the
1999 // default display.
2000 //
2001 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2002 // the hint is set before we acquire a buffer from the surface texture.
2003 //
2004 // NOTE: layer transactions have taken place already, so we use their
2005 // drawing state. However, SurfaceFlinger's own transaction has not
2006 // happened yet, so we must use the current state layer list
2007 // (soon to become the drawing state list).
2008 //
2009 sp<const DisplayDevice> disp;
2010 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002011 bool first = true;
2012 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002013 // NOTE: we rely on the fact that layers are sorted by
2014 // layerStack first (so we don't have to traverse the list
2015 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002016 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002017 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002018 currentlayerStack = layerStack;
2019 // figure out if this layerstack is mirrored
2020 // (more than one display) if so, pick the default display,
2021 // if not, pick the only display it's on.
2022 disp.clear();
2023 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2024 sp<const DisplayDevice> hw(mDisplays[dpy]);
2025 if (hw->getLayerStack() == currentlayerStack) {
2026 if (disp == NULL) {
2027 disp = hw;
2028 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002029 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002030 break;
2031 }
2032 }
2033 }
2034 }
Chet Haase91d25932013-04-11 15:24:55 -07002035 if (disp == NULL) {
2036 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2037 // redraw after transform hint changes. See bug 8508397.
2038
2039 // could be null when this layer is using a layerStack
2040 // that is not visible on any display. Also can occur at
2041 // screen off/on times.
2042 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002043 }
Chet Haase91d25932013-04-11 15:24:55 -07002044 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002045
2046 first = false;
2047 });
Mathias Agopian84300952012-11-21 16:02:13 -08002048 }
2049
2050
Mathias Agopian3559b072012-08-15 13:46:03 -07002051 /*
2052 * Perform our own transaction if needed
2053 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002054
2055 if (mLayersAdded) {
2056 mLayersAdded = false;
2057 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002058 mVisibleRegionsDirty = true;
2059 }
2060
2061 // some layers might have been removed, so
2062 // we need to update the regions they're exposing.
2063 if (mLayersRemoved) {
2064 mLayersRemoved = false;
2065 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002066 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002067 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002068 // this layer is not visible anymore
2069 // TODO: we could traverse the tree from front to back and
2070 // compute the actual visible region
2071 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002072 Region visibleReg;
2073 visibleReg.set(layer->computeScreenBounds());
2074 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002075 }
Robert Carr2047fae2016-11-28 14:09:09 -08002076 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002077 }
2078
2079 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002080
2081 updateCursorAsync();
2082}
2083
2084void SurfaceFlinger::updateCursorAsync()
2085{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2087 auto& displayDevice = mDisplays[displayId];
2088 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002089 continue;
2090 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091
2092 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2093 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002094 }
2095 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096}
2097
2098void SurfaceFlinger::commitTransaction()
2099{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002100 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002101 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002102 for (const auto& l : mLayersPendingRemoval) {
2103 recordBufferingStats(l->getName().string(),
2104 l->getOccupancyHistory(true));
2105 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002106 }
2107 mLayersPendingRemoval.clear();
2108 }
2109
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002110 // If this transaction is part of a window animation then the next frame
2111 // we composite should be considered an animation as well.
2112 mAnimCompositionPending = mAnimTransactionPending;
2113
Mathias Agopian4fec8732012-06-29 14:12:52 -07002114 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002115 mDrawingState.traverseInZOrder([](Layer* layer) {
2116 layer->commitChildList();
2117 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002118 mTransactionPending = false;
2119 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002120 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121}
2122
Robert Carr2047fae2016-11-28 14:09:09 -08002123void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002124 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002125{
Mathias Agopian841cde52012-03-01 15:44:37 -08002126 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129 Region aboveOpaqueLayers;
2130 Region aboveCoveredLayers;
2131 Region dirty;
2132
Mathias Agopian87baae12012-07-31 12:38:26 -07002133 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134
Robert Carr2047fae2016-11-28 14:09:09 -08002135 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002137 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138
Jesse Hall01e29052013-02-19 16:13:35 -08002139 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002140 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002141 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002142
Mathias Agopianab028732010-03-16 16:41:46 -07002143 /*
2144 * opaqueRegion: area of a surface that is fully opaque.
2145 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002147
2148 /*
2149 * visibleRegion: area of a surface that is visible on screen
2150 * and not fully transparent. This is essentially the layer's
2151 * footprint minus the opaque regions above it.
2152 * Areas covered by a translucent surface are considered visible.
2153 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002155
2156 /*
2157 * coveredRegion: area of a surface that is covered by all
2158 * visible regions above it (which includes the translucent areas).
2159 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002161
Jesse Halla8026d22012-09-25 13:25:04 -07002162 /*
2163 * transparentRegion: area of a surface that is hinted to be completely
2164 * transparent. This is only used to tell when the layer has no visible
2165 * non-transparent regions and can be removed from the layer list. It
2166 * does not affect the visibleRegion of this layer or any layers
2167 * beneath it. The hint may not be correct if apps don't respect the
2168 * SurfaceView restrictions (which, sadly, some don't).
2169 */
2170 Region transparentRegion;
2171
Mathias Agopianab028732010-03-16 16:41:46 -07002172
2173 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002174 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002175 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002178 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002179 if (!visibleRegion.isEmpty()) {
2180 // Remove the transparent area from the visible region
2181 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002182 if (tr.preserveRects()) {
2183 // transform the transparent region
2184 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002185 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002186 // transformation too complex, can't do the
2187 // transparent region optimization.
2188 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002189 }
Mathias Agopianab028732010-03-16 16:41:46 -07002190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191
Mathias Agopianab028732010-03-16 16:41:46 -07002192 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002193 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002195 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2196 // the opaque region is the layer's footprint
2197 opaqueRegion = visibleRegion;
2198 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002199 }
2200 }
2201
Mathias Agopianab028732010-03-16 16:41:46 -07002202 // Clip the covered region to the visible region
2203 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2204
2205 // Update aboveCoveredLayers for next (lower) layer
2206 aboveCoveredLayers.orSelf(visibleRegion);
2207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002208 // subtract the opaque region covered by the layers above us
2209 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210
2211 // compute this layer's dirty region
2212 if (layer->contentDirty) {
2213 // we need to invalidate the whole region
2214 dirty = visibleRegion;
2215 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002216 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217 layer->contentDirty = false;
2218 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002219 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002220 * the exposed region consists of two components:
2221 * 1) what's VISIBLE now and was COVERED before
2222 * 2) what's EXPOSED now less what was EXPOSED before
2223 *
2224 * note that (1) is conservative, we start with the whole
2225 * visible region but only keep what used to be covered by
2226 * something -- which mean it may have been exposed.
2227 *
2228 * (2) handles areas that were not covered by anything but got
2229 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002230 */
Mathias Agopianab028732010-03-16 16:41:46 -07002231 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002232 const Region oldVisibleRegion = layer->visibleRegion;
2233 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002234 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2235 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236 }
2237 dirty.subtractSelf(aboveOpaqueLayers);
2238
2239 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002240 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241
Mathias Agopianab028732010-03-16 16:41:46 -07002242 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002244
Jesse Halla8026d22012-09-25 13:25:04 -07002245 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246 layer->setVisibleRegion(visibleRegion);
2247 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002248 layer->setVisibleNonTransparentRegion(
2249 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002250 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002251
Mathias Agopian87baae12012-07-31 12:38:26 -07002252 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253}
2254
Mathias Agopian87baae12012-07-31 12:38:26 -07002255void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2256 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002257 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002258 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2259 if (hw->getLayerStack() == layerStack) {
2260 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002261 }
2262 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002263}
2264
Dan Stoza6b9454d2014-11-07 16:00:59 -08002265bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002266{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 ALOGV("handlePageFlip");
2268
Brian Andersond6927fb2016-07-23 23:37:30 -07002269 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002270
Mathias Agopian4fec8732012-06-29 14:12:52 -07002271 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002272 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002273
2274 // Store the set of layers that need updates. This set must not change as
2275 // buffers are being latched, as this could result in a deadlock.
2276 // Example: Two producers share the same command stream and:
2277 // 1.) Layer 0 is latched
2278 // 2.) Layer 0 gets a new frame
2279 // 2.) Layer 1 gets a new frame
2280 // 3.) Layer 1 is latched.
2281 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2282 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002283 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002284 if (layer->hasQueuedFrame()) {
2285 frameQueued = true;
2286 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002287 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002288 } else {
2289 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002290 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002291 } else {
2292 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002293 }
Robert Carr2047fae2016-11-28 14:09:09 -08002294 });
2295
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002297 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002298 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002299 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002300 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002301
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002302 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002303
2304 // If we will need to wake up at some time in the future to deal with a
2305 // queued frame that shouldn't be displayed during this vsync period, wake
2306 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002307 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002308 signalLayerUpdate();
2309 }
2310
2311 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313}
2314
Mathias Agopianad456f92011-01-13 17:53:01 -08002315void SurfaceFlinger::invalidateHwcGeometry()
2316{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002318}
2319
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002320
Fabien Sanglard830b8472016-11-30 16:35:58 -08002321void SurfaceFlinger::doDisplayComposition(
2322 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002323 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324{
Dan Stoza71433162014-02-04 16:22:36 -08002325 // We only need to actually compose the display if:
2326 // 1) It is being handled by hardware composer, which may need this to
2327 // keep its virtual display state machine in sync, or
2328 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002329 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002330 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002331 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002332 return;
2333 }
2334
Dan Stoza9e56aa02015-11-02 13:00:03 -08002335 ALOGV("doDisplayComposition");
2336
Mathias Agopian87baae12012-07-31 12:38:26 -07002337 Region dirtyRegion(inDirtyRegion);
2338
Mathias Agopianb8a55602009-06-26 19:06:36 -07002339 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002343 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002344 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2345 // takes a rectangle, we must make sure to update that whole
2346 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002347 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002348 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002349 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002350 // We need to redraw the rectangle that will be updated
2351 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002352 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002353 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002354 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002355 } else {
2356 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 dirtyRegion.set(displayDevice->bounds());
2358 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 }
2360 }
2361
Fabien Sanglard830b8472016-11-30 16:35:58 -08002362 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002364 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002365 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002366
2367 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002368 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369}
2370
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371bool SurfaceFlinger::doComposeSurfaces(
2372 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002373{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002375
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002377
2378 mat4 oldColorMatrix;
2379 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2380 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2381 if (applyColorMatrix) {
2382 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2383 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2384 }
2385
Dan Stoza9e56aa02015-11-02 13:00:03 -08002386 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2387 if (hasClientComposition) {
2388 ALOGV("hasClientComposition");
2389
2390 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002391 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002392 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002393 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2394 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2395 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2396 }
2397 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002398 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002399
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002400 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2402 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002403 // when using overlays, we assume a fully transparent framebuffer
2404 // NOTE: we could reduce how much we need to clear, for instance
2405 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002406 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002407 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002410 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002412
2413 // we remove the scissor part
2414 // we're left with the letterbox region
2415 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002417
2418 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002420
2421 // but limit it to the dirty region
2422 region.andSelf(dirty);
2423
Mathias Agopianb9494d52012-04-18 02:28:45 -07002424 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002425 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002426 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002428 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002429 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002430
Dan Stoza9e56aa02015-11-02 13:00:03 -08002431 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002432 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002433 // scissor on the main display. It should never be needed
2434 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 const Rect& bounds(displayDevice->getBounds());
2436 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002437 if (scissor != bounds) {
2438 // scissor doesn't match the screen's dimensions, so we
2439 // need to clear everything outside of it and enable
2440 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002441
Mathias Agopianf45c5102012-10-24 16:29:17 -07002442 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 const uint32_t height = displayDevice->getHeight();
2444 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002445 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002446 }
2447 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002448 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002449
Mathias Agopian85d751c2012-08-29 16:59:24 -07002450 /*
2451 * and then, render the layers targeted at the framebuffer
2452 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002453
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 ALOGV("Rendering client layers");
2455 const Transform& displayTransform = displayDevice->getTransform();
2456 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002457 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 bool firstLayer = true;
2459 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2460 const Region clip(dirty.intersect(
2461 displayTransform.transform(layer->visibleRegion)));
2462 ALOGV("Layer: %s", layer->getName().string());
2463 ALOGV(" Composition type: %s",
2464 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002465 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 switch (layer->getCompositionType(hwcId)) {
2467 case HWC2::Composition::Cursor:
2468 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002469 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002471 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2473 layer->isOpaque(state) && (state.alpha == 1.0f)
2474 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002475 // never clear the very first layer since we're
2476 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002477 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002478 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002479 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002480 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 case HWC2::Composition::Client: {
2482 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002483 break;
2484 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002486 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002487 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 } else {
2489 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002490 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002492 }
2493 } else {
2494 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002496 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002498 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002500 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002501 }
2502 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002503
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002504 if (applyColorMatrix) {
2505 getRenderEngine().setupColorTransform(oldColorMatrix);
2506 }
2507
Mathias Agopianf45c5102012-10-24 16:29:17 -07002508 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002509 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002510 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511}
2512
Fabien Sanglard830b8472016-11-30 16:35:58 -08002513void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2514 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002515 RenderEngine& engine(getRenderEngine());
2516 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517}
2518
Dan Stoza7d89d062015-04-30 13:29:25 -07002519status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002520 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002521 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002522 const sp<Layer>& lbc,
2523 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002524{
Dan Stoza7d89d062015-04-30 13:29:25 -07002525 // add this layer to the current state list
2526 {
2527 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002529 return NO_MEMORY;
2530 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002531 if (parent == nullptr) {
2532 mCurrentState.layersSortedByZ.add(lbc);
2533 } else {
2534 parent->addChild(lbc);
2535 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002536 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 mLayersAdded = true;
2538 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002539 }
2540
Mathias Agopian96f08192010-06-02 23:28:45 -07002541 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002542 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002543
Dan Stoza7d89d062015-04-30 13:29:25 -07002544 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002545}
2546
Robert Carr9524cb32017-02-13 11:32:32 -08002547status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002548 Mutex::Autolock _l(mStateLock);
2549
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 const auto& p = layer->getParent();
2551 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2552 mCurrentState.layersSortedByZ.remove(layer);
2553
Robert Carr136e2f62017-02-08 17:54:29 -08002554 // As a matter of normal operation, the LayerCleaner will produce a second
2555 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2556 // so we will succeed in promoting it, but it's already been removed
2557 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2558 // otherwise something has gone wrong and we are leaking the layer.
2559 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002560 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2561 layer->getName().string(),
2562 (p != nullptr) ? p->getName().string() : "no-parent");
2563 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002564 } else if (index < 0) {
2565 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002566 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567
2568 mLayersPendingRemoval.add(layer);
2569 mLayersRemoved = true;
2570 mNumLayers--;
2571 setTransactionFlags(eTransactionNeeded);
2572 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573}
2574
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002575uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002576 return android_atomic_release_load(&mTransactionFlags);
2577}
2578
Mathias Agopian3f844832013-08-07 21:24:32 -07002579uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2581}
2582
Mathias Agopian3f844832013-08-07 21:24:32 -07002583uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2585 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002586 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588 return old;
2589}
2590
Mathias Agopian8b33f032012-07-24 20:43:54 -07002591void SurfaceFlinger::setTransactionState(
2592 const Vector<ComposerState>& state,
2593 const Vector<DisplayState>& displays,
2594 uint32_t flags)
2595{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002596 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002597 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002598 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002599
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002600 if (flags & eAnimation) {
2601 // For window updates that are part of an animation we must wait for
2602 // previous animation "frames" to be handled.
2603 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002604 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002605 if (CC_UNLIKELY(err != NO_ERROR)) {
2606 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002607 // caller after a few seconds.
2608 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2609 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002610 mAnimTransactionPending = false;
2611 break;
2612 }
2613 }
2614 }
2615
Mathias Agopiane57f2922012-08-09 16:29:12 -07002616 size_t count = displays.size();
2617 for (size_t i=0 ; i<count ; i++) {
2618 const DisplayState& s(displays[i]);
2619 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002620 }
2621
Mathias Agopiane57f2922012-08-09 16:29:12 -07002622 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002623 for (size_t i=0 ; i<count ; i++) {
2624 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002625 // Here we need to check that the interface we're given is indeed
2626 // one of our own. A malicious client could give us a NULL
2627 // IInterface, or one of its own or even one of our own but a
2628 // different type. All these situations would cause us to crash.
2629 //
2630 // NOTE: it would be better to use RTTI as we could directly check
2631 // that we have a Client*. however, RTTI is disabled in Android.
2632 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002633 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002634 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002635 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002636 sp<Client> client( static_cast<Client *>(s.client.get()) );
2637 transactionFlags |= setClientStateLocked(client, s.state);
2638 }
2639 }
2640 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002641 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002642
Robert Carr2a7dbb42016-05-24 11:41:28 -07002643 // If a synchronous transaction is explicitly requested without any changes,
2644 // force a transaction anyway. This can be used as a flush mechanism for
2645 // previous async transactions.
2646 if (transactionFlags == 0 && (flags & eSynchronous)) {
2647 transactionFlags = eTransactionNeeded;
2648 }
2649
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002651 if (mInterceptor.isEnabled()) {
2652 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2653 }
Irvel468051e2016-06-13 16:44:44 -07002654
Mathias Agopian386aa982011-11-07 21:58:03 -08002655 // this triggers the transaction
2656 setTransactionFlags(transactionFlags);
2657
2658 // if this is a synchronous transaction, wait for it to take effect
2659 // before returning.
2660 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002661 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002662 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002663 if (flags & eAnimation) {
2664 mAnimTransactionPending = true;
2665 }
2666 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002667 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2668 if (CC_UNLIKELY(err != NO_ERROR)) {
2669 // just in case something goes wrong in SF, return to the
2670 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002671 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2672 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002673 break;
2674 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 }
2677}
2678
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2680{
Jesse Hall9a143922012-10-04 16:29:19 -07002681 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2682 if (dpyIdx < 0)
2683 return 0;
2684
Mathias Agopiane57f2922012-08-09 16:29:12 -07002685 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002686 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002687 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002688 const uint32_t what = s.what;
2689 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002690 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002691 disp.surface = s.surface;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 }
2695 if (what & DisplayState::eLayerStackChanged) {
2696 if (disp.layerStack != s.layerStack) {
2697 disp.layerStack = s.layerStack;
2698 flags |= eDisplayTransactionNeeded;
2699 }
2700 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002701 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002702 if (disp.orientation != s.orientation) {
2703 disp.orientation = s.orientation;
2704 flags |= eDisplayTransactionNeeded;
2705 }
2706 if (disp.frame != s.frame) {
2707 disp.frame = s.frame;
2708 flags |= eDisplayTransactionNeeded;
2709 }
2710 if (disp.viewport != s.viewport) {
2711 disp.viewport = s.viewport;
2712 flags |= eDisplayTransactionNeeded;
2713 }
2714 }
Michael Lentine47e45402014-07-18 15:34:25 -07002715 if (what & DisplayState::eDisplaySizeChanged) {
2716 if (disp.width != s.width) {
2717 disp.width = s.width;
2718 flags |= eDisplayTransactionNeeded;
2719 }
2720 if (disp.height != s.height) {
2721 disp.height = s.height;
2722 flags |= eDisplayTransactionNeeded;
2723 }
2724 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002725 }
2726 return flags;
2727}
2728
2729uint32_t SurfaceFlinger::setClientStateLocked(
2730 const sp<Client>& client,
2731 const layer_state_t& s)
2732{
2733 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002734 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 if (layer != 0) {
2736 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002737 bool geometryAppliesWithResize =
2738 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002739 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002740 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002742 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 }
2744 if (what & layer_state_t::eLayerChanged) {
2745 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 const auto& p = layer->getParent();
2747 if (p == nullptr) {
2748 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2749 if (layer->setLayer(s.z) && idx >= 0) {
2750 mCurrentState.layersSortedByZ.removeAt(idx);
2751 mCurrentState.layersSortedByZ.add(layer);
2752 // we need traversal (state changed)
2753 // AND transaction (list changed)
2754 flags |= eTransactionNeeded|eTraversalNeeded;
2755 }
2756 } else {
2757 if (p->setChildLayer(layer, s.z)) {
2758 flags |= eTransactionNeeded|eTraversalNeeded;
2759 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002760 }
2761 }
2762 if (what & layer_state_t::eSizeChanged) {
2763 if (layer->setSize(s.w, s.h)) {
2764 flags |= eTraversalNeeded;
2765 }
2766 }
2767 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002769 flags |= eTraversalNeeded;
2770 }
2771 if (what & layer_state_t::eMatrixChanged) {
2772 if (layer->setMatrix(s.matrix))
2773 flags |= eTraversalNeeded;
2774 }
2775 if (what & layer_state_t::eTransparentRegionChanged) {
2776 if (layer->setTransparentRegionHint(s.transparentRegion))
2777 flags |= eTraversalNeeded;
2778 }
Dan Stoza23116082015-06-18 14:58:39 -07002779 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 if (layer->setFlags(s.flags, s.mask))
2781 flags |= eTraversalNeeded;
2782 }
2783 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002784 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002785 flags |= eTraversalNeeded;
2786 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002787 if (what & layer_state_t::eFinalCropChanged) {
2788 if (layer->setFinalCrop(s.finalCrop))
2789 flags |= eTraversalNeeded;
2790 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 // We only allow setting layer stacks for top level layers,
2794 // everything else inherits layer stack from its parent.
2795 if (layer->hasParent()) {
2796 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2797 layer->getName().string());
2798 } else if (idx < 0) {
2799 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2800 "that also does not appear in the top level layer list. Something"
2801 " has gone wrong.", layer->getName().string());
2802 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002803 mCurrentState.layersSortedByZ.removeAt(idx);
2804 mCurrentState.layersSortedByZ.add(layer);
2805 // we need traversal (state changed)
2806 // AND transaction (list changed)
2807 flags |= eTransactionNeeded|eTraversalNeeded;
2808 }
2809 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002810 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002811 if (s.barrierHandle != nullptr) {
2812 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2813 } else if (s.barrierGbp != nullptr) {
2814 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2815 if (authenticateSurfaceTextureLocked(gbp)) {
2816 const auto& otherLayer =
2817 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2818 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2819 } else {
2820 ALOGE("Attempt to defer transaction to to an"
2821 " unrecognized GraphicBufferProducer");
2822 }
2823 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002824 // We don't trigger a traversal here because if no other state is
2825 // changed, we don't want this to cause any more work
2826 }
Robert Carr1db73f62016-12-21 12:58:51 -08002827 if (what & layer_state_t::eReparentChildren) {
2828 if (layer->reparentChildren(s.reparentHandle)) {
2829 flags |= eTransactionNeeded|eTraversalNeeded;
2830 }
2831 }
Robert Carr9524cb32017-02-13 11:32:32 -08002832 if (what & layer_state_t::eDetachChildren) {
2833 layer->detachChildren();
2834 }
Robert Carrc3574f72016-03-24 12:19:32 -07002835 if (what & layer_state_t::eOverrideScalingModeChanged) {
2836 layer->setOverrideScalingMode(s.overrideScalingMode);
2837 // We don't trigger a traversal here because if no other state is
2838 // changed, we don't want this to cause any more work
2839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 }
2841 return flags;
2842}
2843
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002844status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002845 const String8& name,
2846 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002847 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002848 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2849 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002851 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002852 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002853 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002854 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002855 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002856
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002857 status_t result = NO_ERROR;
2858
2859 sp<Layer> layer;
2860
Mathias Agopian3165cc22012-08-08 19:42:09 -07002861 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2862 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002863 result = createNormalLayer(client,
2864 name, w, h, flags, format,
2865 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002867 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002868 result = createDimLayer(client,
2869 name, w, h, flags,
2870 handle, gbp, &layer);
2871 break;
2872 default:
2873 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 break;
2875 }
2876
Dan Stoza7d89d062015-04-30 13:29:25 -07002877 if (result != NO_ERROR) {
2878 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002880
Albert Chaulk479c60c2017-01-27 14:21:34 -05002881 layer->setInfo(windowType, ownerUid);
2882
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002884 if (result != NO_ERROR) {
2885 return result;
2886 }
Irvelffc9efc2016-07-27 15:16:37 -07002887 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002888
2889 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002890 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2894 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2895 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
2897 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002898 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899 case PIXEL_FORMAT_TRANSPARENT:
2900 case PIXEL_FORMAT_TRANSLUCENT:
2901 format = PIXEL_FORMAT_RGBA_8888;
2902 break;
2903 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002904 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 break;
2906 }
2907
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002908 *outLayer = new Layer(this, client, name, w, h, flags);
2909 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2910 if (err == NO_ERROR) {
2911 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002912 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002914
2915 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2916 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917}
2918
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002919status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2920 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2921 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002923 *outLayer = new LayerDim(this, client, name, w, h, flags);
2924 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002925 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002926 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002927}
2928
Mathias Agopianac9fa422013-02-11 16:40:36 -08002929status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930{
Robert Carr9524cb32017-02-13 11:32:32 -08002931 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002932 status_t err = NO_ERROR;
2933 sp<Layer> l(client->getLayerUser(handle));
2934 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002935 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002936 err = removeLayer(l);
2937 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2938 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002939 }
2940 return err;
2941}
2942
Mathias Agopian13127d82013-03-05 17:47:11 -08002943status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002944{
Mathias Agopian67106042013-03-14 19:18:13 -07002945 // called by ~LayerCleaner() when all references to the IBinder (handle)
2946 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002947 sp<Layer> l = layer.promote();
2948 if (l == nullptr) {
2949 // The layer has already been removed, carry on
2950 return NO_ERROR;
2951 } if (l->getParent() != nullptr) {
2952 // If we have a parent, then we can continue to live as long as it does.
2953 return NO_ERROR;
2954 }
2955 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956}
2957
Mathias Agopianb60314a2012-04-10 22:09:54 -07002958// ---------------------------------------------------------------------------
2959
Andy McFadden13a082e2012-08-24 10:16:42 -07002960void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002961 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002962 Vector<ComposerState> state;
2963 Vector<DisplayState> displays;
2964 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002965 d.what = DisplayState::eDisplayProjectionChanged |
2966 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002967 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002968 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002969 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002970 d.frame.makeInvalid();
2971 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002972 d.width = 0;
2973 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002974 displays.add(d);
2975 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002977
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2979 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002980 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002981
2982 {
2983 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2984 mCompositorTiming.interval = period;
2985 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002986}
2987
2988void SurfaceFlinger::initializeDisplays() {
2989 class MessageScreenInitialized : public MessageBase {
2990 SurfaceFlinger* flinger;
2991 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002992 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002993 virtual bool handler() {
2994 flinger->onInitializeDisplays();
2995 return true;
2996 }
2997 };
2998 sp<MessageBase> msg = new MessageScreenInitialized(this);
2999 postMessageAsync(msg); // we may be called from main thread, use async message
3000}
3001
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003002void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3003 int mode) {
3004 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3005 this);
3006 int32_t type = hw->getDisplayType();
3007 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003008
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003009 if (mode == currentMode) {
3010 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003011 return;
3012 }
3013
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003014 hw->setPowerMode(mode);
3015 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3016 ALOGW("Trying to set power mode for virtual display");
3017 return;
3018 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003019
Irvelffc9efc2016-07-27 15:16:37 -07003020 if (mInterceptor.isEnabled()) {
3021 Mutex::Autolock _l(mStateLock);
3022 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3023 if (idx < 0) {
3024 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3025 return;
3026 }
3027 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3028 }
3029
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003030 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003031 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003032 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3034 // FIXME: eventthread only knows about the main display right now
3035 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003036 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003039 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003040 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003042
3043 struct sched_param param = {0};
3044 param.sched_priority = 1;
3045 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3046 ALOGW("Couldn't set SCHED_FIFO on display on");
3047 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003049 // Turn off the display
3050 struct sched_param param = {0};
3051 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3052 ALOGW("Couldn't set SCHED_OTHER on display off");
3053 }
3054
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003055 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003056 disableHardwareVsync(true); // also cancels any in-progress resync
3057
Mathias Agopiancde87a32012-09-13 14:09:01 -07003058 // FIXME: eventthread only knows about the main display right now
3059 mEventThread->onScreenReleased();
3060 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003061
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003062 getHwComposer().setPowerMode(type, mode);
3063 mVisibleRegionsDirty = true;
3064 // from this point on, SF will stop drawing on this display
3065 } else {
3066 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003068}
3069
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003070void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3071 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003072 SurfaceFlinger& mFlinger;
3073 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003075 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003076 MessageSetPowerMode(SurfaceFlinger& flinger,
3077 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3078 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003079 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003080 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003081 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003082 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003083 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003084 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003085 ALOGW("Attempt to set power mode = %d for virtual display",
3086 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003087 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003089 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003090 return true;
3091 }
3092 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003093 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003094 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003095}
3096
3097// ---------------------------------------------------------------------------
3098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3100{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003102
Mathias Agopianbd115332013-04-18 16:41:04 -07003103 IPCThreadState* ipc = IPCThreadState::self();
3104 const int pid = ipc->getCallingPid();
3105 const int uid = ipc->getCallingUid();
3106 if ((uid != AID_SHELL) &&
3107 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003108 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003109 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003111 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003112 // (this would indicate SF is stuck, but we want to be able to
3113 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003114 status_t err = mStateLock.timedLock(s2ns(1));
3115 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003116 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003117 result.appendFormat(
3118 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3119 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003120 }
3121
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003122 bool dumpAll = true;
3123 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003124 size_t numArgs = args.size();
3125 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003126 if ((index < numArgs) &&
3127 (args[index] == String16("--list"))) {
3128 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003129 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003130 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003131 }
3132
3133 if ((index < numArgs) &&
3134 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003136 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003137 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003138 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003139
3140 if ((index < numArgs) &&
3141 (args[index] == String16("--latency-clear"))) {
3142 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003143 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003144 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003145 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003146
3147 if ((index < numArgs) &&
3148 (args[index] == String16("--dispsync"))) {
3149 index++;
3150 mPrimaryDispSync.dump(result);
3151 dumpAll = false;
3152 }
Dan Stozab90cf072015-03-05 11:05:59 -08003153
3154 if ((index < numArgs) &&
3155 (args[index] == String16("--static-screen"))) {
3156 index++;
3157 dumpStaticScreenStats(result);
3158 dumpAll = false;
3159 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003160
3161 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003162 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003163 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003164 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003165 dumpAll = false;
3166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003168
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003169 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003170 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003171 }
3172
Mathias Agopian9795c422009-08-26 16:36:26 -07003173 if (locked) {
3174 mStateLock.unlock();
3175 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 }
3177 write(fd, result.string(), result.size());
3178 return NO_ERROR;
3179}
3180
Dan Stozac7014012014-02-14 15:03:43 -08003181void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3182 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003183{
Robert Carr2047fae2016-11-28 14:09:09 -08003184 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003185 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003186 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003187}
3188
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003189void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003190 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003191{
3192 String8 name;
3193 if (index < args.size()) {
3194 name = String8(args[index]);
3195 index++;
3196 }
3197
Dan Stoza9e56aa02015-11-02 13:00:03 -08003198 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3199 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003200 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003201
3202 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003203 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003204 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003206 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003207 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003208 }
Robert Carr2047fae2016-11-28 14:09:09 -08003209 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003210 }
3211}
3212
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003213void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003214 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003215{
3216 String8 name;
3217 if (index < args.size()) {
3218 name = String8(args[index]);
3219 index++;
3220 }
3221
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003223 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003224 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003225 }
Robert Carr2047fae2016-11-28 14:09:09 -08003226 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003227
Svetoslavd85084b2014-03-20 10:28:31 -07003228 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003229}
3230
Jamie Gennis6547ff42013-07-16 20:12:42 -07003231// This should only be called from the main thread. Otherwise it would need
3232// the lock and should use mCurrentState rather than mDrawingState.
3233void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003234 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003235 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003236 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003237
3238 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3239}
3240
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003241void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003242{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003243 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003244 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3245
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003246 if (isLayerTripleBufferingDisabled())
3247 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003248
3249 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003250 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003251 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003252 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003253}
3254
Dan Stozab90cf072015-03-05 11:05:59 -08003255void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3256{
3257 result.appendFormat("Static screen stats:\n");
3258 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3259 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3260 float percent = 100.0f *
3261 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3262 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3263 b + 1, bucketTimeSec, percent);
3264 }
3265 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3266 float percent = 100.0f *
3267 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3268 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3269 NUM_BUCKETS - 1, bucketTimeSec, percent);
3270}
3271
Dan Stozae77c7662016-05-13 11:37:28 -07003272void SurfaceFlinger::recordBufferingStats(const char* layerName,
3273 std::vector<OccupancyTracker::Segment>&& history) {
3274 Mutex::Autolock lock(mBufferingStatsMutex);
3275 auto& stats = mBufferingStats[layerName];
3276 for (const auto& segment : history) {
3277 if (!segment.usedThirdBuffer) {
3278 stats.twoBufferTime += segment.totalTime;
3279 }
3280 if (segment.occupancyAverage < 1.0f) {
3281 stats.doubleBufferedTime += segment.totalTime;
3282 } else if (segment.occupancyAverage < 2.0f) {
3283 stats.tripleBufferedTime += segment.totalTime;
3284 }
3285 ++stats.numSegments;
3286 stats.totalTime += segment.totalTime;
3287 }
3288}
3289
Brian Andersond6927fb2016-07-23 23:37:30 -07003290void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3291 result.appendFormat("Layer frame timestamps:\n");
3292
3293 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3294 const size_t count = currentLayers.size();
3295 for (size_t i=0 ; i<count ; i++) {
3296 currentLayers[i]->dumpFrameEvents(result);
3297 }
3298}
3299
Dan Stozae77c7662016-05-13 11:37:28 -07003300void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3301 result.append("Buffering stats:\n");
3302 result.append(" [Layer name] <Active time> <Two buffer> "
3303 "<Double buffered> <Triple buffered>\n");
3304 Mutex::Autolock lock(mBufferingStatsMutex);
3305 typedef std::tuple<std::string, float, float, float> BufferTuple;
3306 std::map<float, BufferTuple, std::greater<float>> sorted;
3307 for (const auto& statsPair : mBufferingStats) {
3308 const char* name = statsPair.first.c_str();
3309 const BufferingStats& stats = statsPair.second;
3310 if (stats.numSegments == 0) {
3311 continue;
3312 }
3313 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3314 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3315 stats.totalTime;
3316 float doubleBufferRatio = static_cast<float>(
3317 stats.doubleBufferedTime) / stats.totalTime;
3318 float tripleBufferRatio = static_cast<float>(
3319 stats.tripleBufferedTime) / stats.totalTime;
3320 sorted.insert({activeTime, {name, twoBufferRatio,
3321 doubleBufferRatio, tripleBufferRatio}});
3322 }
3323 for (const auto& sortedPair : sorted) {
3324 float activeTime = sortedPair.first;
3325 const BufferTuple& values = sortedPair.second;
3326 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3327 std::get<0>(values).c_str(), activeTime,
3328 std::get<1>(values), std::get<2>(values),
3329 std::get<3>(values));
3330 }
3331 result.append("\n");
3332}
3333
3334
Mathias Agopian74d211a2013-04-22 16:55:35 +02003335void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3336 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003337{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003338 bool colorize = false;
3339 if (index < args.size()
3340 && (args[index] == String16("--color"))) {
3341 colorize = true;
3342 index++;
3343 }
3344
3345 Colorizer colorizer(colorize);
3346
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003347 // figure out if we're stuck somewhere
3348 const nsecs_t now = systemTime();
3349 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3350 const nsecs_t inTransaction(mDebugInTransaction);
3351 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3352 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3353
3354 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003355 * Dump library configuration.
3356 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003357
3358 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003359 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003361 appendSfConfigString(result);
3362 appendUiConfigString(result);
3363 appendGuiConfigString(result);
3364 result.append("\n");
3365
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003366 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003367 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003368 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003369 result.append(SyncFeatures::getInstance().toString());
3370 result.append("\n");
3371
Dan Stoza9e56aa02015-11-02 13:00:03 -08003372 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3373
Andy McFadden41d67d72014-04-25 16:58:34 -07003374 colorizer.bold(result);
3375 result.append("DispSync configuration: ");
3376 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003377 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003378 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003379 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003380 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003381 result.append("\n");
3382
Dan Stozab90cf072015-03-05 11:05:59 -08003383 // Dump static screen stats
3384 result.append("\n");
3385 dumpStaticScreenStats(result);
3386 result.append("\n");
3387
Dan Stozae77c7662016-05-13 11:37:28 -07003388 dumpBufferingStats(result);
3389
Andy McFadden4803b742012-09-24 19:07:20 -07003390 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003391 * Dump the visible layer list
3392 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003393 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003394 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003395 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003396 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003398 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003399
3400 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003401 * Dump Display state
3402 */
3403
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003404 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003405 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003406 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003407 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3408 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003409 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003410 }
3411
3412 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413 * Dump SurfaceFlinger global state
3414 */
3415
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003416 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003417 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003418 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419
Mathias Agopian888c8222012-08-04 21:10:38 -07003420 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003421 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003422
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003423 colorizer.bold(result);
3424 result.appendFormat("EGL implementation : %s\n",
3425 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3426 colorizer.reset(result);
3427 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003428 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003429
Mathias Agopian875d8e12013-06-07 15:35:48 -07003430 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431
Mathias Agopian42977342012-08-05 00:40:46 -07003432 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003433 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3434 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003435 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436 " last eglSwapBuffers() time: %f us\n"
3437 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003438 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003439 " refresh-rate : %f fps\n"
3440 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003441 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003442 " gpu_to_cpu_unsupported : %d\n"
3443 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003444 mLastSwapBufferTime/1000.0,
3445 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003446 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003447 1e9 / activeConfig->getVsyncPeriod(),
3448 activeConfig->getDpiX(),
3449 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003450 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003451
Mathias Agopian74d211a2013-04-22 16:55:35 +02003452 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003453 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003454
Mathias Agopian74d211a2013-04-22 16:55:35 +02003455 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457
3458 /*
3459 * VSYNC state
3460 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003461 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003462 result.append("\n");
3463
3464 /*
3465 * HWC layer minidump
3466 */
3467 for (size_t d = 0; d < mDisplays.size(); d++) {
3468 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3469 int32_t hwcId = displayDevice->getHwcDisplayId();
3470 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3471 continue;
3472 }
3473
3474 result.appendFormat("Display %d HWC layers:\n", hwcId);
3475 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003476 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003477 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 });
Dan Stozae22aec72016-08-01 13:20:59 -07003479 result.append("\n");
3480 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003481
3482 /*
3483 * Dump HWComposer state
3484 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003485 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003486 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003487 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003488 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003489 result.appendFormat(" h/w composer %s\n",
3490 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003491 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003492
3493 /*
3494 * Dump gralloc state
3495 */
3496 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3497 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003498}
3499
Mathias Agopian13127d82013-03-05 17:47:11 -08003500const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003501SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003502 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003503 wp<IBinder> dpy;
3504 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3505 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3506 dpy = mDisplays.keyAt(i);
3507 break;
3508 }
3509 }
3510 if (dpy == NULL) {
3511 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3512 // Just use the primary display so we have something to return
3513 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3514 }
3515 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003516}
3517
Keun young Park63f165f2012-08-31 10:53:36 -07003518bool SurfaceFlinger::startDdmConnection()
3519{
3520 void* libddmconnection_dso =
3521 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3522 if (!libddmconnection_dso) {
3523 return false;
3524 }
3525 void (*DdmConnection_start)(const char* name);
3526 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003527 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003528 if (!DdmConnection_start) {
3529 dlclose(libddmconnection_dso);
3530 return false;
3531 }
3532 (*DdmConnection_start)(getServiceName());
3533 return true;
3534}
3535
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003536status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 switch (code) {
3538 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003539 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003541 case CLEAR_ANIMATION_FRAME_STATS:
3542 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003543 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003544 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545 {
3546 // codes that require permission check
3547 IPCThreadState* ipc = IPCThreadState::self();
3548 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003549 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003550 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003551 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003552 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003553 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003555 break;
3556 }
Robert Carr1db73f62016-12-21 12:58:51 -08003557 /*
3558 * Calling setTransactionState is safe, because you need to have been
3559 * granted a reference to Client* and Handle* to do anything with it.
3560 *
3561 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3562 */
3563 case SET_TRANSACTION_STATE:
3564 case CREATE_SCOPED_CONNECTION:
3565 {
3566 return OK;
3567 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003568 case CAPTURE_SCREEN:
3569 {
3570 // codes that require permission check
3571 IPCThreadState* ipc = IPCThreadState::self();
3572 const int pid = ipc->getCallingPid();
3573 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003574 if ((uid != AID_GRAPHICS) &&
3575 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003576 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003577 return PERMISSION_DENIED;
3578 }
3579 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 }
3581 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003582 return OK;
3583}
3584
3585status_t SurfaceFlinger::onTransact(
3586 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3587{
3588 status_t credentialCheck = CheckTransactCodeCredentials(code);
3589 if (credentialCheck != OK) {
3590 return credentialCheck;
3591 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3594 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003595 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003596 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003597 IPCThreadState* ipc = IPCThreadState::self();
3598 const int pid = ipc->getCallingPid();
3599 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003600 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003601 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 return PERMISSION_DENIED;
3603 }
3604 int n;
3605 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003606 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003607 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 return NO_ERROR;
3609 case 1002: // SHOW_UPDATES
3610 n = data.readInt32();
3611 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003612 invalidateHwcGeometry();
3613 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003616 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003617 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003619 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003620 setTransactionFlags(
3621 eTransactionNeeded|
3622 eDisplayTransactionNeeded|
3623 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003624 return NO_ERROR;
3625 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003626 case 1006:{ // send empty update
3627 signalRefresh();
3628 return NO_ERROR;
3629 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003630 case 1008: // toggle use of hw composer
3631 n = data.readInt32();
3632 mDebugDisableHWC = n ? 1 : 0;
3633 invalidateHwcGeometry();
3634 repaintEverything();
3635 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003636 case 1009: // toggle use of transform hint
3637 n = data.readInt32();
3638 mDebugDisableTransformHint = n ? 1 : 0;
3639 invalidateHwcGeometry();
3640 repaintEverything();
3641 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003643 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 reply->writeInt32(0);
3645 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003646 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003647 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 return NO_ERROR;
3649 case 1013: {
3650 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003651 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3652 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003653 return NO_ERROR;
3654 }
3655 case 1014: {
3656 // daltonize
3657 n = data.readInt32();
3658 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003659 case 1:
3660 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3661 break;
3662 case 2:
3663 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3664 break;
3665 case 3:
3666 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3667 break;
3668 default:
3669 mDaltonizer.setType(ColorBlindnessType::None);
3670 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003671 }
3672 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003673 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003674 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003675 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003676 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003677 invalidateHwcGeometry();
3678 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003681 case 1015: {
3682 // apply a color matrix
3683 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003684 if (n) {
3685 // color matrix is sent as mat3 matrix followed by vec3
3686 // offset, then packed into a mat4 where the last row is
3687 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003688 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003689 for (size_t j = 0; j < 4; j++) {
3690 mColorMatrix[i][j] = data.readFloat();
3691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003692 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003693 } else {
3694 mColorMatrix = mat4();
3695 }
3696 invalidateHwcGeometry();
3697 repaintEverything();
3698 return NO_ERROR;
3699 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003700 // This is an experimental interface
3701 // Needs to be shifted to proper binder interface when we productize
3702 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003703 n = data.readInt32();
3704 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003705 return NO_ERROR;
3706 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003707 case 1017: {
3708 n = data.readInt32();
3709 mForceFullDamage = static_cast<bool>(n);
3710 return NO_ERROR;
3711 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003712 case 1018: { // Modify Choreographer's phase offset
3713 n = data.readInt32();
3714 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3715 return NO_ERROR;
3716 }
3717 case 1019: { // Modify SurfaceFlinger's phase offset
3718 n = data.readInt32();
3719 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3720 return NO_ERROR;
3721 }
Irvel468051e2016-06-13 16:44:44 -07003722 case 1020: { // Layer updates interceptor
3723 n = data.readInt32();
3724 if (n) {
3725 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003726 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003727 }
3728 else{
3729 ALOGV("Interceptor disabled");
3730 mInterceptor.disable();
3731 }
3732 return NO_ERROR;
3733 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003734 case 1021: { // Disable HWC virtual displays
3735 n = data.readInt32();
3736 mUseHwcVirtualDisplays = !n;
3737 return NO_ERROR;
3738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 }
3740 }
3741 return err;
3742}
3743
Mathias Agopian53331da2011-08-22 21:44:41 -07003744void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003745 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003746 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003747}
3748
Mathias Agopian59119e62010-10-11 12:37:43 -07003749// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003750// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003751// ---------------------------------------------------------------------------
3752
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753/* The code below is here to handle b/8734824
3754 *
3755 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003756 * from the surfaceflinger thread to the calling binder thread, where they
3757 * are executed. This allows the calling thread in the calling process to be
3758 * reused and not depend on having "enough" binder threads to handle the
3759 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003760 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003761class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003762 /* Parts of GraphicProducerWrapper are run on two different threads,
3763 * communicating by sending messages via Looper but also by shared member
3764 * data. Coherence maintenance is subtle and in places implicit (ugh).
3765 *
3766 * Don't rely on Looper's sendMessage/handleMessage providing
3767 * release/acquire semantics for any data not actually in the Message.
3768 * Data going from surfaceflinger to binder threads needs to be
3769 * synchronized explicitly.
3770 *
3771 * Barrier open/wait do provide release/acquire semantics. This provides
3772 * implicit synchronization for data coming back from binder to
3773 * surfaceflinger threads.
3774 */
3775
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003776 sp<IGraphicBufferProducer> impl;
3777 sp<Looper> looper;
3778 status_t result;
3779 bool exitPending;
3780 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003781 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003782 uint32_t code;
3783 Parcel const* data;
3784 Parcel* reply;
3785
3786 enum {
3787 MSG_API_CALL,
3788 MSG_EXIT
3789 };
3790
3791 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003792 * Called on surfaceflinger thread. This is called by our "fake"
3793 * BpGraphicBufferProducer. We package the data and reply Parcel and
3794 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 */
3796 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003797 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 this->code = code;
3799 this->data = &data;
3800 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003801 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003802 // if we've exited, we run the message synchronously right here.
3803 // note (JH): as far as I can tell from looking at the code, this
3804 // never actually happens. if it does, i'm not sure if it happens
3805 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003806 handleMessage(Message(MSG_API_CALL));
3807 } else {
3808 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003809 // Prevent stores to this->{code, data, reply} from being
3810 // reordered later than the construction of Message.
3811 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 looper->sendMessage(this, Message(MSG_API_CALL));
3813 barrier.wait();
3814 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003815 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003816 }
3817
3818 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003819 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 * call the real BpGraphicBufferProducer.
3821 */
3822 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003823 int what = message.what;
3824 // Prevent reads below from happening before the read from Message
3825 atomic_thread_fence(memory_order_acquire);
3826 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003827 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003829 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003830 exitRequested = true;
3831 }
3832 }
3833
3834public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003835 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003836 : impl(impl),
3837 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003838 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003839 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003840 exitRequested(false),
3841 code(0),
3842 data(NULL),
3843 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003844 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003845
Jesse Hallb154c422014-07-13 12:47:02 -07003846 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003847 status_t waitForResponse() {
3848 do {
3849 looper->pollOnce(-1);
3850 } while (!exitRequested);
3851 return result;
3852 }
3853
Jesse Hallb154c422014-07-13 12:47:02 -07003854 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003855 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003856 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003857 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003858 // Ensure this->result is visible to the binder thread before it
3859 // handles the message.
3860 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003861 looper->sendMessage(this, Message(MSG_EXIT));
3862 }
3863};
3864
3865
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003866status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3867 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003868 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003869 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003870 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871
3872 if (CC_UNLIKELY(display == 0))
3873 return BAD_VALUE;
3874
3875 if (CC_UNLIKELY(producer == 0))
3876 return BAD_VALUE;
3877
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003878 // if we have secure windows on this display, never allow the screen capture
3879 // unless the producer interface is local (i.e.: we can take a screenshot for
3880 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003881 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003882
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003883 // Convert to surfaceflinger's internal rotation type.
3884 Transform::orientation_flags rotationFlags;
3885 switch (rotation) {
3886 case ISurfaceComposer::eRotateNone:
3887 rotationFlags = Transform::ROT_0;
3888 break;
3889 case ISurfaceComposer::eRotate90:
3890 rotationFlags = Transform::ROT_90;
3891 break;
3892 case ISurfaceComposer::eRotate180:
3893 rotationFlags = Transform::ROT_180;
3894 break;
3895 case ISurfaceComposer::eRotate270:
3896 rotationFlags = Transform::ROT_270;
3897 break;
3898 default:
3899 rotationFlags = Transform::ROT_0;
3900 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3901 break;
3902 }
3903
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003904 class MessageCaptureScreen : public MessageBase {
3905 SurfaceFlinger* flinger;
3906 sp<IBinder> display;
3907 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003908 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 uint32_t reqWidth, reqHeight;
3910 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003911 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003912 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003913 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003914 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003915 public:
3916 MessageCaptureScreen(SurfaceFlinger* flinger,
3917 const sp<IBinder>& display,
3918 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003919 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003920 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003921 bool useIdentityTransform,
3922 Transform::orientation_flags rotation,
3923 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003924 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003925 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003927 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003928 rotation(rotation), result(PERMISSION_DENIED),
3929 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 {
3931 }
3932 status_t getResult() const {
3933 return result;
3934 }
3935 virtual bool handler() {
3936 Mutex::Autolock _l(flinger->mStateLock);
3937 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003938 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003939 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003940 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003941 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003942 return true;
3943 }
3944 };
3945
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946 // this creates a "fake" BBinder which will serve as a "fake" remote
3947 // binder to receive the marshaled calls and forward them to the
3948 // real remote (a BpGraphicBufferProducer)
3949 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3950
3951 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3952 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003953 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003955 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003956 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003957
3958 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003959 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003960 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003961 }
3962 return res;
3963}
3964
Mathias Agopian180f10d2013-04-10 22:55:41 -07003965
3966void SurfaceFlinger::renderScreenImplLocked(
3967 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003968 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003969 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003970 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003971{
3972 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003973 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003974
3975 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003976 const int32_t hw_w = hw->getWidth();
3977 const int32_t hw_h = hw->getHeight();
3978 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003979 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003980
Dan Stozac1879002014-05-22 15:59:05 -07003981 // if a default or invalid sourceCrop is passed in, set reasonable values
3982 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3983 !sourceCrop.isValid()) {
3984 sourceCrop.setLeftTop(Point(0, 0));
3985 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3986 }
3987
3988 // ensure that sourceCrop is inside screen
3989 if (sourceCrop.left < 0) {
3990 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3991 }
Dan Stozabe31f442014-06-11 11:20:54 -07003992 if (sourceCrop.right > hw_w) {
3993 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003994 }
3995 if (sourceCrop.top < 0) {
3996 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3997 }
Dan Stozabe31f442014-06-11 11:20:54 -07003998 if (sourceCrop.bottom > hw_h) {
3999 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004000 }
4001
Mathias Agopian180f10d2013-04-10 22:55:41 -07004002 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004003 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004004
4005 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004006 engine.setViewportAndProjection(
4007 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004008 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004009
4010 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004011 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004012
Robert Carr1f0a16a2016-10-24 16:27:39 -07004013 // We loop through the first level of layers without traversing,
4014 // as we need to interpret min/max layer Z in the top level Z space.
4015 for (const auto& layer : mDrawingState.layersSortedByZ) {
4016 if (layer->getLayerStack() != hw->getLayerStack()) {
4017 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004018 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004019 const Layer::State& state(layer->getDrawingState());
4020 if (state.z < minLayerZ || state.z > maxLayerZ) {
4021 continue;
4022 }
4023 layer->traverseInZOrder([&](Layer* layer) {
4024 if (!layer->isVisible()) {
4025 return;
4026 }
4027 if (filtering) layer->setFiltering(true);
4028 layer->draw(hw, useIdentityTransform);
4029 if (filtering) layer->setFiltering(false);
4030 });
4031 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004032
Mathias Agopian931bda12013-08-28 18:11:46 -07004033 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004034}
4035
4036
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004037status_t SurfaceFlinger::captureScreenImplLocked(
4038 const sp<const DisplayDevice>& hw,
4039 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004040 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004041 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004042 bool useIdentityTransform, Transform::orientation_flags rotation,
4043 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004044{
4045 ATRACE_CALL();
4046
Mathias Agopian180f10d2013-04-10 22:55:41 -07004047 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004048 uint32_t hw_w = hw->getWidth();
4049 uint32_t hw_h = hw->getHeight();
4050
4051 if (rotation & Transform::ROT_90) {
4052 std::swap(hw_w, hw_h);
4053 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004054
Mathias Agopian180f10d2013-04-10 22:55:41 -07004055 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4056 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4057 reqWidth, reqHeight, hw_w, hw_h);
4058 return BAD_VALUE;
4059 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004060
Mathias Agopian180f10d2013-04-10 22:55:41 -07004061 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4062 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4063
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004064 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004065 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004066 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004067 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4068 (state.z < minLayerZ || state.z > maxLayerZ)) {
4069 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004070 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004071 layer->traverseInZOrder([&](Layer *layer) {
4072 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4073 layer->isSecure());
4074 });
4075 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004076
4077 if (!isLocalScreenshot && secureLayerIsVisible) {
4078 ALOGW("FB is protected: PERMISSION_DENIED");
4079 return PERMISSION_DENIED;
4080 }
4081
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004082 // create a surface (because we're a producer, and we need to
4083 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004084 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004085
4086 // Put the screenshot Surface into async mode so that
4087 // Layer::headFenceHasSignaled will always return true and we'll latch the
4088 // first buffer regardless of whether or not its acquire fence has
4089 // signaled. This is needed to avoid a race condition in the rotation
4090 // animation. See b/30209608
4091 sur->setAsyncMode(true);
4092
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004093 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004094
Michael Lentine5a16a622015-05-21 13:48:24 -07004095 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4096 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004097 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4098 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004099
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004100 int err = 0;
4101 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004102 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004103 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4104 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004105
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004106 if (err == NO_ERROR) {
4107 ANativeWindowBuffer* buffer;
4108 /* TODO: Once we have the sync framework everywhere this can use
4109 * server-side waits on the fence that dequeueBuffer returns.
4110 */
4111 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4112 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004113 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004114 // create an EGLImage from the buffer so we can later
4115 // turn it into a texture
4116 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4117 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4118 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004119 // this binds the given EGLImage as a framebuffer for the
4120 // duration of this scope.
4121 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4122 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004123 // this will in fact render into our dequeued buffer
4124 // via an FBO, which means we didn't have to create
4125 // an EGLSurface and therefore we're not
4126 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004127 renderScreenImplLocked(
4128 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4129 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004130
Riley Andrews86639902014-08-15 12:27:24 -07004131 // Attempt to create a sync khr object that can produce a sync point. If that
4132 // isn't available, create a non-dupable sync object in the fallback path and
4133 // wait on it directly.
4134 EGLSyncKHR sync;
4135 if (!DEBUG_SCREENSHOTS) {
4136 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004137 // native fence fd will not be populated until flush() is done.
4138 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004139 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004140 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004141 }
Riley Andrews86639902014-08-15 12:27:24 -07004142 if (sync != EGL_NO_SYNC_KHR) {
4143 // get the sync fd
4144 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4145 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4146 ALOGW("captureScreen: failed to dup sync khr object");
4147 syncFd = -1;
4148 }
4149 eglDestroySyncKHR(mEGLDisplay, sync);
4150 } else {
4151 // fallback path
4152 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4153 if (sync != EGL_NO_SYNC_KHR) {
4154 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4155 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4156 EGLint eglErr = eglGetError();
4157 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4158 ALOGW("captureScreen: fence wait timed out");
4159 } else {
4160 ALOGW_IF(eglErr != EGL_SUCCESS,
4161 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4162 }
4163 eglDestroySyncKHR(mEGLDisplay, sync);
4164 } else {
4165 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4166 }
4167 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004168 if (DEBUG_SCREENSHOTS) {
4169 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4170 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4171 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4172 hw, minLayerZ, maxLayerZ);
4173 delete [] pixels;
4174 }
4175
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004176 } else {
4177 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4178 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004179 window->cancelBuffer(window, buffer, syncFd);
4180 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004181 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004182 // destroy our image
4183 eglDestroyImageKHR(mEGLDisplay, image);
4184 } else {
4185 result = BAD_VALUE;
4186 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004187 if (buffer) {
4188 // queueBuffer takes ownership of syncFd
4189 result = window->queueBuffer(window, buffer, syncFd);
4190 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004191 }
4192 } else {
4193 result = BAD_VALUE;
4194 }
4195 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4196 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004197
Mathias Agopian74c40c02010-09-29 13:02:36 -07004198 return result;
4199}
4200
Mathias Agopiand5556842013-09-19 17:08:37 -07004201void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004202 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004203 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004204 for (size_t y=0 ; y<h ; y++) {
4205 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4206 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004207 if (p[x] != 0xFF000000) return;
4208 }
4209 }
4210 ALOGE("*** we just took a black screenshot ***\n"
4211 "requested minz=%d, maxz=%d, layerStack=%d",
4212 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004213
Robert Carr2047fae2016-11-28 14:09:09 -08004214 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004215 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004216 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004217 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4218 state.z <= maxLayerZ) {
4219 layer->traverseInZOrder([&](Layer* layer) {
4220 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4221 layer->isVisible() ? '+' : '-',
4222 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004223 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004224 i++;
4225 });
4226 }
4227 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004228 }
4229}
4230
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004231// ---------------------------------------------------------------------------
4232
Robert Carr2047fae2016-11-28 14:09:09 -08004233void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4234 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004235}
4236
Robert Carr2047fae2016-11-28 14:09:09 -08004237void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4238 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004239}
4240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004242
4243
4244#if defined(__gl_h_)
4245#error "don't include gl/gl.h in this file"
4246#endif
4247
4248#if defined(__gl2_h_)
4249#error "don't include gl2/gl2.h in this file"
4250#endif