blob: 04358dc76b20e6dd49eafc79c4570b67e6c632dd [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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800118uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800119bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800120bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800121int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Mathias Agopian99b49842011-06-27 16:05:52 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700124 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700126 mTransactionPending(false),
127 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700128 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700129 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700130 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800131 mHwc(nullptr),
132 mRealHwc(nullptr),
133 mVrHwc(nullptr),
134 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800136 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800139 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700141 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700142 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700143 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700144 mDebugInSwapBuffers(0),
145 mLastSwapBufferTime(0),
146 mDebugInTransaction(0),
147 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700148 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700149 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800150 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000151 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700152 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700153 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800154 mHasColorMatrix(false),
155 mHasPoweredOff(false),
156 mFrameBuckets(),
157 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700158 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800159 mNumLayers(0),
160 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800162 ALOGI("SurfaceFlinger is starting");
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
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800170 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700173 useContextPriority = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::useContextPriority>(false);
175
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700176 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
178
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700179 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
181
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800182 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
184
Steven Thomas050b2c82017-03-06 11:45:16 -0800185 // Vr flinger is only enabled on Daydream ready devices.
186 useVrFlinger = getBool< ISurfaceFlingerConfigs,
187 &ISurfaceFlingerConfigs::useVrFlinger>(false);
188
Fabien Sanglard1971b632017-03-10 14:50:03 -0800189 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 // debugging stuff...
193 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194
Mathias Agopianb4b17302013-03-20 18:36:41 -0700195 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700196 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 property_get("debug.sf.showupdates", value, "0");
199 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700201 property_get("debug.sf.ddms", value, "0");
202 mDebugDDMS = atoi(value);
203 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700204 if (!startDdmConnection()) {
205 // start failed, and DDMS debugging not enabled
206 mDebugDDMS = 0;
207 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700208 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700209 ALOGI_IF(mDebugRegion, "showupdates enabled");
210 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700211
212 property_get("debug.sf.disable_backpressure", value, "0");
213 mPropagateBackpressure = !atoi(value);
214 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700215
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800216 property_get("debug.sf.enable_hwc_vds", value, "0");
217 mUseHwcVirtualDisplays = atoi(value);
218 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800219
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800220 property_get("ro.sf.disable_triple_buffer", value, "1");
221 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800222 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223}
224
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800225void SurfaceFlinger::onFirstRef()
226{
227 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800228}
229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230SurfaceFlinger::~SurfaceFlinger()
231{
Mathias Agopiana4912602012-07-12 14:25:33 -0700232 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
233 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
234 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235}
236
Dan Stozac7014012014-02-14 15:03:43 -0800237void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238{
239 // the window manager died on us. prepare its eulogy.
240
Andy McFadden13a082e2012-08-24 10:16:42 -0700241 // restore initial conditions (default device unblank, etc)
242 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243
244 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700245 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800246}
247
Robert Carr1db73f62016-12-21 12:58:51 -0800248static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700249 status_t err = client->initCheck();
250 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800251 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 }
Robert Carr1db73f62016-12-21 12:58:51 -0800253 return nullptr;
254}
255
256sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
257 return initClient(new Client(this));
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
261 const sp<IGraphicBufferProducer>& gbp) {
262 if (authenticateSurfaceTexture(gbp) == false) {
263 return nullptr;
264 }
265 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
266 if (layer == nullptr) {
267 return nullptr;
268 }
269
270 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271}
272
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700273sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
274 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700275{
276 class DisplayToken : public BBinder {
277 sp<SurfaceFlinger> flinger;
278 virtual ~DisplayToken() {
279 // no more references, this display must be terminated
280 Mutex::Autolock _l(flinger->mStateLock);
281 flinger->mCurrentState.displays.removeItem(this);
282 flinger->setTransactionFlags(eDisplayTransactionNeeded);
283 }
284 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700285 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700286 : flinger(flinger) {
287 }
288 };
289
290 sp<BBinder> token = new DisplayToken(this);
291
292 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700293 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700294 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700296 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 return token;
298}
299
Jesse Hall6c913be2013-08-08 12:15:49 -0700300void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
301 Mutex::Autolock _l(mStateLock);
302
303 ssize_t idx = mCurrentState.displays.indexOfKey(display);
304 if (idx < 0) {
305 ALOGW("destroyDisplay: invalid display token");
306 return;
307 }
308
309 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
310 if (!info.isVirtualDisplay()) {
311 ALOGE("destroyDisplay called for non-virtual display");
312 return;
313 }
Irvelffc9efc2016-07-27 15:16:37 -0700314 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700315 mCurrentState.displays.removeItemsAt(idx);
316 setTransactionFlags(eDisplayTransactionNeeded);
317}
318
Jesse Hall692c7232012-11-08 15:41:56 -0800319void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800320 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800321 ALOGW_IF(mBuiltinDisplays[type],
322 "Overwriting display token for display type %d", type);
323 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800324 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700325 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700327 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800328}
329
Mathias Agopiane57f2922012-08-09 16:29:12 -0700330sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700331 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
333 return NULL;
334 }
Jesse Hall692c7232012-11-08 15:41:56 -0800335 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336}
337
Romain Guyf8b4ca52017-03-16 18:39:20 +0000338sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
339{
340 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
341 return gba;
342}
343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344void SurfaceFlinger::bootFinished()
345{
Wei Wangb254fa32017-01-31 17:43:23 -0800346 if (mStartBootAnimThread->join() != NO_ERROR) {
347 ALOGE("Join StartBootAnimThread failed!");
348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 const nsecs_t now = systemTime();
350 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000351 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700352 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700353
354 // wait patiently for the window manager death
355 const String16 name("window");
356 sp<IBinder> window(defaultServiceManager()->getService(name));
357 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700358 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359 }
360
Steven Thomas050b2c82017-03-06 11:45:16 -0800361 if (mVrFlinger) {
362 mVrFlinger->OnBootFinished();
363 }
364
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700365 // 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)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800373}
374
Mathias Agopian3f844832013-08-07 21:24:32 -0700375void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700376 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700377 RenderEngine& engine;
378 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700380 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
381 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700382 }
383 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700384 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385 return true;
386 }
387 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700388 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389}
390
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700391class DispSyncSource : public VSyncSource, private DispSync::Callback {
392public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700393 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000394 const char* name) :
395 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700396 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700397 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000398 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
399 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700400 mDispSync(dispSync),
401 mCallbackMutex(),
402 mCallback(),
403 mVsyncMutex(),
404 mPhaseOffset(phaseOffset),
405 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700406
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700407 virtual ~DispSyncSource() {}
408
409 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700410 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700411 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000412 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700413 static_cast<DispSync::Callback*>(this));
414 if (err != NO_ERROR) {
415 ALOGE("error registering vsync callback: %s (%d)",
416 strerror(-err), err);
417 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700418 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 } else {
420 status_t err = mDispSync->removeEventListener(
421 static_cast<DispSync::Callback*>(this));
422 if (err != NO_ERROR) {
423 ALOGE("error unregistering vsync callback: %s (%d)",
424 strerror(-err), err);
425 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700426 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700428 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 }
430
431 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700432 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700433 mCallback = callback;
434 }
435
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 virtual void setPhaseOffset(nsecs_t phaseOffset) {
437 Mutex::Autolock lock(mVsyncMutex);
438
439 // Normalize phaseOffset to [0, period)
440 auto period = mDispSync->getPeriod();
441 phaseOffset %= period;
442 if (phaseOffset < 0) {
443 // If we're here, then phaseOffset is in (-period, 0). After this
444 // operation, it will be in (0, period)
445 phaseOffset += period;
446 }
447 mPhaseOffset = phaseOffset;
448
449 // If we're not enabled, we don't need to mess with the listeners
450 if (!mEnabled) {
451 return;
452 }
453
454 // Remove the listener with the old offset
455 status_t err = mDispSync->removeEventListener(
456 static_cast<DispSync::Callback*>(this));
457 if (err != NO_ERROR) {
458 ALOGE("error unregistering vsync callback: %s (%d)",
459 strerror(-err), err);
460 }
461
462 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error registering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
469 }
470
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700471private:
472 virtual void onDispSyncEvent(nsecs_t when) {
473 sp<VSyncSource::Callback> callback;
474 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700475 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476 callback = mCallback;
477
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700478 if (mTraceVsync) {
479 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700480 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700481 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 }
483
484 if (callback != NULL) {
485 callback->onVSyncEvent(when);
486 }
487 }
488
Tim Murray4a4e4a22016-04-19 16:29:23 +0000489 const char* const mName;
490
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 int mValue;
492
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700493 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700494 const String8 mVsyncOnLabel;
495 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700496
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700498
499 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501
502 Mutex mVsyncMutex; // Protects the following
503 nsecs_t mPhaseOffset;
504 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505};
506
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700507class InjectVSyncSource : public VSyncSource {
508public:
509 InjectVSyncSource() {}
510
511 virtual ~InjectVSyncSource() {}
512
513 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
514 std::lock_guard<std::mutex> lock(mCallbackMutex);
515 mCallback = callback;
516 }
517
518 virtual void onInjectSyncEvent(nsecs_t when) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback->onVSyncEvent(when);
521 }
522
523 virtual void setVSyncEnabled(bool) {}
524 virtual void setPhaseOffset(nsecs_t) {}
525
526private:
527 std::mutex mCallbackMutex; // Protects the following
528 sp<VSyncSource::Callback> mCallback;
529};
530
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700532 ALOGI( "SurfaceFlinger's main thread ready to run. "
533 "Initializing graphics H/W...");
534
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900535 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
536
Dan Stoza9e56aa02015-11-02 13:00:03 -0800537 { // Autolock scope
538 Mutex::Autolock _l(mStateLock);
539
540 // initialize EGL for the default display
541 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
542 eglInitialize(mEGLDisplay, NULL, NULL);
543
544 // start the EventThread
545 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
546 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700547 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800548 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
549 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700550 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 mEventQueue.setEventThread(mSFEventThread);
552
Tim Murrayacff43d2016-07-29 13:57:24 -0700553 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700554 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700555 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700556 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
557 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
558 }
559
Dan Stoza9e56aa02015-11-02 13:00:03 -0800560 // Get a RenderEngine for the given display / config (can't fail)
561 mRenderEngine = RenderEngine::create(mEGLDisplay,
562 HAL_PIXEL_FORMAT_RGBA_8888);
563 }
564
565 // Drop the state lock while we initialize the hardware composer. We drop
566 // the lock because on creation, it will call back into SurfaceFlinger to
567 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800568 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
569 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800570 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800571 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800572 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
573
Jesse Hall692c7232012-11-08 15:41:56 -0800574 Mutex::Autolock _l(mStateLock);
575
Steven Thomas050b2c82017-03-06 11:45:16 -0800576 if (useVrFlinger) {
577 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
578 mVrFlingerRequestsDisplay = requestDisplay;
579 signalTransaction();
580 };
581 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
582 vrFlingerRequestDisplayCallback);
583 if (!mVrFlinger) {
584 ALOGE("Failed to start vrflinger");
585 }
586 }
587
Mathias Agopian875d8e12013-06-07 15:35:48 -0700588 // retrieve the EGL context that was selected/created
589 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700590
Mathias Agopianda27af92012-09-13 18:17:13 -0700591 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
592 "couldn't create EGLContext");
593
Dan Stoza9e56aa02015-11-02 13:00:03 -0800594 // make the GLContext current so that we can create textures when creating
595 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700596 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
597
Jamie Gennisd1700752013-10-14 12:22:52 -0700598 mEventControlThread = new EventControlThread(this);
599 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
600
Mathias Agopian92a979a2012-08-02 18:32:23 -0700601 // initialize our drawing state
602 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700603
Andy McFadden13a082e2012-08-24 10:16:42 -0700604 // set initial conditions (e.g. unblank default device)
605 initializeDisplays();
606
Dan Stoza4e637772016-07-28 13:31:51 -0700607 mRenderEngine->primeCache();
608
Wei Wangb254fa32017-01-31 17:43:23 -0800609 mStartBootAnimThread = new StartBootAnimThread();
610 if (mStartBootAnimThread->Start() != NO_ERROR) {
611 ALOGE("Run StartBootAnimThread failed!");
612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800613
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700615}
616
Mathias Agopiana67e4182012-06-19 17:26:12 -0700617void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800618 // Start boot animation service by setting a property mailbox
619 // if property setting thread is already running, Start() will be just a NOP
620 mStartBootAnimThread->Start();
621 // Wait until property was set
622 if (mStartBootAnimThread->join() != NO_ERROR) {
623 ALOGE("Join StartBootAnimThread failed!");
624 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700625}
626
Mathias Agopian875d8e12013-06-07 15:35:48 -0700627size_t SurfaceFlinger::getMaxTextureSize() const {
628 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700629}
630
Mathias Agopian875d8e12013-06-07 15:35:48 -0700631size_t SurfaceFlinger::getMaxViewportDims() const {
632 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700633}
634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800636
Jamie Gennis582270d2011-08-17 18:19:00 -0700637bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800638 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800639 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800640 return authenticateSurfaceTextureLocked(bufferProducer);
641}
642
643bool SurfaceFlinger::authenticateSurfaceTextureLocked(
644 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800645 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700646 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800647}
648
Dan Stoza7f7da322014-05-02 15:26:25 -0700649status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
650 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700651 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700652 return BAD_VALUE;
653 }
654
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500655 if (!display.get())
656 return NAME_NOT_FOUND;
657
Jesse Hall692c7232012-11-08 15:41:56 -0800658 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700659 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800660 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700661 type = i;
662 break;
663 }
664 }
665
666 if (type < 0) {
667 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700668 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700669
Mathias Agopian8b736f12012-08-13 17:54:26 -0700670 // TODO: Not sure if display density should handled by SF any longer
671 class Density {
672 static int getDensityFromProperty(char const* propName) {
673 char property[PROPERTY_VALUE_MAX];
674 int density = 0;
675 if (property_get(propName, property, NULL) > 0) {
676 density = atoi(property);
677 }
678 return density;
679 }
680 public:
681 static int getEmuDensity() {
682 return getDensityFromProperty("qemu.sf.lcd_density"); }
683 static int getBuildDensity() {
684 return getDensityFromProperty("ro.sf.lcd_density"); }
685 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700686
Dan Stoza7f7da322014-05-02 15:26:25 -0700687 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700688
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700690 DisplayInfo info = DisplayInfo();
691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 float xdpi = hwConfig->getDpiX();
693 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700694
695 if (type == DisplayDevice::DISPLAY_PRIMARY) {
696 // The density of the device is provided by a build property
697 float density = Density::getBuildDensity() / 160.0f;
698 if (density == 0) {
699 // the build doesn't provide a density -- this is wrong!
700 // use xdpi instead
701 ALOGE("ro.sf.lcd_density must be defined as a build property");
702 density = xdpi / 160.0f;
703 }
704 if (Density::getEmuDensity()) {
705 // if "qemu.sf.lcd_density" is specified, it overrides everything
706 xdpi = ydpi = density = Density::getEmuDensity();
707 density /= 160.0f;
708 }
709 info.density = density;
710
711 // TODO: this needs to go away (currently needed only by webkit)
712 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
713 info.orientation = hw->getOrientation();
714 } else {
715 // TODO: where should this value come from?
716 static const int TV_DENSITY = 213;
717 info.density = TV_DENSITY / 160.0f;
718 info.orientation = 0;
719 }
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 info.w = hwConfig->getWidth();
722 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700723 info.xdpi = xdpi;
724 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900726 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727
Andy McFadden91b2ca82014-06-13 14:04:23 -0700728 // This is how far in advance a buffer must be queued for
729 // presentation at a given time. If you want a buffer to appear
730 // on the screen at time N, you must submit the buffer before
731 // (N - presentationDeadline).
732 //
733 // Normally it's one full refresh period (to give SF a chance to
734 // latch the buffer), but this can be reduced by configuring a
735 // DispSync offset. Any additional delays introduced by the hardware
736 // composer or panel must be accounted for here.
737 //
738 // We add an additional 1ms to allow for processing time and
739 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800741 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700742
743 // All non-virtual displays are currently considered secure.
744 info.secure = true;
745
Michael Wright28f24d02016-07-12 13:30:53 -0700746 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747 }
748
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return NO_ERROR;
750}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700751
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800752status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700753 DisplayStatInfo* stats) {
754 if (stats == NULL) {
755 return BAD_VALUE;
756 }
757
758 // FIXME for now we always return stats for the primary display
759 memset(stats, 0, sizeof(*stats));
760 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
761 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
762 return NO_ERROR;
763}
764
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700765int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800766 if (display == NULL) {
767 ALOGE("%s : display is NULL", __func__);
768 return BAD_VALUE;
769 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700770 sp<DisplayDevice> device(getDisplayDevice(display));
771 if (device != NULL) {
772 return device->getActiveConfig();
773 }
774 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700775}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700776
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700777void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
778 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
779 this);
780 int32_t type = hw->getDisplayType();
781 int currentMode = hw->getActiveConfig();
782
783 if (mode == currentMode) {
784 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
785 return;
786 }
787
788 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
789 ALOGW("Trying to set config for virtual display");
790 return;
791 }
792
793 hw->setActiveConfig(mode);
794 getHwComposer().setActiveConfig(type, mode);
795}
796
797status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
798 class MessageSetActiveConfig: public MessageBase {
799 SurfaceFlinger& mFlinger;
800 sp<IBinder> mDisplay;
801 int mMode;
802 public:
803 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
804 int mode) :
805 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
806 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700807 Vector<DisplayInfo> configs;
808 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700809 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700810 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700811 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700812 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700813 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700814 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
815 if (hw == NULL) {
816 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700817 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700818 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
819 ALOGW("Attempt to set active config = %d for virtual display",
820 mMode);
821 } else {
822 mFlinger.setActiveConfigInternal(hw, mMode);
823 }
824 return true;
825 }
826 };
827 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
828 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700829 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700830}
Michael Wright28f24d02016-07-12 13:30:53 -0700831status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
832 Vector<android_color_mode_t>* outColorModes) {
833 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
834 return BAD_VALUE;
835 }
836
837 if (!display.get()) {
838 return NAME_NOT_FOUND;
839 }
840
841 int32_t type = NAME_NOT_FOUND;
842 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
843 if (display == mBuiltinDisplays[i]) {
844 type = i;
845 break;
846 }
847 }
848
849 if (type < 0) {
850 return type;
851 }
852
853 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
854 outColorModes->clear();
855 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
856
857 return NO_ERROR;
858}
859
860android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
861 sp<DisplayDevice> device(getDisplayDevice(display));
862 if (device != nullptr) {
863 return device->getActiveColorMode();
864 }
865 return static_cast<android_color_mode_t>(BAD_VALUE);
866}
867
868void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
869 android_color_mode_t mode) {
870 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
871 this);
872 int32_t type = hw->getDisplayType();
873 android_color_mode_t currentMode = hw->getActiveColorMode();
874
875 if (mode == currentMode) {
876 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
877 return;
878 }
879
880 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
881 ALOGW("Trying to set config for virtual display");
882 return;
883 }
884
885 hw->setActiveColorMode(mode);
886 getHwComposer().setActiveColorMode(type, mode);
887}
888
889
890status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
891 android_color_mode_t colorMode) {
892 class MessageSetActiveColorMode: public MessageBase {
893 SurfaceFlinger& mFlinger;
894 sp<IBinder> mDisplay;
895 android_color_mode_t mMode;
896 public:
897 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
898 android_color_mode_t mode) :
899 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
900 virtual bool handler() {
901 Vector<android_color_mode_t> modes;
902 mFlinger.getDisplayColorModes(mDisplay, &modes);
903 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
904 if (mMode < 0 || !exists) {
905 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
906 mDisplay.get());
907 return true;
908 }
909 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
910 if (hw == nullptr) {
911 ALOGE("Attempt to set active color mode = %d for null display %p",
912 mMode, mDisplay.get());
913 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
914 ALOGW("Attempt to set active color mode= %d for virtual display",
915 mMode);
916 } else {
917 mFlinger.setActiveColorModeInternal(hw, mMode);
918 }
919 return true;
920 }
921 };
922 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
923 postMessageSync(msg);
924 return NO_ERROR;
925}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700926
Svetoslavd85084b2014-03-20 10:28:31 -0700927status_t SurfaceFlinger::clearAnimationFrameStats() {
928 Mutex::Autolock _l(mStateLock);
929 mAnimFrameTracker.clearStats();
930 return NO_ERROR;
931}
932
933status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
934 Mutex::Autolock _l(mStateLock);
935 mAnimFrameTracker.getStats(outStats);
936 return NO_ERROR;
937}
938
Dan Stozac4f471e2016-03-24 09:31:08 -0700939status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
940 HdrCapabilities* outCapabilities) const {
941 Mutex::Autolock _l(mStateLock);
942
943 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
944 if (displayDevice == nullptr) {
945 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
946 return BAD_VALUE;
947 }
948
949 std::unique_ptr<HdrCapabilities> capabilities =
950 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
951 if (capabilities) {
952 std::swap(*outCapabilities, *capabilities);
953 } else {
954 return BAD_VALUE;
955 }
956
957 return NO_ERROR;
958}
959
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700960status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
961 if (enable == mInjectVSyncs) {
962 return NO_ERROR;
963 }
964
965 if (enable) {
966 mInjectVSyncs = enable;
967 ALOGV("VSync Injections enabled");
968 if (mVSyncInjector.get() == nullptr) {
969 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700970 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700971 }
972 mEventQueue.setEventThread(mInjectorEventThread);
973 } else {
974 mInjectVSyncs = enable;
975 ALOGV("VSync Injections disabled");
976 mEventQueue.setEventThread(mSFEventThread);
977 mVSyncInjector.clear();
978 }
979 return NO_ERROR;
980}
981
982status_t SurfaceFlinger::injectVSync(nsecs_t when) {
983 if (!mInjectVSyncs) {
984 ALOGE("VSync Injections not enabled");
985 return BAD_VALUE;
986 }
987 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
988 ALOGV("Injecting VSync inside SurfaceFlinger");
989 mVSyncInjector->onInjectSyncEvent(when);
990 }
991 return NO_ERROR;
992}
993
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800994// ----------------------------------------------------------------------------
995
996sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800997 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700998}
999
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001000// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001001
1002void SurfaceFlinger::waitForEvent() {
1003 mEventQueue.waitMessage();
1004}
1005
1006void SurfaceFlinger::signalTransaction() {
1007 mEventQueue.invalidate();
1008}
1009
1010void SurfaceFlinger::signalLayerUpdate() {
1011 mEventQueue.invalidate();
1012}
1013
1014void SurfaceFlinger::signalRefresh() {
1015 mEventQueue.refresh();
1016}
1017
1018status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001019 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001020 return mEventQueue.postMessage(msg, reltime);
1021}
1022
1023status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001024 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001025 status_t res = mEventQueue.postMessage(msg, reltime);
1026 if (res == NO_ERROR) {
1027 msg->wait();
1028 }
1029 return res;
1030}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001032void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001033 do {
1034 waitForEvent();
1035 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036}
1037
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001038void SurfaceFlinger::enableHardwareVsync() {
1039 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001040 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001041 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001042 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1043 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001044 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001045 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001046}
1047
Jesse Hall948fe0c2013-10-14 12:56:09 -07001048void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049 Mutex::Autolock _l(mHWVsyncLock);
1050
Jesse Hall948fe0c2013-10-14 12:56:09 -07001051 if (makeAvailable) {
1052 mHWVsyncAvailable = true;
1053 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001054 // Hardware vsync is not currently available, so abort the resync
1055 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001056 return;
1057 }
1058
Dan Stoza9e56aa02015-11-02 13:00:03 -08001059 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1060 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061
1062 mPrimaryDispSync.reset();
1063 mPrimaryDispSync.setPeriod(period);
1064
1065 if (!mPrimaryHWVsyncEnabled) {
1066 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001067 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1068 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069 mPrimaryHWVsyncEnabled = true;
1070 }
1071}
1072
Jesse Hall948fe0c2013-10-14 12:56:09 -07001073void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 Mutex::Autolock _l(mHWVsyncLock);
1075 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001076 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1077 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078 mPrimaryDispSync.endResync();
1079 mPrimaryHWVsyncEnabled = false;
1080 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001081 if (makeUnavailable) {
1082 mHWVsyncAvailable = false;
1083 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001084}
1085
Tim Murray4a4e4a22016-04-19 16:29:23 +00001086void SurfaceFlinger::resyncWithRateLimit() {
1087 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1088 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001089 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001090 }
1091}
1092
Steven Thomas3cfac282017-02-06 12:29:30 -08001093void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1094 nsecs_t timestamp) {
1095 Mutex::Autolock lock(mStateLock);
1096 // Ignore any vsyncs from the non-active hardware composer.
1097 if (composer != mHwc) {
1098 return;
1099 }
1100
Jamie Gennisd1700752013-10-14 12:22:52 -07001101 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001102
Jamie Gennisd1700752013-10-14 12:22:52 -07001103 { // Scope for the lock
1104 Mutex::Autolock _l(mHWVsyncLock);
1105 if (type == 0 && mPrimaryHWVsyncEnabled) {
1106 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001108 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001109
1110 if (needsHwVsync) {
1111 enableHardwareVsync();
1112 } else {
1113 disableHardwareVsync(false);
1114 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001115}
1116
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001117void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001118 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001119 *compositorTiming = mCompositorTiming;
1120}
1121
Dan Stoza9e56aa02015-11-02 13:00:03 -08001122void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1123 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1124 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1125 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001126
Dan Stoza9e56aa02015-11-02 13:00:03 -08001127 // All non-virtual displays are currently considered secure.
1128 bool isSecure = true;
1129
1130 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001131
1132 // When we're using the vr composer, the assumption is that we've
1133 // already created the IBinder object for the primary display.
1134 if (!mHwc->isUsingVrComposer()) {
1135 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1136 }
1137
Dan Stoza9e56aa02015-11-02 13:00:03 -08001138 wp<IBinder> token = mBuiltinDisplays[type];
1139
1140 sp<IGraphicBufferProducer> producer;
1141 sp<IGraphicBufferConsumer> consumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001142 BufferQueue::createBufferQueue(&producer, &consumer,
1143 new GraphicBufferAlloc());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001144
1145 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1146 DisplayDevice::DISPLAY_PRIMARY, consumer);
1147 sp<DisplayDevice> hw = new DisplayDevice(this,
1148 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1149 producer, mRenderEngine->getEGLConfig());
1150 mDisplays.add(token, hw);
1151 } else {
1152 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001153 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001154 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001155 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001156 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001157 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1158 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001159 }
1160 setTransactionFlags(eDisplayTransactionNeeded);
1161
Andy McFadden9e9689c2012-10-10 18:17:51 -07001162 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001163 }
Mathias Agopian86303202012-07-24 22:46:10 -07001164}
1165
Steven Thomas3cfac282017-02-06 12:29:30 -08001166void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1167 Mutex::Autolock lock(mStateLock);
1168 if (composer == mHwc) {
1169 repaintEverything();
1170 } else {
1171 // This isn't from our current hardware composer. If it's a callback
1172 // from the real composer, forward the refresh request to vr
1173 // flinger. Otherwise ignore it.
1174 if (!composer->isUsingVrComposer()) {
1175 mVrFlinger->OnHardwareComposerRefresh();
1176 }
1177 }
1178}
1179
Dan Stoza9e56aa02015-11-02 13:00:03 -08001180void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001182 getHwComposer().setVsyncEnabled(disp,
1183 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001184}
1185
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001186void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1187 for (size_t i = 0; i < layers.size(); ++i) {
1188 layers[i]->clearHwcLayers();
1189 }
1190}
1191
1192void SurfaceFlinger::resetHwc() {
1193 disableHardwareVsync(true);
1194 clearHwcLayers(mDrawingState.layersSortedByZ);
1195 clearHwcLayers(mCurrentState.layersSortedByZ);
1196 // Clear the drawing state so that the logic inside of
1197 // handleTransactionLocked will fire. It will determine the delta between
1198 // mCurrentState and mDrawingState and re-apply all changes when we make the
1199 // transition.
1200 mDrawingState.displays.clear();
1201 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001202 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001203}
1204
Steven Thomas050b2c82017-03-06 11:45:16 -08001205void SurfaceFlinger::updateVrFlinger() {
1206 if (!mVrFlinger)
1207 return;
1208 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1209 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001210 return;
1211 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001212 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001213 // Construct new HWComposer without holding any locks.
1214 mVrHwc = new HWComposer(true);
1215 ALOGV("Vr HWC created");
1216 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001217 {
1218 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001219
Steven Thomas050b2c82017-03-06 11:45:16 -08001220 if (vrFlingerRequestsDisplay) {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001221 resetHwc();
1222
1223 mHwc = mVrHwc;
Steven Thomas050b2c82017-03-06 11:45:16 -08001224 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001225 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -08001226 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001227
1228 resetHwc();
1229
1230 mHwc = mRealHwc;
1231 enableHardwareVsync();
1232 }
1233
1234 mVisibleRegionsDirty = true;
1235 invalidateHwcGeometry();
1236 android_atomic_or(1, &mRepaintEverything);
1237 setTransactionFlags(eDisplayTransactionNeeded);
1238 }
1239 if (mVrHwc) {
1240 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1241 }
1242}
1243
Mathias Agopian4fec8732012-06-29 14:12:52 -07001244void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001245 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001246 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001247 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001248 bool frameMissed = !mHadClientComposition &&
1249 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001250 (mPreviousPresentFence->getSignalTime() ==
1251 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001252 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001253 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001254 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001255 signalLayerUpdate();
1256 break;
1257 }
1258
Steven Thomas050b2c82017-03-06 11:45:16 -08001259 // Now that we're going to make it to the handleMessageTransaction()
1260 // call below it's safe to call updateVrFlinger(), which will
1261 // potentially trigger a display handoff.
1262 updateVrFlinger();
1263
Dan Stoza6b9454d2014-11-07 16:00:59 -08001264 bool refreshNeeded = handleMessageTransaction();
1265 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001266 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001267 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001268 // Signal a refresh if a transaction modified the window state,
1269 // a new buffer was latched, or if HWC has requested a full
1270 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001271 signalRefresh();
1272 }
1273 break;
1274 }
1275 case MessageQueue::REFRESH: {
1276 handleMessageRefresh();
1277 break;
1278 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279 }
1280}
1281
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001283 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001284 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001285 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001286 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001287 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001289}
1290
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001292 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001293 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001294}
1295
1296void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001297 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001298
Pablo Ceballos40845df2016-01-25 17:41:15 -08001299 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001300
Brian Andersond6927fb2016-07-23 23:37:30 -07001301 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001302 rebuildLayerStacks();
1303 setUpHWComposer();
1304 doDebugFlashRegions();
1305 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001306 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001307
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001308 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001309
1310 mHadClientComposition = false;
1311 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1312 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1313 mHadClientComposition = mHadClientComposition ||
1314 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1315 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001316
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001318}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001319
Mathias Agopiancd60f992012-08-16 16:28:27 -07001320void SurfaceFlinger::doDebugFlashRegions()
1321{
1322 // is debugging enabled
1323 if (CC_LIKELY(!mDebugRegion))
1324 return;
1325
1326 const bool repaintEverything = mRepaintEverything;
1327 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1328 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001329 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001330 // transform the dirty region into this screen's coordinate space
1331 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1332 if (!dirtyRegion.isEmpty()) {
1333 // redraw the whole screen
1334 doComposeSurfaces(hw, Region(hw->bounds()));
1335
1336 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001337 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001338 RenderEngine& engine(getRenderEngine());
1339 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1340
Mathias Agopianda27af92012-09-13 18:17:13 -07001341 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342 }
1343 }
1344 }
1345
1346 postFramebuffer();
1347
1348 if (mDebugRegion > 1) {
1349 usleep(mDebugRegion * 1000);
1350 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001351
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001353 auto& displayDevice = mDisplays[displayId];
1354 if (!displayDevice->isDisplayOn()) {
1355 continue;
1356 }
1357
1358 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1360 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001361 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362}
1363
Brian Andersond6927fb2016-07-23 23:37:30 -07001364void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001366 ATRACE_CALL();
1367 ALOGV("preComposition");
1368
Mathias Agopiancd60f992012-08-16 16:28:27 -07001369 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001370 mDrawingState.traverseInZOrder([&](Layer* layer) {
1371 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 needExtraInvalidate = true;
1373 }
Robert Carr2047fae2016-11-28 14:09:09 -08001374 });
1375
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376 if (needExtraInvalidate) {
1377 signalLayerUpdate();
1378 }
1379}
1380
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001381void SurfaceFlinger::updateCompositorTiming(
1382 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1383 std::shared_ptr<FenceTime>& presentFenceTime) {
1384 // Update queue of past composite+present times and determine the
1385 // most recently known composite to present latency.
1386 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1387 nsecs_t compositeToPresentLatency = -1;
1388 while (!mCompositePresentTimes.empty()) {
1389 CompositePresentTime& cpt = mCompositePresentTimes.front();
1390 // Cached values should have been updated before calling this method,
1391 // which helps avoid duplicate syscalls.
1392 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1393 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1394 break;
1395 }
1396 compositeToPresentLatency = displayTime - cpt.composite;
1397 mCompositePresentTimes.pop();
1398 }
1399
1400 // Don't let mCompositePresentTimes grow unbounded, just in case.
1401 while (mCompositePresentTimes.size() > 16) {
1402 mCompositePresentTimes.pop();
1403 }
1404
Brian Andersond0010582017-03-07 13:20:31 -08001405 setCompositorTimingSnapped(
1406 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1407}
1408
1409void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1410 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411 // Integer division and modulo round toward 0 not -inf, so we need to
1412 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001413 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001414 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1415 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1416
Brian Andersond0010582017-03-07 13:20:31 -08001417 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1418 if (idealLatency <= 0) {
1419 idealLatency = vsyncInterval;
1420 }
1421
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001422 // Snap the latency to a value that removes scheduling jitter from the
1423 // composition and present times, which often have >1ms of jitter.
1424 // Reducing jitter is important if an app attempts to extrapolate
1425 // something (such as user input) to an accurate diasplay time.
1426 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1427 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001428 nsecs_t bias = vsyncInterval / 2;
1429 int64_t extraVsyncs =
1430 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1431 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1432 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001433
Brian Andersond0010582017-03-07 13:20:31 -08001434 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1436 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001437 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438}
1439
1440void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001442 ATRACE_CALL();
1443 ALOGV("postComposition");
1444
Brian Anderson3546a3f2016-07-14 11:51:14 -07001445 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001446 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001447 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001448 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001449 }
1450
Brian Andersond6927fb2016-07-23 23:37:30 -07001451 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001452
1453 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1454 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1455 glCompositionDoneFenceTime =
1456 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1457 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1458 } else {
1459 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1460 }
1461 mGlCompositionDoneTimeline.updateSignalTimes();
1462
Brian Anderson4e606e32017-03-16 15:34:57 -07001463 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1464 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1465 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001466 mDisplayTimeline.updateSignalTimes();
1467
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001468 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1469 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1470
1471 // We use the refreshStartTime which might be sampled a little later than
1472 // when we started doing work for this frame, but that should be okay
1473 // since updateCompositorTiming has snapping logic.
1474 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001475 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001476 CompositorTiming compositorTiming;
1477 {
1478 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1479 compositorTiming = mCompositorTiming;
1480 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481
Robert Carr2047fae2016-11-28 14:09:09 -08001482 mDrawingState.traverseInZOrder([&](Layer* layer) {
1483 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001484 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001485 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001486 recordBufferingStats(layer->getName().string(),
1487 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001488 }
Robert Carr2047fae2016-11-28 14:09:09 -08001489 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001490
Brian Anderson4e606e32017-03-16 15:34:57 -07001491 if (presentFence->isValid()) {
1492 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001493 enableHardwareVsync();
1494 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001495 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001496 }
1497 }
1498
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001499 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001500 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001501 enableHardwareVsync();
1502 }
1503 }
1504
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001505 if (mAnimCompositionPending) {
1506 mAnimCompositionPending = false;
1507
Brian Anderson4e606e32017-03-16 15:34:57 -07001508 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001509 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001510 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001511 } else {
1512 // The HWC doesn't support present fences, so use the refresh
1513 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001514 nsecs_t presentTime =
1515 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001516 mAnimFrameTracker.setActualPresentTime(presentTime);
1517 }
1518 mAnimFrameTracker.advanceFrame();
1519 }
Dan Stozab90cf072015-03-05 11:05:59 -08001520
1521 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1522 return;
1523 }
1524
1525 nsecs_t currentTime = systemTime();
1526 if (mHasPoweredOff) {
1527 mHasPoweredOff = false;
1528 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001529 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001531 if (numPeriods < NUM_BUCKETS - 1) {
1532 mFrameBuckets[numPeriods] += elapsedTime;
1533 } else {
1534 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1535 }
1536 mTotalTime += elapsedTime;
1537 }
1538 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001539}
1540
1541void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 ATRACE_CALL();
1543 ALOGV("rebuildLayerStacks");
1544
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001546 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1547 ATRACE_CALL();
1548 mVisibleRegionsDirty = false;
1549 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001550
Jeff Sharkey76488112017-02-27 14:15:18 -07001551 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1552 Region opaqueRegion;
1553 Region dirtyRegion;
1554 Vector<sp<Layer>> layersSortedByZ;
1555 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1556 const Transform& tr(displayDevice->getTransform());
1557 const Rect bounds(displayDevice->getBounds());
1558 if (displayDevice->isDisplayOn()) {
1559 computeVisibleRegions(
1560 displayDevice->getLayerStack(), dirtyRegion,
1561 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001562
Jeff Sharkey76488112017-02-27 14:15:18 -07001563 mDrawingState.traverseInZOrder([&](Layer* layer) {
1564 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1565 Region drawRegion(tr.transform(
1566 layer->visibleNonTransparentRegion));
1567 drawRegion.andSelf(bounds);
1568 if (!drawRegion.isEmpty()) {
1569 layersSortedByZ.add(layer);
1570 } else {
1571 // Clear out the HWC layer if this layer was
1572 // previously visible, but no longer is
1573 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1574 nullptr);
1575 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001576 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001577 // WM changes displayDevice->layerStack upon sleep/awake.
1578 // Here we make sure we delete the HWC layers even if
1579 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001580 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1581 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001582 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001583 });
1584 }
1585 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1586 displayDevice->undefinedRegion.set(bounds);
1587 displayDevice->undefinedRegion.subtractSelf(
1588 tr.transform(opaqueRegion));
1589 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001590 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001591 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001593
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 ATRACE_CALL();
1596 ALOGV("setUpHWComposer");
1597
Jesse Hall028dc8f2013-08-20 16:35:32 -07001598 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001599 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1600 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1601 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1602
1603 // If nothing has changed (!dirty), don't recompose.
1604 // If something changed, but we don't currently have any visible layers,
1605 // and didn't when we last did a composition, then skip it this time.
1606 // The second rule does two things:
1607 // - When all layers are removed from a display, we'll emit one black
1608 // frame, then nothing more until we get new layers.
1609 // - When a display is created with a private layer stack, we won't
1610 // emit any black frames until a layer is added to the layer stack.
1611 bool mustRecompose = dirty && !(empty && wasEmpty);
1612
1613 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1614 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1615 mustRecompose ? "doing" : "skipping",
1616 dirty ? "+" : "-",
1617 empty ? "+" : "-",
1618 wasEmpty ? "+" : "-");
1619
Dan Stoza71433162014-02-04 16:22:36 -08001620 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001621
1622 if (mustRecompose) {
1623 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1624 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001625 }
1626
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 // build the h/w work list
1628 if (CC_UNLIKELY(mGeometryInvalid)) {
1629 mGeometryInvalid = false;
1630 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1631 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1632 const auto hwcId = displayDevice->getHwcDisplayId();
1633 if (hwcId >= 0) {
1634 const Vector<sp<Layer>>& currentLayers(
1635 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001636 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001637 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001638 if (!layer->hasHwcLayer(hwcId)) {
1639 auto hwcLayer = mHwc->createLayer(hwcId);
1640 if (hwcLayer) {
1641 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1642 } else {
1643 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001645 }
1646 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001647
Robert Carrae060832016-11-28 10:51:00 -08001648 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001649 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001651 }
1652 }
1653 }
1654 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 }
Riley Andrews03414a12014-07-01 14:22:59 -07001656
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001657
1658 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1659
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 // Set the per-frame data
1661 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1662 auto& displayDevice = mDisplays[displayId];
1663 const auto hwcId = displayDevice->getHwcDisplayId();
1664 if (hwcId < 0) {
1665 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001666 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001667 if (colorMatrix != mPreviousColorMatrix) {
1668 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1669 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1670 "display %zd: %d", displayId, result);
1671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1673 layer->setPerFrameData(displayDevice);
1674 }
1675 }
1676
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001677 mPreviousColorMatrix = colorMatrix;
1678
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001680 auto& displayDevice = mDisplays[displayId];
1681 if (!displayDevice->isDisplayOn()) {
1682 continue;
1683 }
1684
1685 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1687 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001688 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001690
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691void SurfaceFlinger::doComposition() {
1692 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 ALOGV("doComposition");
1694
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001695 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001696 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001697 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001698 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 // transform the dirty region into this screen's coordinate space
1700 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001701
1702 // repaint the framebuffer (if needed)
1703 doDisplayComposition(hw, dirtyRegion);
1704
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 hw->dirtyRegion.clear();
1706 hw->flip(hw->swapRegion);
1707 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001708 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001710 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711}
1712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001713void SurfaceFlinger::postFramebuffer()
1714{
Mathias Agopian841cde52012-03-01 15:44:37 -08001715 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001717
Mathias Agopiana44b0412011-10-16 18:46:35 -07001718 const nsecs_t now = systemTime();
1719 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001720
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1722 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001723 if (!displayDevice->isDisplayOn()) {
1724 continue;
1725 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 const auto hwcId = displayDevice->getHwcDisplayId();
1727 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001728 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001729 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001730 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001731 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1733 sp<Fence> releaseFence = Fence::NO_FENCE;
1734 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1735 releaseFence = displayDevice->getClientTargetAcquireFence();
1736 } else {
1737 auto hwcLayer = layer->getHwcLayer(hwcId);
1738 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 layer->onLayerDisplayed(releaseFence);
1741 }
1742 if (hwcId >= 0) {
1743 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001744 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001745 }
1746
Mathias Agopiana44b0412011-10-16 18:46:35 -07001747 mLastSwapBufferTime = systemTime() - now;
1748 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001749
1750 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1751 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1752 logFrameStats();
1753 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001754}
1755
Mathias Agopian87baae12012-07-31 12:38:26 -07001756void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001757{
Mathias Agopian841cde52012-03-01 15:44:37 -08001758 ATRACE_CALL();
1759
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001760 // here we keep a copy of the drawing state (that is the state that's
1761 // going to be overwritten by handleTransactionLocked()) outside of
1762 // mStateLock so that the side-effects of the State assignment
1763 // don't happen with mStateLock held (which can cause deadlocks).
1764 State drawingState(mDrawingState);
1765
Mathias Agopianca4d3602011-05-19 15:38:14 -07001766 Mutex::Autolock _l(mStateLock);
1767 const nsecs_t now = systemTime();
1768 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769
Mathias Agopianca4d3602011-05-19 15:38:14 -07001770 // Here we're guaranteed that some transaction flags are set
1771 // so we can call handleTransactionLocked() unconditionally.
1772 // We call getTransactionFlags(), which will also clear the flags,
1773 // with mStateLock held to guarantee that mCurrentState won't change
1774 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001775
Mathias Agopiane57f2922012-08-09 16:29:12 -07001776 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001777 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001778
Mathias Agopianca4d3602011-05-19 15:38:14 -07001779 mLastTransactionTime = systemTime() - now;
1780 mDebugInTransaction = 0;
1781 invalidateHwcGeometry();
1782 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001783}
1784
Mathias Agopian87baae12012-07-31 12:38:26 -07001785void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001786{
Dan Stoza7dde5992015-05-22 09:51:44 -07001787 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001788 mCurrentState.traverseInZOrder([](Layer* layer) {
1789 layer->notifyAvailableFrames();
1790 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001791
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001792 /*
1793 * Traversal of the children
1794 * (perform the transaction for each of them if needed)
1795 */
1796
Mathias Agopian3559b072012-08-15 13:46:03 -07001797 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001798 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001799 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001800 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801
1802 const uint32_t flags = layer->doTransaction(0);
1803 if (flags & Layer::eVisibleRegion)
1804 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001805 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806 }
1807
1808 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001809 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810 */
1811
Mathias Agopiane57f2922012-08-09 16:29:12 -07001812 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001813 // here we take advantage of Vector's copy-on-write semantics to
1814 // improve performance by skipping the transaction entirely when
1815 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001816 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1817 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001818 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001820 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001821 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001822
1823 // find the displays that were removed
1824 // (ie: in drawing state but not in current state)
1825 // also handle displays that changed
1826 // (ie: displays that are in both lists)
1827 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001828 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1829 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001830 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001831 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001832 // Call makeCurrent() on the primary display so we can
1833 // be sure that nothing associated with this display
1834 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001835 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001836 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001837 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1838 if (hw != NULL)
1839 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001840 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001841 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001842 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001843 } else {
1844 ALOGW("trying to remove the main display");
1845 }
1846 } else {
1847 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001848 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001849 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001850 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1851 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001852 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001853 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001854 // recreating the DisplayDevice, so we just remove it
1855 // from the drawing state, so that it get re-added
1856 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001857 sp<DisplayDevice> hw(getDisplayDevice(display));
1858 if (hw != NULL)
1859 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001860 mDisplays.removeItem(display);
1861 mDrawingState.displays.removeItemsAt(i);
1862 dc--; i--;
1863 // at this point we must loop to the next item
1864 continue;
1865 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001866
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001867 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001868 if (disp != NULL) {
1869 if (state.layerStack != draw[i].layerStack) {
1870 disp->setLayerStack(state.layerStack);
1871 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001872 if ((state.orientation != draw[i].orientation)
1873 || (state.viewport != draw[i].viewport)
1874 || (state.frame != draw[i].frame))
1875 {
1876 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001877 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001878 }
Michael Lentine47e45402014-07-18 15:34:25 -07001879 if (state.width != draw[i].width || state.height != draw[i].height) {
1880 disp->setDisplaySize(state.width, state.height);
1881 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001882 }
1883 }
1884 }
1885
1886 // find displays that were added
1887 // (ie: in current state but not in drawing state)
1888 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001889 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001890 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001891
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001892 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001893 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001894 sp<IGraphicBufferProducer> bqProducer;
1895 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001896 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1897 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001898
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001900 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001901 // Virtual displays without a surface are dormant:
1902 // they have external state (layer stack, projection,
1903 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001904 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001905
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04001906 // Allow VR composer to use virtual displays.
1907 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07001908 int width = 0;
1909 int status = state.surface->query(
1910 NATIVE_WINDOW_WIDTH, &width);
1911 ALOGE_IF(status != NO_ERROR,
1912 "Unable to query width (%d)", status);
1913 int height = 0;
1914 status = state.surface->query(
1915 NATIVE_WINDOW_HEIGHT, &height);
1916 ALOGE_IF(status != NO_ERROR,
1917 "Unable to query height (%d)", status);
1918 int intFormat = 0;
1919 status = state.surface->query(
1920 NATIVE_WINDOW_FORMAT, &intFormat);
1921 ALOGE_IF(status != NO_ERROR,
1922 "Unable to query format (%d)", status);
1923 auto format = static_cast<android_pixel_format_t>(
1924 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001925
Dan Stoza8cf150a2016-08-02 10:27:31 -07001926 mHwc->allocateVirtualDisplay(width, height, &format,
1927 &hwcId);
1928 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929
Dan Stoza5cf424b2016-05-20 14:02:39 -07001930 // TODO: Plumb requested format back up to consumer
1931
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 sp<VirtualDisplaySurface> vds =
1933 new VirtualDisplaySurface(*mHwc,
1934 hwcId, state.surface, bqProducer,
1935 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001936
1937 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001938 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001939 }
1940 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001941 ALOGE_IF(state.surface!=NULL,
1942 "adding a supported display, but rendering "
1943 "surface is provided (%p), ignoring it",
1944 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001945
1946 hwcId = state.type;
1947 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1948 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001949 }
1950
1951 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001952 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001953 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 state.type, hwcId, state.isSecure, display,
1955 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001956 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001957 hw->setLayerStack(state.layerStack);
1958 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001959 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001960 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001961 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001963 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001964 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001965 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001966 }
1967 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970
Mathias Agopian84300952012-11-21 16:02:13 -08001971 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1972 // The transform hint might have changed for some layers
1973 // (either because a display has changed, or because a layer
1974 // as changed).
1975 //
1976 // Walk through all the layers in currentLayers,
1977 // and update their transform hint.
1978 //
1979 // If a layer is visible only on a single display, then that
1980 // display is used to calculate the hint, otherwise we use the
1981 // default display.
1982 //
1983 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1984 // the hint is set before we acquire a buffer from the surface texture.
1985 //
1986 // NOTE: layer transactions have taken place already, so we use their
1987 // drawing state. However, SurfaceFlinger's own transaction has not
1988 // happened yet, so we must use the current state layer list
1989 // (soon to become the drawing state list).
1990 //
1991 sp<const DisplayDevice> disp;
1992 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001993 bool first = true;
1994 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001995 // NOTE: we rely on the fact that layers are sorted by
1996 // layerStack first (so we don't have to traverse the list
1997 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001998 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001999 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002000 currentlayerStack = layerStack;
2001 // figure out if this layerstack is mirrored
2002 // (more than one display) if so, pick the default display,
2003 // if not, pick the only display it's on.
2004 disp.clear();
2005 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2006 sp<const DisplayDevice> hw(mDisplays[dpy]);
2007 if (hw->getLayerStack() == currentlayerStack) {
2008 if (disp == NULL) {
2009 disp = hw;
2010 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002011 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002012 break;
2013 }
2014 }
2015 }
2016 }
Chet Haase91d25932013-04-11 15:24:55 -07002017 if (disp == NULL) {
2018 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2019 // redraw after transform hint changes. See bug 8508397.
2020
2021 // could be null when this layer is using a layerStack
2022 // that is not visible on any display. Also can occur at
2023 // screen off/on times.
2024 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002025 }
Chet Haase91d25932013-04-11 15:24:55 -07002026 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002027
2028 first = false;
2029 });
Mathias Agopian84300952012-11-21 16:02:13 -08002030 }
2031
2032
Mathias Agopian3559b072012-08-15 13:46:03 -07002033 /*
2034 * Perform our own transaction if needed
2035 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002036
2037 if (mLayersAdded) {
2038 mLayersAdded = false;
2039 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002040 mVisibleRegionsDirty = true;
2041 }
2042
2043 // some layers might have been removed, so
2044 // we need to update the regions they're exposing.
2045 if (mLayersRemoved) {
2046 mLayersRemoved = false;
2047 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002048 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002049 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002050 // this layer is not visible anymore
2051 // TODO: we could traverse the tree from front to back and
2052 // compute the actual visible region
2053 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002054 Region visibleReg;
2055 visibleReg.set(layer->computeScreenBounds());
2056 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002057 }
Robert Carr2047fae2016-11-28 14:09:09 -08002058 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059 }
2060
2061 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002062
2063 updateCursorAsync();
2064}
2065
2066void SurfaceFlinger::updateCursorAsync()
2067{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2069 auto& displayDevice = mDisplays[displayId];
2070 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002071 continue;
2072 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073
2074 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2075 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002076 }
2077 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002078}
2079
2080void SurfaceFlinger::commitTransaction()
2081{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002082 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002083 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002084 for (const auto& l : mLayersPendingRemoval) {
2085 recordBufferingStats(l->getName().string(),
2086 l->getOccupancyHistory(true));
2087 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002088 }
2089 mLayersPendingRemoval.clear();
2090 }
2091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 // If this transaction is part of a window animation then the next frame
2093 // we composite should be considered an animation as well.
2094 mAnimCompositionPending = mAnimTransactionPending;
2095
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002097 mDrawingState.traverseInZOrder([](Layer* layer) {
2098 layer->commitChildList();
2099 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002100 mTransactionPending = false;
2101 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103}
2104
Robert Carr2047fae2016-11-28 14:09:09 -08002105void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002106 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002107{
Mathias Agopian841cde52012-03-01 15:44:37 -08002108 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111 Region aboveOpaqueLayers;
2112 Region aboveCoveredLayers;
2113 Region dirty;
2114
Mathias Agopian87baae12012-07-31 12:38:26 -07002115 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116
Robert Carr2047fae2016-11-28 14:09:09 -08002117 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002119 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120
Jesse Hall01e29052013-02-19 16:13:35 -08002121 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002122 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002123 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002124
Mathias Agopianab028732010-03-16 16:41:46 -07002125 /*
2126 * opaqueRegion: area of a surface that is fully opaque.
2127 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002129
2130 /*
2131 * visibleRegion: area of a surface that is visible on screen
2132 * and not fully transparent. This is essentially the layer's
2133 * footprint minus the opaque regions above it.
2134 * Areas covered by a translucent surface are considered visible.
2135 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002137
2138 /*
2139 * coveredRegion: area of a surface that is covered by all
2140 * visible regions above it (which includes the translucent areas).
2141 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002143
Jesse Halla8026d22012-09-25 13:25:04 -07002144 /*
2145 * transparentRegion: area of a surface that is hinted to be completely
2146 * transparent. This is only used to tell when the layer has no visible
2147 * non-transparent regions and can be removed from the layer list. It
2148 * does not affect the visibleRegion of this layer or any layers
2149 * beneath it. The hint may not be correct if apps don't respect the
2150 * SurfaceView restrictions (which, sadly, some don't).
2151 */
2152 Region transparentRegion;
2153
Mathias Agopianab028732010-03-16 16:41:46 -07002154
2155 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002156 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002157 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002158 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002160 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002161 if (!visibleRegion.isEmpty()) {
2162 // Remove the transparent area from the visible region
2163 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002164 if (tr.preserveRects()) {
2165 // transform the transparent region
2166 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002167 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002168 // transformation too complex, can't do the
2169 // transparent region optimization.
2170 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002171 }
Mathias Agopianab028732010-03-16 16:41:46 -07002172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002173
Mathias Agopianab028732010-03-16 16:41:46 -07002174 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002175 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002177 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2178 // the opaque region is the layer's footprint
2179 opaqueRegion = visibleRegion;
2180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002181 }
2182 }
2183
Mathias Agopianab028732010-03-16 16:41:46 -07002184 // Clip the covered region to the visible region
2185 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2186
2187 // Update aboveCoveredLayers for next (lower) layer
2188 aboveCoveredLayers.orSelf(visibleRegion);
2189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002190 // subtract the opaque region covered by the layers above us
2191 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192
2193 // compute this layer's dirty region
2194 if (layer->contentDirty) {
2195 // we need to invalidate the whole region
2196 dirty = visibleRegion;
2197 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002198 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002199 layer->contentDirty = false;
2200 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002201 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002202 * the exposed region consists of two components:
2203 * 1) what's VISIBLE now and was COVERED before
2204 * 2) what's EXPOSED now less what was EXPOSED before
2205 *
2206 * note that (1) is conservative, we start with the whole
2207 * visible region but only keep what used to be covered by
2208 * something -- which mean it may have been exposed.
2209 *
2210 * (2) handles areas that were not covered by anything but got
2211 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002212 */
Mathias Agopianab028732010-03-16 16:41:46 -07002213 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002214 const Region oldVisibleRegion = layer->visibleRegion;
2215 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002216 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2217 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218 }
2219 dirty.subtractSelf(aboveOpaqueLayers);
2220
2221 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002222 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223
Mathias Agopianab028732010-03-16 16:41:46 -07002224 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002226
Jesse Halla8026d22012-09-25 13:25:04 -07002227 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 layer->setVisibleRegion(visibleRegion);
2229 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002230 layer->setVisibleNonTransparentRegion(
2231 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002232 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233
Mathias Agopian87baae12012-07-31 12:38:26 -07002234 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235}
2236
Mathias Agopian87baae12012-07-31 12:38:26 -07002237void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2238 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002239 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002240 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2241 if (hw->getLayerStack() == layerStack) {
2242 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002243 }
2244 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002245}
2246
Dan Stoza6b9454d2014-11-07 16:00:59 -08002247bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 ALOGV("handlePageFlip");
2250
Brian Andersond6927fb2016-07-23 23:37:30 -07002251 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252
Mathias Agopian4fec8732012-06-29 14:12:52 -07002253 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002254 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002255
2256 // Store the set of layers that need updates. This set must not change as
2257 // buffers are being latched, as this could result in a deadlock.
2258 // Example: Two producers share the same command stream and:
2259 // 1.) Layer 0 is latched
2260 // 2.) Layer 0 gets a new frame
2261 // 2.) Layer 1 gets a new frame
2262 // 3.) Layer 1 is latched.
2263 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2264 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002265 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002266 if (layer->hasQueuedFrame()) {
2267 frameQueued = true;
2268 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002269 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002270 } else {
2271 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002272 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002273 } else {
2274 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002275 }
Robert Carr2047fae2016-11-28 14:09:09 -08002276 });
2277
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002279 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002280 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002281 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002282 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002283
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002284 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285
2286 // If we will need to wake up at some time in the future to deal with a
2287 // queued frame that shouldn't be displayed during this vsync period, wake
2288 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002290 signalLayerUpdate();
2291 }
2292
2293 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295}
2296
Mathias Agopianad456f92011-01-13 17:53:01 -08002297void SurfaceFlinger::invalidateHwcGeometry()
2298{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002300}
2301
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002302
Fabien Sanglard830b8472016-11-30 16:35:58 -08002303void SurfaceFlinger::doDisplayComposition(
2304 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002305 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306{
Dan Stoza71433162014-02-04 16:22:36 -08002307 // We only need to actually compose the display if:
2308 // 1) It is being handled by hardware composer, which may need this to
2309 // keep its virtual display state machine in sync, or
2310 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002311 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002312 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002313 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002314 return;
2315 }
2316
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 ALOGV("doDisplayComposition");
2318
Mathias Agopian87baae12012-07-31 12:38:26 -07002319 Region dirtyRegion(inDirtyRegion);
2320
Mathias Agopianb8a55602009-06-26 19:06:36 -07002321 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002322 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323
Fabien Sanglard830b8472016-11-30 16:35:58 -08002324 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002325 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002326 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2327 // takes a rectangle, we must make sure to update that whole
2328 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002329 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002330 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002331 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002332 // We need to redraw the rectangle that will be updated
2333 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002334 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002335 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002336 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002337 } else {
2338 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 dirtyRegion.set(displayDevice->bounds());
2340 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 }
2342 }
2343
Fabien Sanglard830b8472016-11-30 16:35:58 -08002344 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002346 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002347 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002348
2349 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002350 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351}
2352
Dan Stoza9e56aa02015-11-02 13:00:03 -08002353bool SurfaceFlinger::doComposeSurfaces(
2354 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002355{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002356 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002357
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002359
2360 mat4 oldColorMatrix;
2361 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2362 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2363 if (applyColorMatrix) {
2364 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2365 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2366 }
2367
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2369 if (hasClientComposition) {
2370 ALOGV("hasClientComposition");
2371
2372 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002373 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002375 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2376 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2377 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2378 }
2379 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002380 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002381
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002382 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2384 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002385 // when using overlays, we assume a fully transparent framebuffer
2386 // NOTE: we could reduce how much we need to clear, for instance
2387 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002388 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002389 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002390 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002391 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002392 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002394
2395 // we remove the scissor part
2396 // we're left with the letterbox region
2397 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002399
2400 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002402
2403 // but limit it to the dirty region
2404 region.andSelf(dirty);
2405
Mathias Agopianb9494d52012-04-18 02:28:45 -07002406 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002407 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002408 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002410 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002411 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002412
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002414 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002415 // scissor on the main display. It should never be needed
2416 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 const Rect& bounds(displayDevice->getBounds());
2418 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002419 if (scissor != bounds) {
2420 // scissor doesn't match the screen's dimensions, so we
2421 // need to clear everything outside of it and enable
2422 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002423
Mathias Agopianf45c5102012-10-24 16:29:17 -07002424 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002425 const uint32_t height = displayDevice->getHeight();
2426 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002427 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002428 }
2429 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002430 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002431
Mathias Agopian85d751c2012-08-29 16:59:24 -07002432 /*
2433 * and then, render the layers targeted at the framebuffer
2434 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002435
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 ALOGV("Rendering client layers");
2437 const Transform& displayTransform = displayDevice->getTransform();
2438 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002439 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 bool firstLayer = true;
2441 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2442 const Region clip(dirty.intersect(
2443 displayTransform.transform(layer->visibleRegion)));
2444 ALOGV("Layer: %s", layer->getName().string());
2445 ALOGV(" Composition type: %s",
2446 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002447 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 switch (layer->getCompositionType(hwcId)) {
2449 case HWC2::Composition::Cursor:
2450 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002451 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002452 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002453 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2455 layer->isOpaque(state) && (state.alpha == 1.0f)
2456 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002457 // never clear the very first layer since we're
2458 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002459 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002460 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002461 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002462 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 case HWC2::Composition::Client: {
2464 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002465 break;
2466 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002468 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002469 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 } else {
2471 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002472 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002474 }
2475 } else {
2476 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002478 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002480 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002482 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002483 }
2484 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002485
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002486 if (applyColorMatrix) {
2487 getRenderEngine().setupColorTransform(oldColorMatrix);
2488 }
2489
Mathias Agopianf45c5102012-10-24 16:29:17 -07002490 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002492 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493}
2494
Fabien Sanglard830b8472016-11-30 16:35:58 -08002495void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2496 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002497 RenderEngine& engine(getRenderEngine());
2498 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Dan Stoza7d89d062015-04-30 13:29:25 -07002501status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002502 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002503 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002504 const sp<Layer>& lbc,
2505 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002506{
Dan Stoza7d89d062015-04-30 13:29:25 -07002507 // add this layer to the current state list
2508 {
2509 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002510 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002511 return NO_MEMORY;
2512 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 if (parent == nullptr) {
2514 mCurrentState.layersSortedByZ.add(lbc);
2515 } else {
2516 parent->addChild(lbc);
2517 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002518 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519 mLayersAdded = true;
2520 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002521 }
2522
Mathias Agopian96f08192010-06-02 23:28:45 -07002523 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002524 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002525
Dan Stoza7d89d062015-04-30 13:29:25 -07002526 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002527}
2528
Robert Carr9524cb32017-02-13 11:32:32 -08002529status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002530 Mutex::Autolock _l(mStateLock);
2531
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 const auto& p = layer->getParent();
2533 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2534 mCurrentState.layersSortedByZ.remove(layer);
2535
Robert Carr136e2f62017-02-08 17:54:29 -08002536 // As a matter of normal operation, the LayerCleaner will produce a second
2537 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2538 // so we will succeed in promoting it, but it's already been removed
2539 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2540 // otherwise something has gone wrong and we are leaking the layer.
2541 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2543 layer->getName().string(),
2544 (p != nullptr) ? p->getName().string() : "no-parent");
2545 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002546 } else if (index < 0) {
2547 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002548 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002549
2550 mLayersPendingRemoval.add(layer);
2551 mLayersRemoved = true;
2552 mNumLayers--;
2553 setTransactionFlags(eTransactionNeeded);
2554 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555}
2556
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002557uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002558 return android_atomic_release_load(&mTransactionFlags);
2559}
2560
Mathias Agopian3f844832013-08-07 21:24:32 -07002561uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2563}
2564
Mathias Agopian3f844832013-08-07 21:24:32 -07002565uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2567 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002568 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 }
2570 return old;
2571}
2572
Mathias Agopian8b33f032012-07-24 20:43:54 -07002573void SurfaceFlinger::setTransactionState(
2574 const Vector<ComposerState>& state,
2575 const Vector<DisplayState>& displays,
2576 uint32_t flags)
2577{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002578 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002579 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002580 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002581
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 if (flags & eAnimation) {
2583 // For window updates that are part of an animation we must wait for
2584 // previous animation "frames" to be handled.
2585 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002586 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002587 if (CC_UNLIKELY(err != NO_ERROR)) {
2588 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002589 // caller after a few seconds.
2590 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2591 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002592 mAnimTransactionPending = false;
2593 break;
2594 }
2595 }
2596 }
2597
Mathias Agopiane57f2922012-08-09 16:29:12 -07002598 size_t count = displays.size();
2599 for (size_t i=0 ; i<count ; i++) {
2600 const DisplayState& s(displays[i]);
2601 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002602 }
2603
Mathias Agopiane57f2922012-08-09 16:29:12 -07002604 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002605 for (size_t i=0 ; i<count ; i++) {
2606 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002607 // Here we need to check that the interface we're given is indeed
2608 // one of our own. A malicious client could give us a NULL
2609 // IInterface, or one of its own or even one of our own but a
2610 // different type. All these situations would cause us to crash.
2611 //
2612 // NOTE: it would be better to use RTTI as we could directly check
2613 // that we have a Client*. however, RTTI is disabled in Android.
2614 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002615 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002616 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002617 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002618 sp<Client> client( static_cast<Client *>(s.client.get()) );
2619 transactionFlags |= setClientStateLocked(client, s.state);
2620 }
2621 }
2622 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002623 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002624
Robert Carr2a7dbb42016-05-24 11:41:28 -07002625 // If a synchronous transaction is explicitly requested without any changes,
2626 // force a transaction anyway. This can be used as a flush mechanism for
2627 // previous async transactions.
2628 if (transactionFlags == 0 && (flags & eSynchronous)) {
2629 transactionFlags = eTransactionNeeded;
2630 }
2631
Mathias Agopian386aa982011-11-07 21:58:03 -08002632 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002633 if (mInterceptor.isEnabled()) {
2634 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2635 }
Irvel468051e2016-06-13 16:44:44 -07002636
Mathias Agopian386aa982011-11-07 21:58:03 -08002637 // this triggers the transaction
2638 setTransactionFlags(transactionFlags);
2639
2640 // if this is a synchronous transaction, wait for it to take effect
2641 // before returning.
2642 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002643 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002644 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002645 if (flags & eAnimation) {
2646 mAnimTransactionPending = true;
2647 }
2648 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002649 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2650 if (CC_UNLIKELY(err != NO_ERROR)) {
2651 // just in case something goes wrong in SF, return to the
2652 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002653 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2654 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002655 break;
2656 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 }
2659}
2660
Mathias Agopiane57f2922012-08-09 16:29:12 -07002661uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2662{
Jesse Hall9a143922012-10-04 16:29:19 -07002663 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2664 if (dpyIdx < 0)
2665 return 0;
2666
Mathias Agopiane57f2922012-08-09 16:29:12 -07002667 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002668 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002669 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002670 const uint32_t what = s.what;
2671 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002672 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002673 disp.surface = s.surface;
2674 flags |= eDisplayTransactionNeeded;
2675 }
2676 }
2677 if (what & DisplayState::eLayerStackChanged) {
2678 if (disp.layerStack != s.layerStack) {
2679 disp.layerStack = s.layerStack;
2680 flags |= eDisplayTransactionNeeded;
2681 }
2682 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002683 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002684 if (disp.orientation != s.orientation) {
2685 disp.orientation = s.orientation;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 if (disp.frame != s.frame) {
2689 disp.frame = s.frame;
2690 flags |= eDisplayTransactionNeeded;
2691 }
2692 if (disp.viewport != s.viewport) {
2693 disp.viewport = s.viewport;
2694 flags |= eDisplayTransactionNeeded;
2695 }
2696 }
Michael Lentine47e45402014-07-18 15:34:25 -07002697 if (what & DisplayState::eDisplaySizeChanged) {
2698 if (disp.width != s.width) {
2699 disp.width = s.width;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 if (disp.height != s.height) {
2703 disp.height = s.height;
2704 flags |= eDisplayTransactionNeeded;
2705 }
2706 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002707 }
2708 return flags;
2709}
2710
2711uint32_t SurfaceFlinger::setClientStateLocked(
2712 const sp<Client>& client,
2713 const layer_state_t& s)
2714{
2715 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002716 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002717 if (layer != 0) {
2718 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002719 bool geometryAppliesWithResize =
2720 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002721 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002722 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002723 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002724 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002725 }
2726 if (what & layer_state_t::eLayerChanged) {
2727 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002728 const auto& p = layer->getParent();
2729 if (p == nullptr) {
2730 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2731 if (layer->setLayer(s.z) && idx >= 0) {
2732 mCurrentState.layersSortedByZ.removeAt(idx);
2733 mCurrentState.layersSortedByZ.add(layer);
2734 // we need traversal (state changed)
2735 // AND transaction (list changed)
2736 flags |= eTransactionNeeded|eTraversalNeeded;
2737 }
2738 } else {
2739 if (p->setChildLayer(layer, s.z)) {
2740 flags |= eTransactionNeeded|eTraversalNeeded;
2741 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002742 }
2743 }
2744 if (what & layer_state_t::eSizeChanged) {
2745 if (layer->setSize(s.w, s.h)) {
2746 flags |= eTraversalNeeded;
2747 }
2748 }
2749 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002751 flags |= eTraversalNeeded;
2752 }
2753 if (what & layer_state_t::eMatrixChanged) {
2754 if (layer->setMatrix(s.matrix))
2755 flags |= eTraversalNeeded;
2756 }
2757 if (what & layer_state_t::eTransparentRegionChanged) {
2758 if (layer->setTransparentRegionHint(s.transparentRegion))
2759 flags |= eTraversalNeeded;
2760 }
Dan Stoza23116082015-06-18 14:58:39 -07002761 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002762 if (layer->setFlags(s.flags, s.mask))
2763 flags |= eTraversalNeeded;
2764 }
2765 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002766 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002767 flags |= eTraversalNeeded;
2768 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002769 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002770 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002771 flags |= eTraversalNeeded;
2772 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002774 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 // We only allow setting layer stacks for top level layers,
2776 // everything else inherits layer stack from its parent.
2777 if (layer->hasParent()) {
2778 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2779 layer->getName().string());
2780 } else if (idx < 0) {
2781 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2782 "that also does not appear in the top level layer list. Something"
2783 " has gone wrong.", layer->getName().string());
2784 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002785 mCurrentState.layersSortedByZ.removeAt(idx);
2786 mCurrentState.layersSortedByZ.add(layer);
2787 // we need traversal (state changed)
2788 // AND transaction (list changed)
2789 flags |= eTransactionNeeded|eTraversalNeeded;
2790 }
2791 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002792 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002793 if (s.barrierHandle != nullptr) {
2794 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2795 } else if (s.barrierGbp != nullptr) {
2796 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2797 if (authenticateSurfaceTextureLocked(gbp)) {
2798 const auto& otherLayer =
2799 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2800 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2801 } else {
2802 ALOGE("Attempt to defer transaction to to an"
2803 " unrecognized GraphicBufferProducer");
2804 }
2805 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002806 // We don't trigger a traversal here because if no other state is
2807 // changed, we don't want this to cause any more work
2808 }
Robert Carr1db73f62016-12-21 12:58:51 -08002809 if (what & layer_state_t::eReparentChildren) {
2810 if (layer->reparentChildren(s.reparentHandle)) {
2811 flags |= eTransactionNeeded|eTraversalNeeded;
2812 }
2813 }
Robert Carr9524cb32017-02-13 11:32:32 -08002814 if (what & layer_state_t::eDetachChildren) {
2815 layer->detachChildren();
2816 }
Robert Carrc3574f72016-03-24 12:19:32 -07002817 if (what & layer_state_t::eOverrideScalingModeChanged) {
2818 layer->setOverrideScalingMode(s.overrideScalingMode);
2819 // We don't trigger a traversal here because if no other state is
2820 // changed, we don't want this to cause any more work
2821 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002822 }
2823 return flags;
2824}
2825
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002826status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002827 const String8& name,
2828 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002829 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002830 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2831 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002833 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002834 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002835 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002836 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002837 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002838
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002839 status_t result = NO_ERROR;
2840
2841 sp<Layer> layer;
2842
Mathias Agopian3165cc22012-08-08 19:42:09 -07002843 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2844 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002845 result = createNormalLayer(client,
2846 name, w, h, flags, format,
2847 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002849 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002850 result = createDimLayer(client,
2851 name, w, h, flags,
2852 handle, gbp, &layer);
2853 break;
2854 default:
2855 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 break;
2857 }
2858
Dan Stoza7d89d062015-04-30 13:29:25 -07002859 if (result != NO_ERROR) {
2860 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002862
Albert Chaulk479c60c2017-01-27 14:21:34 -05002863 layer->setInfo(windowType, ownerUid);
2864
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002866 if (result != NO_ERROR) {
2867 return result;
2868 }
Irvelffc9efc2016-07-27 15:16:37 -07002869 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002870
2871 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002872 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002875status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2876 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2877 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878{
2879 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002880 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 case PIXEL_FORMAT_TRANSPARENT:
2882 case PIXEL_FORMAT_TRANSLUCENT:
2883 format = PIXEL_FORMAT_RGBA_8888;
2884 break;
2885 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002886 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 break;
2888 }
2889
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002890 *outLayer = new Layer(this, client, name, w, h, flags);
2891 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2892 if (err == NO_ERROR) {
2893 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002894 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002896
2897 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2898 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899}
2900
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002901status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2902 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2903 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002905 *outLayer = new LayerDim(this, client, name, w, h, flags);
2906 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002907 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002908 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002909}
2910
Mathias Agopianac9fa422013-02-11 16:40:36 -08002911status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912{
Robert Carr9524cb32017-02-13 11:32:32 -08002913 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002914 status_t err = NO_ERROR;
2915 sp<Layer> l(client->getLayerUser(handle));
2916 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002917 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002918 err = removeLayer(l);
2919 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2920 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002921 }
2922 return err;
2923}
2924
Mathias Agopian13127d82013-03-05 17:47:11 -08002925status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002926{
Mathias Agopian67106042013-03-14 19:18:13 -07002927 // called by ~LayerCleaner() when all references to the IBinder (handle)
2928 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002929 sp<Layer> l = layer.promote();
2930 if (l == nullptr) {
2931 // The layer has already been removed, carry on
2932 return NO_ERROR;
2933 } if (l->getParent() != nullptr) {
2934 // If we have a parent, then we can continue to live as long as it does.
2935 return NO_ERROR;
2936 }
2937 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938}
2939
Mathias Agopianb60314a2012-04-10 22:09:54 -07002940// ---------------------------------------------------------------------------
2941
Andy McFadden13a082e2012-08-24 10:16:42 -07002942void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002943 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002944 Vector<ComposerState> state;
2945 Vector<DisplayState> displays;
2946 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002947 d.what = DisplayState::eDisplayProjectionChanged |
2948 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002949 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002950 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002951 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002952 d.frame.makeInvalid();
2953 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002954 d.width = 0;
2955 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002956 displays.add(d);
2957 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002958 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002959
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2961 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002962 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002963
Brian Andersond0010582017-03-07 13:20:31 -08002964 // Use phase of 0 since phase is not known.
2965 // Use latency of 0, which will snap to the ideal latency.
2966 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07002967}
2968
2969void SurfaceFlinger::initializeDisplays() {
2970 class MessageScreenInitialized : public MessageBase {
2971 SurfaceFlinger* flinger;
2972 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002973 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002974 virtual bool handler() {
2975 flinger->onInitializeDisplays();
2976 return true;
2977 }
2978 };
2979 sp<MessageBase> msg = new MessageScreenInitialized(this);
2980 postMessageAsync(msg); // we may be called from main thread, use async message
2981}
2982
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002983void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2984 int mode) {
2985 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2986 this);
2987 int32_t type = hw->getDisplayType();
2988 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002989
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002990 if (mode == currentMode) {
2991 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002992 return;
2993 }
2994
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002995 hw->setPowerMode(mode);
2996 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2997 ALOGW("Trying to set power mode for virtual display");
2998 return;
2999 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003000
Irvelffc9efc2016-07-27 15:16:37 -07003001 if (mInterceptor.isEnabled()) {
3002 Mutex::Autolock _l(mStateLock);
3003 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3004 if (idx < 0) {
3005 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3006 return;
3007 }
3008 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3009 }
3010
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003011 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003012 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003013 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003014 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3015 // FIXME: eventthread only knows about the main display right now
3016 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003017 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003020 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003021 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003022 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003023
3024 struct sched_param param = {0};
3025 param.sched_priority = 1;
3026 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3027 ALOGW("Couldn't set SCHED_FIFO on display on");
3028 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003030 // Turn off the display
3031 struct sched_param param = {0};
3032 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3033 ALOGW("Couldn't set SCHED_OTHER on display off");
3034 }
3035
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003036 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003037 disableHardwareVsync(true); // also cancels any in-progress resync
3038
Mathias Agopiancde87a32012-09-13 14:09:01 -07003039 // FIXME: eventthread only knows about the main display right now
3040 mEventThread->onScreenReleased();
3041 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003042
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 getHwComposer().setPowerMode(type, mode);
3044 mVisibleRegionsDirty = true;
3045 // from this point on, SF will stop drawing on this display
3046 } else {
3047 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003048 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003049}
3050
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3052 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003053 SurfaceFlinger& mFlinger;
3054 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003055 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003057 MessageSetPowerMode(SurfaceFlinger& flinger,
3058 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3059 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003060 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003061 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003062 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003063 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003064 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003065 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003066 ALOGW("Attempt to set power mode = %d for virtual display",
3067 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003068 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003069 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003070 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003071 return true;
3072 }
3073 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003075 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003076}
3077
3078// ---------------------------------------------------------------------------
3079
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3081{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003083
Mathias Agopianbd115332013-04-18 16:41:04 -07003084 IPCThreadState* ipc = IPCThreadState::self();
3085 const int pid = ipc->getCallingPid();
3086 const int uid = ipc->getCallingUid();
3087 if ((uid != AID_SHELL) &&
3088 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003089 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003090 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003092 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003093 // (this would indicate SF is stuck, but we want to be able to
3094 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003095 status_t err = mStateLock.timedLock(s2ns(1));
3096 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003097 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003098 result.appendFormat(
3099 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3100 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003101 }
3102
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003103 bool dumpAll = true;
3104 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003105 size_t numArgs = args.size();
3106 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003107 if ((index < numArgs) &&
3108 (args[index] == String16("--list"))) {
3109 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003111 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112 }
3113
3114 if ((index < numArgs) &&
3115 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003116 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003117 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003118 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003119 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--latency-clear"))) {
3123 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003124 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003125 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003126 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003127
3128 if ((index < numArgs) &&
3129 (args[index] == String16("--dispsync"))) {
3130 index++;
3131 mPrimaryDispSync.dump(result);
3132 dumpAll = false;
3133 }
Dan Stozab90cf072015-03-05 11:05:59 -08003134
3135 if ((index < numArgs) &&
3136 (args[index] == String16("--static-screen"))) {
3137 index++;
3138 dumpStaticScreenStats(result);
3139 dumpAll = false;
3140 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003141
3142 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003143 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003144 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003145 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003146 dumpAll = false;
3147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003151 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003152 }
3153
Mathias Agopian9795c422009-08-26 16:36:26 -07003154 if (locked) {
3155 mStateLock.unlock();
3156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 write(fd, result.string(), result.size());
3159 return NO_ERROR;
3160}
3161
Dan Stozac7014012014-02-14 15:03:43 -08003162void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3163 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003164{
Robert Carr2047fae2016-11-28 14:09:09 -08003165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003166 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003167 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003168}
3169
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003171 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003172{
3173 String8 name;
3174 if (index < args.size()) {
3175 name = String8(args[index]);
3176 index++;
3177 }
3178
Dan Stoza9e56aa02015-11-02 13:00:03 -08003179 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3180 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003181 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003182
3183 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003184 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003185 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003187 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003188 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003189 }
Robert Carr2047fae2016-11-28 14:09:09 -08003190 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003191 }
3192}
3193
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003194void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003195 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003196{
3197 String8 name;
3198 if (index < args.size()) {
3199 name = String8(args[index]);
3200 index++;
3201 }
3202
Robert Carr2047fae2016-11-28 14:09:09 -08003203 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003204 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003205 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003206 }
Robert Carr2047fae2016-11-28 14:09:09 -08003207 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003208
Svetoslavd85084b2014-03-20 10:28:31 -07003209 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003210}
3211
Jamie Gennis6547ff42013-07-16 20:12:42 -07003212// This should only be called from the main thread. Otherwise it would need
3213// the lock and should use mCurrentState rather than mDrawingState.
3214void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003215 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003216 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003218
3219 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3220}
3221
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003222void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003223{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003224 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003225 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3226
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003227 if (isLayerTripleBufferingDisabled())
3228 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003229
3230 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003231 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003232 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003233 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003234 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3235 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003236 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003237}
3238
Dan Stozab90cf072015-03-05 11:05:59 -08003239void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3240{
3241 result.appendFormat("Static screen stats:\n");
3242 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3243 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3244 float percent = 100.0f *
3245 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3246 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3247 b + 1, bucketTimeSec, percent);
3248 }
3249 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3250 float percent = 100.0f *
3251 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3252 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3253 NUM_BUCKETS - 1, bucketTimeSec, percent);
3254}
3255
Dan Stozae77c7662016-05-13 11:37:28 -07003256void SurfaceFlinger::recordBufferingStats(const char* layerName,
3257 std::vector<OccupancyTracker::Segment>&& history) {
3258 Mutex::Autolock lock(mBufferingStatsMutex);
3259 auto& stats = mBufferingStats[layerName];
3260 for (const auto& segment : history) {
3261 if (!segment.usedThirdBuffer) {
3262 stats.twoBufferTime += segment.totalTime;
3263 }
3264 if (segment.occupancyAverage < 1.0f) {
3265 stats.doubleBufferedTime += segment.totalTime;
3266 } else if (segment.occupancyAverage < 2.0f) {
3267 stats.tripleBufferedTime += segment.totalTime;
3268 }
3269 ++stats.numSegments;
3270 stats.totalTime += segment.totalTime;
3271 }
3272}
3273
Brian Andersond6927fb2016-07-23 23:37:30 -07003274void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3275 result.appendFormat("Layer frame timestamps:\n");
3276
3277 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3278 const size_t count = currentLayers.size();
3279 for (size_t i=0 ; i<count ; i++) {
3280 currentLayers[i]->dumpFrameEvents(result);
3281 }
3282}
3283
Dan Stozae77c7662016-05-13 11:37:28 -07003284void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3285 result.append("Buffering stats:\n");
3286 result.append(" [Layer name] <Active time> <Two buffer> "
3287 "<Double buffered> <Triple buffered>\n");
3288 Mutex::Autolock lock(mBufferingStatsMutex);
3289 typedef std::tuple<std::string, float, float, float> BufferTuple;
3290 std::map<float, BufferTuple, std::greater<float>> sorted;
3291 for (const auto& statsPair : mBufferingStats) {
3292 const char* name = statsPair.first.c_str();
3293 const BufferingStats& stats = statsPair.second;
3294 if (stats.numSegments == 0) {
3295 continue;
3296 }
3297 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3298 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3299 stats.totalTime;
3300 float doubleBufferRatio = static_cast<float>(
3301 stats.doubleBufferedTime) / stats.totalTime;
3302 float tripleBufferRatio = static_cast<float>(
3303 stats.tripleBufferedTime) / stats.totalTime;
3304 sorted.insert({activeTime, {name, twoBufferRatio,
3305 doubleBufferRatio, tripleBufferRatio}});
3306 }
3307 for (const auto& sortedPair : sorted) {
3308 float activeTime = sortedPair.first;
3309 const BufferTuple& values = sortedPair.second;
3310 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3311 std::get<0>(values).c_str(), activeTime,
3312 std::get<1>(values), std::get<2>(values),
3313 std::get<3>(values));
3314 }
3315 result.append("\n");
3316}
3317
3318
Mathias Agopian74d211a2013-04-22 16:55:35 +02003319void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3320 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003321{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003322 bool colorize = false;
3323 if (index < args.size()
3324 && (args[index] == String16("--color"))) {
3325 colorize = true;
3326 index++;
3327 }
3328
3329 Colorizer colorizer(colorize);
3330
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003331 // figure out if we're stuck somewhere
3332 const nsecs_t now = systemTime();
3333 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3334 const nsecs_t inTransaction(mDebugInTransaction);
3335 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3336 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3337
3338 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003339 * Dump library configuration.
3340 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003341
3342 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003343 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003344 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003345 appendSfConfigString(result);
3346 appendUiConfigString(result);
3347 appendGuiConfigString(result);
3348 result.append("\n");
3349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003350 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003351 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003352 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003353 result.append(SyncFeatures::getInstance().toString());
3354 result.append("\n");
3355
Dan Stoza9e56aa02015-11-02 13:00:03 -08003356 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3357
Andy McFadden41d67d72014-04-25 16:58:34 -07003358 colorizer.bold(result);
3359 result.append("DispSync configuration: ");
3360 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003361 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003362 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003364 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003365 result.append("\n");
3366
Dan Stozab90cf072015-03-05 11:05:59 -08003367 // Dump static screen stats
3368 result.append("\n");
3369 dumpStaticScreenStats(result);
3370 result.append("\n");
3371
Dan Stozae77c7662016-05-13 11:37:28 -07003372 dumpBufferingStats(result);
3373
Andy McFadden4803b742012-09-24 19:07:20 -07003374 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003375 * Dump the visible layer list
3376 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003377 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003378 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003379 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003380 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003382 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003383
3384 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003385 * Dump Display state
3386 */
3387
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003388 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003389 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003390 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003391 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3392 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003393 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003394 }
3395
3396 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003397 * Dump SurfaceFlinger global state
3398 */
3399
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003400 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003402 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403
Mathias Agopian888c8222012-08-04 21:10:38 -07003404 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003405 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003406
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003407 colorizer.bold(result);
3408 result.appendFormat("EGL implementation : %s\n",
3409 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3410 colorizer.reset(result);
3411 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003412 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003413
Mathias Agopian875d8e12013-06-07 15:35:48 -07003414 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003415
Mathias Agopian42977342012-08-05 00:40:46 -07003416 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3418 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420 " last eglSwapBuffers() time: %f us\n"
3421 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003422 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423 " refresh-rate : %f fps\n"
3424 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003425 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003426 " gpu_to_cpu_unsupported : %d\n"
3427 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428 mLastSwapBufferTime/1000.0,
3429 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003430 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003431 1e9 / activeConfig->getVsyncPeriod(),
3432 activeConfig->getDpiX(),
3433 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003434 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003435
Mathias Agopian74d211a2013-04-22 16:55:35 +02003436 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003437 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438
Mathias Agopian74d211a2013-04-22 16:55:35 +02003439 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003440 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003441
3442 /*
3443 * VSYNC state
3444 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003445 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003446 result.append("\n");
3447
3448 /*
3449 * HWC layer minidump
3450 */
3451 for (size_t d = 0; d < mDisplays.size(); d++) {
3452 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3453 int32_t hwcId = displayDevice->getHwcDisplayId();
3454 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3455 continue;
3456 }
3457
3458 result.appendFormat("Display %d HWC layers:\n", hwcId);
3459 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003460 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003461 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003462 });
Dan Stozae22aec72016-08-01 13:20:59 -07003463 result.append("\n");
3464 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465
3466 /*
3467 * Dump HWComposer state
3468 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003469 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003470 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003471 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003472 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003473 result.appendFormat(" h/w composer %s\n",
3474 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003475 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003476
3477 /*
3478 * Dump gralloc state
3479 */
3480 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3481 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003482}
3483
Mathias Agopian13127d82013-03-05 17:47:11 -08003484const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003485SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003486 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003487 wp<IBinder> dpy;
3488 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3489 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3490 dpy = mDisplays.keyAt(i);
3491 break;
3492 }
3493 }
3494 if (dpy == NULL) {
3495 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3496 // Just use the primary display so we have something to return
3497 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3498 }
3499 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003500}
3501
Keun young Park63f165f2012-08-31 10:53:36 -07003502bool SurfaceFlinger::startDdmConnection()
3503{
3504 void* libddmconnection_dso =
3505 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3506 if (!libddmconnection_dso) {
3507 return false;
3508 }
3509 void (*DdmConnection_start)(const char* name);
3510 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003511 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003512 if (!DdmConnection_start) {
3513 dlclose(libddmconnection_dso);
3514 return false;
3515 }
3516 (*DdmConnection_start)(getServiceName());
3517 return true;
3518}
3519
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003520status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 switch (code) {
3522 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003523 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003525 case CLEAR_ANIMATION_FRAME_STATS:
3526 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003527 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003528 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 {
3530 // codes that require permission check
3531 IPCThreadState* ipc = IPCThreadState::self();
3532 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003533 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003534 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003535 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003536 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003537 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003539 break;
3540 }
Robert Carr1db73f62016-12-21 12:58:51 -08003541 /*
3542 * Calling setTransactionState is safe, because you need to have been
3543 * granted a reference to Client* and Handle* to do anything with it.
3544 *
3545 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3546 */
3547 case SET_TRANSACTION_STATE:
3548 case CREATE_SCOPED_CONNECTION:
3549 {
3550 return OK;
3551 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003552 case CAPTURE_SCREEN:
3553 {
3554 // codes that require permission check
3555 IPCThreadState* ipc = IPCThreadState::self();
3556 const int pid = ipc->getCallingPid();
3557 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003558 if ((uid != AID_GRAPHICS) &&
3559 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003560 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003561 return PERMISSION_DENIED;
3562 }
3563 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564 }
3565 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003566 return OK;
3567}
3568
3569status_t SurfaceFlinger::onTransact(
3570 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3571{
3572 status_t credentialCheck = CheckTransactCodeCredentials(code);
3573 if (credentialCheck != OK) {
3574 return credentialCheck;
3575 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003576
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003577 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3578 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003579 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003580 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003581 IPCThreadState* ipc = IPCThreadState::self();
3582 const int pid = ipc->getCallingPid();
3583 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003584 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003585 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 return PERMISSION_DENIED;
3587 }
3588 int n;
3589 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003590 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003591 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 return NO_ERROR;
3593 case 1002: // SHOW_UPDATES
3594 n = data.readInt32();
3595 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003596 invalidateHwcGeometry();
3597 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003600 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003601 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003603 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003604 setTransactionFlags(
3605 eTransactionNeeded|
3606 eDisplayTransactionNeeded|
3607 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003608 return NO_ERROR;
3609 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003610 case 1006:{ // send empty update
3611 signalRefresh();
3612 return NO_ERROR;
3613 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003614 case 1008: // toggle use of hw composer
3615 n = data.readInt32();
3616 mDebugDisableHWC = n ? 1 : 0;
3617 invalidateHwcGeometry();
3618 repaintEverything();
3619 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003620 case 1009: // toggle use of transform hint
3621 n = data.readInt32();
3622 mDebugDisableTransformHint = n ? 1 : 0;
3623 invalidateHwcGeometry();
3624 repaintEverything();
3625 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003627 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 reply->writeInt32(0);
3629 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003630 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003631 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632 return NO_ERROR;
3633 case 1013: {
3634 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003635 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3636 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003637 return NO_ERROR;
3638 }
3639 case 1014: {
3640 // daltonize
3641 n = data.readInt32();
3642 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003643 case 1:
3644 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3645 break;
3646 case 2:
3647 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3648 break;
3649 case 3:
3650 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3651 break;
3652 default:
3653 mDaltonizer.setType(ColorBlindnessType::None);
3654 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003655 }
3656 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003657 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003658 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003659 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003660 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003661 invalidateHwcGeometry();
3662 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003663 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003664 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003665 case 1015: {
3666 // apply a color matrix
3667 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003668 if (n) {
3669 // color matrix is sent as mat3 matrix followed by vec3
3670 // offset, then packed into a mat4 where the last row is
3671 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003672 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003673 for (size_t j = 0; j < 4; j++) {
3674 mColorMatrix[i][j] = data.readFloat();
3675 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003676 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003677 } else {
3678 mColorMatrix = mat4();
3679 }
3680 invalidateHwcGeometry();
3681 repaintEverything();
3682 return NO_ERROR;
3683 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003684 // This is an experimental interface
3685 // Needs to be shifted to proper binder interface when we productize
3686 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003687 n = data.readInt32();
3688 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003689 return NO_ERROR;
3690 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003691 case 1017: {
3692 n = data.readInt32();
3693 mForceFullDamage = static_cast<bool>(n);
3694 return NO_ERROR;
3695 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003696 case 1018: { // Modify Choreographer's phase offset
3697 n = data.readInt32();
3698 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3699 return NO_ERROR;
3700 }
3701 case 1019: { // Modify SurfaceFlinger's phase offset
3702 n = data.readInt32();
3703 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3704 return NO_ERROR;
3705 }
Irvel468051e2016-06-13 16:44:44 -07003706 case 1020: { // Layer updates interceptor
3707 n = data.readInt32();
3708 if (n) {
3709 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003710 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003711 }
3712 else{
3713 ALOGV("Interceptor disabled");
3714 mInterceptor.disable();
3715 }
3716 return NO_ERROR;
3717 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003718 case 1021: { // Disable HWC virtual displays
3719 n = data.readInt32();
3720 mUseHwcVirtualDisplays = !n;
3721 return NO_ERROR;
3722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
3724 }
3725 return err;
3726}
3727
Mathias Agopian53331da2011-08-22 21:44:41 -07003728void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003729 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003730 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003731}
3732
Mathias Agopian59119e62010-10-11 12:37:43 -07003733// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003734// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003735// ---------------------------------------------------------------------------
3736
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003737/* The code below is here to handle b/8734824
3738 *
3739 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003740 * from the surfaceflinger thread to the calling binder thread, where they
3741 * are executed. This allows the calling thread in the calling process to be
3742 * reused and not depend on having "enough" binder threads to handle the
3743 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003744 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003745class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003746 /* Parts of GraphicProducerWrapper are run on two different threads,
3747 * communicating by sending messages via Looper but also by shared member
3748 * data. Coherence maintenance is subtle and in places implicit (ugh).
3749 *
3750 * Don't rely on Looper's sendMessage/handleMessage providing
3751 * release/acquire semantics for any data not actually in the Message.
3752 * Data going from surfaceflinger to binder threads needs to be
3753 * synchronized explicitly.
3754 *
3755 * Barrier open/wait do provide release/acquire semantics. This provides
3756 * implicit synchronization for data coming back from binder to
3757 * surfaceflinger threads.
3758 */
3759
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003760 sp<IGraphicBufferProducer> impl;
3761 sp<Looper> looper;
3762 status_t result;
3763 bool exitPending;
3764 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003765 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003766 uint32_t code;
3767 Parcel const* data;
3768 Parcel* reply;
3769
3770 enum {
3771 MSG_API_CALL,
3772 MSG_EXIT
3773 };
3774
3775 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003776 * Called on surfaceflinger thread. This is called by our "fake"
3777 * BpGraphicBufferProducer. We package the data and reply Parcel and
3778 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003779 */
3780 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003781 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003782 this->code = code;
3783 this->data = &data;
3784 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003785 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003786 // if we've exited, we run the message synchronously right here.
3787 // note (JH): as far as I can tell from looking at the code, this
3788 // never actually happens. if it does, i'm not sure if it happens
3789 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003790 handleMessage(Message(MSG_API_CALL));
3791 } else {
3792 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003793 // Prevent stores to this->{code, data, reply} from being
3794 // reordered later than the construction of Message.
3795 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003796 looper->sendMessage(this, Message(MSG_API_CALL));
3797 barrier.wait();
3798 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003799 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003800 }
3801
3802 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003803 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003804 * call the real BpGraphicBufferProducer.
3805 */
3806 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003807 int what = message.what;
3808 // Prevent reads below from happening before the read from Message
3809 atomic_thread_fence(memory_order_acquire);
3810 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003811 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003813 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 exitRequested = true;
3815 }
3816 }
3817
3818public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003819 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003820 : impl(impl),
3821 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003822 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003823 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003824 exitRequested(false),
3825 code(0),
3826 data(NULL),
3827 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003828 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829
Jesse Hallb154c422014-07-13 12:47:02 -07003830 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003831 status_t waitForResponse() {
3832 do {
3833 looper->pollOnce(-1);
3834 } while (!exitRequested);
3835 return result;
3836 }
3837
Jesse Hallb154c422014-07-13 12:47:02 -07003838 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003839 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003840 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003841 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003842 // Ensure this->result is visible to the binder thread before it
3843 // handles the message.
3844 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003845 looper->sendMessage(this, Message(MSG_EXIT));
3846 }
3847};
3848
3849
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003850status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3851 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003852 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003853 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003854 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003855
3856 if (CC_UNLIKELY(display == 0))
3857 return BAD_VALUE;
3858
3859 if (CC_UNLIKELY(producer == 0))
3860 return BAD_VALUE;
3861
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003862 // if we have secure windows on this display, never allow the screen capture
3863 // unless the producer interface is local (i.e.: we can take a screenshot for
3864 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003865 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003866
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003867 // Convert to surfaceflinger's internal rotation type.
3868 Transform::orientation_flags rotationFlags;
3869 switch (rotation) {
3870 case ISurfaceComposer::eRotateNone:
3871 rotationFlags = Transform::ROT_0;
3872 break;
3873 case ISurfaceComposer::eRotate90:
3874 rotationFlags = Transform::ROT_90;
3875 break;
3876 case ISurfaceComposer::eRotate180:
3877 rotationFlags = Transform::ROT_180;
3878 break;
3879 case ISurfaceComposer::eRotate270:
3880 rotationFlags = Transform::ROT_270;
3881 break;
3882 default:
3883 rotationFlags = Transform::ROT_0;
3884 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3885 break;
3886 }
3887
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003888 class MessageCaptureScreen : public MessageBase {
3889 SurfaceFlinger* flinger;
3890 sp<IBinder> display;
3891 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003892 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003893 uint32_t reqWidth, reqHeight;
3894 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003895 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003896 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003898 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003899 public:
3900 MessageCaptureScreen(SurfaceFlinger* flinger,
3901 const sp<IBinder>& display,
3902 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003903 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003904 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003905 bool useIdentityTransform,
3906 Transform::orientation_flags rotation,
3907 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003908 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003909 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003910 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003911 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003912 rotation(rotation), result(PERMISSION_DENIED),
3913 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003914 {
3915 }
3916 status_t getResult() const {
3917 return result;
3918 }
3919 virtual bool handler() {
3920 Mutex::Autolock _l(flinger->mStateLock);
3921 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003922 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003923 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003924 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003925 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 return true;
3927 }
3928 };
3929
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003930 // this creates a "fake" BBinder which will serve as a "fake" remote
3931 // binder to receive the marshaled calls and forward them to the
3932 // real remote (a BpGraphicBufferProducer)
3933 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3934
3935 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3936 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003937 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003939 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003940 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003941
3942 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003943 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003944 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003945 }
3946 return res;
3947}
3948
Mathias Agopian180f10d2013-04-10 22:55:41 -07003949
3950void SurfaceFlinger::renderScreenImplLocked(
3951 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003952 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003953 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003954 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003955{
3956 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003957 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003958
3959 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003960 const int32_t hw_w = hw->getWidth();
3961 const int32_t hw_h = hw->getHeight();
3962 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003963 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003964
Dan Stozac1879002014-05-22 15:59:05 -07003965 // if a default or invalid sourceCrop is passed in, set reasonable values
3966 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3967 !sourceCrop.isValid()) {
3968 sourceCrop.setLeftTop(Point(0, 0));
3969 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3970 }
3971
3972 // ensure that sourceCrop is inside screen
3973 if (sourceCrop.left < 0) {
3974 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3975 }
Dan Stozabe31f442014-06-11 11:20:54 -07003976 if (sourceCrop.right > hw_w) {
3977 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003978 }
3979 if (sourceCrop.top < 0) {
3980 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3981 }
Dan Stozabe31f442014-06-11 11:20:54 -07003982 if (sourceCrop.bottom > hw_h) {
3983 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003984 }
3985
Mathias Agopian180f10d2013-04-10 22:55:41 -07003986 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003987 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003988
3989 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003990 engine.setViewportAndProjection(
3991 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003992 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003993
3994 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003995 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003996
Robert Carr1f0a16a2016-10-24 16:27:39 -07003997 // We loop through the first level of layers without traversing,
3998 // as we need to interpret min/max layer Z in the top level Z space.
3999 for (const auto& layer : mDrawingState.layersSortedByZ) {
4000 if (layer->getLayerStack() != hw->getLayerStack()) {
4001 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004002 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004003 const Layer::State& state(layer->getDrawingState());
4004 if (state.z < minLayerZ || state.z > maxLayerZ) {
4005 continue;
4006 }
4007 layer->traverseInZOrder([&](Layer* layer) {
4008 if (!layer->isVisible()) {
4009 return;
4010 }
4011 if (filtering) layer->setFiltering(true);
4012 layer->draw(hw, useIdentityTransform);
4013 if (filtering) layer->setFiltering(false);
4014 });
4015 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004016
Mathias Agopian931bda12013-08-28 18:11:46 -07004017 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004018}
4019
4020
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021status_t SurfaceFlinger::captureScreenImplLocked(
4022 const sp<const DisplayDevice>& hw,
4023 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004024 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004025 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004026 bool useIdentityTransform, Transform::orientation_flags rotation,
4027 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004028{
4029 ATRACE_CALL();
4030
Mathias Agopian180f10d2013-04-10 22:55:41 -07004031 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004032 uint32_t hw_w = hw->getWidth();
4033 uint32_t hw_h = hw->getHeight();
4034
4035 if (rotation & Transform::ROT_90) {
4036 std::swap(hw_w, hw_h);
4037 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004038
Mathias Agopian180f10d2013-04-10 22:55:41 -07004039 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4040 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4041 reqWidth, reqHeight, hw_w, hw_h);
4042 return BAD_VALUE;
4043 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004044
Mathias Agopian180f10d2013-04-10 22:55:41 -07004045 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4046 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4047
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004048 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004049 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004050 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004051 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4052 (state.z < minLayerZ || state.z > maxLayerZ)) {
4053 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004054 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004055 layer->traverseInZOrder([&](Layer *layer) {
4056 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4057 layer->isSecure());
4058 });
4059 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004060
4061 if (!isLocalScreenshot && secureLayerIsVisible) {
4062 ALOGW("FB is protected: PERMISSION_DENIED");
4063 return PERMISSION_DENIED;
4064 }
4065
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004066 // create a surface (because we're a producer, and we need to
4067 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004068 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004069
4070 // Put the screenshot Surface into async mode so that
4071 // Layer::headFenceHasSignaled will always return true and we'll latch the
4072 // first buffer regardless of whether or not its acquire fence has
4073 // signaled. This is needed to avoid a race condition in the rotation
4074 // animation. See b/30209608
4075 sur->setAsyncMode(true);
4076
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004077 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004078
Michael Lentine5a16a622015-05-21 13:48:24 -07004079 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4080 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004081 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4082 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004083
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004084 int err = 0;
4085 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004086 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004087 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4088 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004089
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004090 if (err == NO_ERROR) {
4091 ANativeWindowBuffer* buffer;
4092 /* TODO: Once we have the sync framework everywhere this can use
4093 * server-side waits on the fence that dequeueBuffer returns.
4094 */
4095 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4096 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004097 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004098 // create an EGLImage from the buffer so we can later
4099 // turn it into a texture
4100 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4101 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4102 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004103 // this binds the given EGLImage as a framebuffer for the
4104 // duration of this scope.
4105 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4106 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004107 // this will in fact render into our dequeued buffer
4108 // via an FBO, which means we didn't have to create
4109 // an EGLSurface and therefore we're not
4110 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004111 renderScreenImplLocked(
4112 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4113 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004114
Riley Andrews86639902014-08-15 12:27:24 -07004115 // Attempt to create a sync khr object that can produce a sync point. If that
4116 // isn't available, create a non-dupable sync object in the fallback path and
4117 // wait on it directly.
4118 EGLSyncKHR sync;
4119 if (!DEBUG_SCREENSHOTS) {
4120 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004121 // native fence fd will not be populated until flush() is done.
4122 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004123 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004124 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004125 }
Riley Andrews86639902014-08-15 12:27:24 -07004126 if (sync != EGL_NO_SYNC_KHR) {
4127 // get the sync fd
4128 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4129 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4130 ALOGW("captureScreen: failed to dup sync khr object");
4131 syncFd = -1;
4132 }
4133 eglDestroySyncKHR(mEGLDisplay, sync);
4134 } else {
4135 // fallback path
4136 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4137 if (sync != EGL_NO_SYNC_KHR) {
4138 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4139 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4140 EGLint eglErr = eglGetError();
4141 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4142 ALOGW("captureScreen: fence wait timed out");
4143 } else {
4144 ALOGW_IF(eglErr != EGL_SUCCESS,
4145 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4146 }
4147 eglDestroySyncKHR(mEGLDisplay, sync);
4148 } else {
4149 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4150 }
4151 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004152 if (DEBUG_SCREENSHOTS) {
4153 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4154 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4155 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4156 hw, minLayerZ, maxLayerZ);
4157 delete [] pixels;
4158 }
4159
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004160 } else {
4161 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4162 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004163 window->cancelBuffer(window, buffer, syncFd);
4164 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004165 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004166 // destroy our image
4167 eglDestroyImageKHR(mEGLDisplay, image);
4168 } else {
4169 result = BAD_VALUE;
4170 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004171 if (buffer) {
4172 // queueBuffer takes ownership of syncFd
4173 result = window->queueBuffer(window, buffer, syncFd);
4174 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004175 }
4176 } else {
4177 result = BAD_VALUE;
4178 }
4179 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4180 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004181
Mathias Agopian74c40c02010-09-29 13:02:36 -07004182 return result;
4183}
4184
Mathias Agopiand5556842013-09-19 17:08:37 -07004185void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004186 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004187 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004188 for (size_t y=0 ; y<h ; y++) {
4189 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4190 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004191 if (p[x] != 0xFF000000) return;
4192 }
4193 }
4194 ALOGE("*** we just took a black screenshot ***\n"
4195 "requested minz=%d, maxz=%d, layerStack=%d",
4196 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004197
Robert Carr2047fae2016-11-28 14:09:09 -08004198 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004199 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004200 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4202 state.z <= maxLayerZ) {
4203 layer->traverseInZOrder([&](Layer* layer) {
4204 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4205 layer->isVisible() ? '+' : '-',
4206 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004207 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004208 i++;
4209 });
4210 }
4211 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004212 }
4213}
4214
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004215// ---------------------------------------------------------------------------
4216
Robert Carr2047fae2016-11-28 14:09:09 -08004217void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4218 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004219}
4220
Robert Carr2047fae2016-11-28 14:09:09 -08004221void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4222 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004223}
4224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004225}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004226
4227
4228#if defined(__gl_h_)
4229#error "don't include gl/gl.h in this file"
4230#endif
4231
4232#if defined(__gl2_h_)
4233#error "don't include gl2/gl2.h in this file"
4234#endif