blob: 33f435ee4e06c7c7a3e81a41d17177ffa54963af [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Mathias Agopianc666cae2012-07-25 18:56:13 -070040#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070041#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070071#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080073#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080075#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Jaesoo Lee43518572017-01-23 19:03:16 +0900101using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900102using namespace android::hardware::configstore::V1_0;
103
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104// This is the phase offset in nanoseconds of the software vsync event
105// relative to the vsync event reported by HWComposer. The software vsync
106// event is when SurfaceFlinger and Choreographer-based applications run each
107// frame.
108//
109// This phase offset allows adjustment of the minimum latency from application
110// wake-up (by Choregographer) time to the time at which the resulting window
111// image is displayed. This value may be either positive (after the HW vsync)
112// or negative (before the HW vsync). Setting it to 0 will result in a
113// minimum latency of two vsync periods because the app and SurfaceFlinger
114// will run just after the HW vsync. Setting it to a positive number will
115// result in the minimum latency being:
116//
117// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
118//
119// Note that reducing this latency makes it more likely for the applications
120// to not have their window content image ready in time. When this happens
121// the latency will end up being an additional vsync period, and animations
122// will hiccup. Therefore, this latency should be tuned somewhat
123// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900124static int64_t vsyncPhaseOffsetNs = getInt64<
125 ISurfaceFlingerConfigs,
126 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700127
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700128// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800129static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131// ---------------------------------------------------------------------------
132
Mathias Agopian99b49842011-06-27 16:05:52 -0700133const String16 sHardwareTest("android.permission.HARDWARE_TEST");
134const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
135const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
136const String16 sDump("android.permission.DUMP");
137
138// ---------------------------------------------------------------------------
139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700141 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700143 mTransactionPending(false),
144 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700145 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700146 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700147 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800148 mHwc(nullptr),
149 mRealHwc(nullptr),
150 mVrHwc(nullptr),
151 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800155 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800156 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800157 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700159 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700160 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700161 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700162 mDebugInSwapBuffers(0),
163 mLastSwapBufferTime(0),
164 mDebugInTransaction(0),
165 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700166 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700167 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800168 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000169 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700170 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700171 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800172 mHasColorMatrix(false),
173 mHasPoweredOff(false),
174 mFrameBuckets(),
175 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700176 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800177 mNumLayers(0)
178#ifdef USE_HWC2
179 ,mEnterVrMode(false)
180#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181{
Steve Blocka19954a2012-01-04 20:05:49 +0000182 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183
184 // debugging stuff...
185 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800187 // TODO (urbanus): remove once b/35319396 is fixed.
188 property_get("ro.boot.vr", value, "0");
189 mVrModeSupported = atoi(value);
190
Mathias Agopianb4b17302013-03-20 18:36:41 -0700191 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700192 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 property_get("debug.sf.showupdates", value, "0");
195 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700197 property_get("debug.sf.ddms", value, "0");
198 mDebugDDMS = atoi(value);
199 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700200 if (!startDdmConnection()) {
201 // start failed, and DDMS debugging not enabled
202 mDebugDDMS = 0;
203 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700205 ALOGI_IF(mDebugRegion, "showupdates enabled");
206 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700207
208 property_get("debug.sf.disable_backpressure", value, "0");
209 mPropagateBackpressure = !atoi(value);
210 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700211
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800212 property_get("debug.sf.enable_hwc_vds", value, "0");
213 mUseHwcVirtualDisplays = atoi(value);
214 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800215
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800216 property_get("ro.sf.disable_triple_buffer", value, "1");
217 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800218 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219}
220
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800221void SurfaceFlinger::onFirstRef()
222{
223 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224}
225
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226SurfaceFlinger::~SurfaceFlinger()
227{
Mathias Agopiana4912602012-07-12 14:25:33 -0700228 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
229 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
230 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800231
232 if (mVrStateCallbacks.get()) {
233 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
234 defaultServiceManager()->checkService(String16("vrmanager")));
235 if (vrManagerService.get()) {
236 vrManagerService->unregisterListener(mVrStateCallbacks);
237 }
238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239}
240
Dan Stozac7014012014-02-14 15:03:43 -0800241void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242{
243 // the window manager died on us. prepare its eulogy.
244
Andy McFadden13a082e2012-08-24 10:16:42 -0700245 // restore initial conditions (default device unblank, etc)
246 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247
248 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700249 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250}
251
Robert Carr1db73f62016-12-21 12:58:51 -0800252static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700253 status_t err = client->initCheck();
254 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return nullptr;
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
261 return initClient(new Client(this));
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
265 const sp<IGraphicBufferProducer>& gbp) {
266 if (authenticateSurfaceTexture(gbp) == false) {
267 return nullptr;
268 }
269 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
270 if (layer == nullptr) {
271 return nullptr;
272 }
273
274 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700277sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
278 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279{
280 class DisplayToken : public BBinder {
281 sp<SurfaceFlinger> flinger;
282 virtual ~DisplayToken() {
283 // no more references, this display must be terminated
284 Mutex::Autolock _l(flinger->mStateLock);
285 flinger->mCurrentState.displays.removeItem(this);
286 flinger->setTransactionFlags(eDisplayTransactionNeeded);
287 }
288 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700289 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 : flinger(flinger) {
291 }
292 };
293
294 sp<BBinder> token = new DisplayToken(this);
295
296 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700297 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700298 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 return token;
302}
303
Jesse Hall6c913be2013-08-08 12:15:49 -0700304void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
305 Mutex::Autolock _l(mStateLock);
306
307 ssize_t idx = mCurrentState.displays.indexOfKey(display);
308 if (idx < 0) {
309 ALOGW("destroyDisplay: invalid display token");
310 return;
311 }
312
313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
314 if (!info.isVirtualDisplay()) {
315 ALOGE("destroyDisplay called for non-virtual display");
316 return;
317 }
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700319 mCurrentState.displays.removeItemsAt(idx);
320 setTransactionFlags(eDisplayTransactionNeeded);
321}
322
Jesse Hall692c7232012-11-08 15:41:56 -0800323void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800324 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 ALOGW_IF(mBuiltinDisplays[type],
326 "Overwriting display token for display type %d", type);
327 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800328 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700329 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700331 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800332}
333
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700335 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
337 return NULL;
338 }
Jesse Hall692c7232012-11-08 15:41:56 -0800339 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340}
341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342void SurfaceFlinger::bootFinished()
343{
Wei Wangb254fa32017-01-31 17:43:23 -0800344 if (mStartBootAnimThread->join() != NO_ERROR) {
345 ALOGE("Join StartBootAnimThread failed!");
346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 const nsecs_t now = systemTime();
348 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000349 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700350 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700351
352 // wait patiently for the window manager death
353 const String16 name("window");
354 sp<IBinder> window(defaultServiceManager()->getService(name));
355 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700356 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357 }
358
359 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700360 // formerly we would just kill the process, but we now ask it to exit so it
361 // can choose where to stop the animation.
362 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700363
364 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
365 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
366 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800367
368 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
369 defaultServiceManager()->checkService(String16("vrmanager")));
370 if (vrManagerService.get()) {
371 mVrStateCallbacks = new VrStateCallbacks(*this);
372 vrManagerService->registerListener(mVrStateCallbacks);
373 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800374}
375
Mathias Agopian3f844832013-08-07 21:24:32 -0700376void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700377 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 RenderEngine& engine;
379 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700381 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
382 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383 }
384 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 return true;
387 }
388 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390}
391
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700392class DispSyncSource : public VSyncSource, private DispSync::Callback {
393public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700394 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000395 const char* name) :
396 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700397 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700398 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
400 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700401 mDispSync(dispSync),
402 mCallbackMutex(),
403 mCallback(),
404 mVsyncMutex(),
405 mPhaseOffset(phaseOffset),
406 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700407
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700408 virtual ~DispSyncSource() {}
409
410 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700411 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000413 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 static_cast<DispSync::Callback*>(this));
415 if (err != NO_ERROR) {
416 ALOGE("error registering vsync callback: %s (%d)",
417 strerror(-err), err);
418 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700419 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 } else {
421 status_t err = mDispSync->removeEventListener(
422 static_cast<DispSync::Callback*>(this));
423 if (err != NO_ERROR) {
424 ALOGE("error unregistering vsync callback: %s (%d)",
425 strerror(-err), err);
426 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700427 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700429 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
431
432 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 mCallback = callback;
435 }
436
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 virtual void setPhaseOffset(nsecs_t phaseOffset) {
438 Mutex::Autolock lock(mVsyncMutex);
439
440 // Normalize phaseOffset to [0, period)
441 auto period = mDispSync->getPeriod();
442 phaseOffset %= period;
443 if (phaseOffset < 0) {
444 // If we're here, then phaseOffset is in (-period, 0). After this
445 // operation, it will be in (0, period)
446 phaseOffset += period;
447 }
448 mPhaseOffset = phaseOffset;
449
450 // If we're not enabled, we don't need to mess with the listeners
451 if (!mEnabled) {
452 return;
453 }
454
455 // Remove the listener with the old offset
456 status_t err = mDispSync->removeEventListener(
457 static_cast<DispSync::Callback*>(this));
458 if (err != NO_ERROR) {
459 ALOGE("error unregistering vsync callback: %s (%d)",
460 strerror(-err), err);
461 }
462
463 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000464 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700465 static_cast<DispSync::Callback*>(this));
466 if (err != NO_ERROR) {
467 ALOGE("error registering vsync callback: %s (%d)",
468 strerror(-err), err);
469 }
470 }
471
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472private:
473 virtual void onDispSyncEvent(nsecs_t when) {
474 sp<VSyncSource::Callback> callback;
475 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700476 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477 callback = mCallback;
478
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700479 if (mTraceVsync) {
480 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700481 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700482 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 }
484
485 if (callback != NULL) {
486 callback->onVSyncEvent(when);
487 }
488 }
489
Tim Murray4a4e4a22016-04-19 16:29:23 +0000490 const char* const mName;
491
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492 int mValue;
493
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700494 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 const String8 mVsyncOnLabel;
496 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700497
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499
500 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502
503 Mutex mVsyncMutex; // Protects the following
504 nsecs_t mPhaseOffset;
505 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506};
507
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700508class InjectVSyncSource : public VSyncSource {
509public:
510 InjectVSyncSource() {}
511
512 virtual ~InjectVSyncSource() {}
513
514 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
515 std::lock_guard<std::mutex> lock(mCallbackMutex);
516 mCallback = callback;
517 }
518
519 virtual void onInjectSyncEvent(nsecs_t when) {
520 std::lock_guard<std::mutex> lock(mCallbackMutex);
521 mCallback->onVSyncEvent(when);
522 }
523
524 virtual void setVSyncEnabled(bool) {}
525 virtual void setPhaseOffset(nsecs_t) {}
526
527private:
528 std::mutex mCallbackMutex; // Protects the following
529 sp<VSyncSource::Callback> mCallback;
530};
531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700533 ALOGI( "SurfaceFlinger's main thread ready to run. "
534 "Initializing graphics H/W...");
535
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900536 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
537
Dan Stoza9e56aa02015-11-02 13:00:03 -0800538 { // Autolock scope
539 Mutex::Autolock _l(mStateLock);
540
541 // initialize EGL for the default display
542 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
543 eglInitialize(mEGLDisplay, NULL, NULL);
544
545 // start the EventThread
546 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
547 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700548 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
550 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700551 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800552 mEventQueue.setEventThread(mSFEventThread);
553
Tim Murrayacff43d2016-07-29 13:57:24 -0700554 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700555 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700556 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700557 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
558 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
559 }
560
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 // Get a RenderEngine for the given display / config (can't fail)
562 mRenderEngine = RenderEngine::create(mEGLDisplay,
563 HAL_PIXEL_FORMAT_RGBA_8888);
564 }
565
566 // Drop the state lock while we initialize the hardware composer. We drop
567 // the lock because on creation, it will call back into SurfaceFlinger to
568 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800569 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode 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
Mathias Agopian875d8e12013-06-07 15:35:48 -0700576 // retrieve the EGL context that was selected/created
577 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700578
Mathias Agopianda27af92012-09-13 18:17:13 -0700579 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
580 "couldn't create EGLContext");
581
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582 // make the GLContext current so that we can create textures when creating
583 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700584 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
585
Jamie Gennisd1700752013-10-14 12:22:52 -0700586 mEventControlThread = new EventControlThread(this);
587 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
588
Mathias Agopian92a979a2012-08-02 18:32:23 -0700589 // initialize our drawing state
590 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700591
Andy McFadden13a082e2012-08-24 10:16:42 -0700592 // set initial conditions (e.g. unblank default device)
593 initializeDisplays();
594
Dan Stoza4e637772016-07-28 13:31:51 -0700595 mRenderEngine->primeCache();
596
Wei Wangb254fa32017-01-31 17:43:23 -0800597 mStartBootAnimThread = new StartBootAnimThread();
598 if (mStartBootAnimThread->Start() != NO_ERROR) {
599 ALOGE("Run StartBootAnimThread failed!");
600 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800601
Dan Stoza9e56aa02015-11-02 13:00:03 -0800602 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700603}
604
Mathias Agopiana67e4182012-06-19 17:26:12 -0700605void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800606 // Start boot animation service by setting a property mailbox
607 // if property setting thread is already running, Start() will be just a NOP
608 mStartBootAnimThread->Start();
609 // Wait until property was set
610 if (mStartBootAnimThread->join() != NO_ERROR) {
611 ALOGE("Join StartBootAnimThread failed!");
612 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700613}
614
Mathias Agopian875d8e12013-06-07 15:35:48 -0700615size_t SurfaceFlinger::getMaxTextureSize() const {
616 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700617}
618
Mathias Agopian875d8e12013-06-07 15:35:48 -0700619size_t SurfaceFlinger::getMaxViewportDims() const {
620 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700621}
622
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800623// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800624
Jamie Gennis582270d2011-08-17 18:19:00 -0700625bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800626 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800627 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800628 return authenticateSurfaceTextureLocked(bufferProducer);
629}
630
631bool SurfaceFlinger::authenticateSurfaceTextureLocked(
632 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800633 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700634 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800635}
636
Brian Anderson069b3652016-07-22 10:32:47 -0700637status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700638 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700639 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700640 FrameEvent::REQUESTED_PRESENT,
641 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700642 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700643 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700644 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700645 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700646 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700647 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700648 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700649 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700650 };
651 return NO_ERROR;
652}
653
Dan Stoza7f7da322014-05-02 15:26:25 -0700654status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
655 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700656 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700657 return BAD_VALUE;
658 }
659
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500660 if (!display.get())
661 return NAME_NOT_FOUND;
662
Jesse Hall692c7232012-11-08 15:41:56 -0800663 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700664 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800665 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700666 type = i;
667 break;
668 }
669 }
670
671 if (type < 0) {
672 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700673 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700674
Mathias Agopian8b736f12012-08-13 17:54:26 -0700675 // TODO: Not sure if display density should handled by SF any longer
676 class Density {
677 static int getDensityFromProperty(char const* propName) {
678 char property[PROPERTY_VALUE_MAX];
679 int density = 0;
680 if (property_get(propName, property, NULL) > 0) {
681 density = atoi(property);
682 }
683 return density;
684 }
685 public:
686 static int getEmuDensity() {
687 return getDensityFromProperty("qemu.sf.lcd_density"); }
688 static int getBuildDensity() {
689 return getDensityFromProperty("ro.sf.lcd_density"); }
690 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700691
Dan Stoza7f7da322014-05-02 15:26:25 -0700692 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700693
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700695 DisplayInfo info = DisplayInfo();
696
Dan Stoza9e56aa02015-11-02 13:00:03 -0800697 float xdpi = hwConfig->getDpiX();
698 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700699
700 if (type == DisplayDevice::DISPLAY_PRIMARY) {
701 // The density of the device is provided by a build property
702 float density = Density::getBuildDensity() / 160.0f;
703 if (density == 0) {
704 // the build doesn't provide a density -- this is wrong!
705 // use xdpi instead
706 ALOGE("ro.sf.lcd_density must be defined as a build property");
707 density = xdpi / 160.0f;
708 }
709 if (Density::getEmuDensity()) {
710 // if "qemu.sf.lcd_density" is specified, it overrides everything
711 xdpi = ydpi = density = Density::getEmuDensity();
712 density /= 160.0f;
713 }
714 info.density = density;
715
716 // TODO: this needs to go away (currently needed only by webkit)
717 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
718 info.orientation = hw->getOrientation();
719 } else {
720 // TODO: where should this value come from?
721 static const int TV_DENSITY = 213;
722 info.density = TV_DENSITY / 160.0f;
723 info.orientation = 0;
724 }
725
Dan Stoza9e56aa02015-11-02 13:00:03 -0800726 info.w = hwConfig->getWidth();
727 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700728 info.xdpi = xdpi;
729 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900731 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732
Andy McFadden91b2ca82014-06-13 14:04:23 -0700733 // This is how far in advance a buffer must be queued for
734 // presentation at a given time. If you want a buffer to appear
735 // on the screen at time N, you must submit the buffer before
736 // (N - presentationDeadline).
737 //
738 // Normally it's one full refresh period (to give SF a chance to
739 // latch the buffer), but this can be reduced by configuring a
740 // DispSync offset. Any additional delays introduced by the hardware
741 // composer or panel must be accounted for here.
742 //
743 // We add an additional 1ms to allow for processing time and
744 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 info.presentationDeadline = hwConfig->getVsyncPeriod() -
746 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700747
748 // All non-virtual displays are currently considered secure.
749 info.secure = true;
750
Michael Wright28f24d02016-07-12 13:30:53 -0700751 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 }
753
Dan Stoza7f7da322014-05-02 15:26:25 -0700754 return NO_ERROR;
755}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700756
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800757status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700758 DisplayStatInfo* stats) {
759 if (stats == NULL) {
760 return BAD_VALUE;
761 }
762
763 // FIXME for now we always return stats for the primary display
764 memset(stats, 0, sizeof(*stats));
765 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
766 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
767 return NO_ERROR;
768}
769
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700770int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800771 if (display == NULL) {
772 ALOGE("%s : display is NULL", __func__);
773 return BAD_VALUE;
774 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700775 sp<DisplayDevice> device(getDisplayDevice(display));
776 if (device != NULL) {
777 return device->getActiveConfig();
778 }
779 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700780}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700781
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700782void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
783 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
784 this);
785 int32_t type = hw->getDisplayType();
786 int currentMode = hw->getActiveConfig();
787
788 if (mode == currentMode) {
789 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
790 return;
791 }
792
793 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
794 ALOGW("Trying to set config for virtual display");
795 return;
796 }
797
798 hw->setActiveConfig(mode);
799 getHwComposer().setActiveConfig(type, mode);
800}
801
802status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
803 class MessageSetActiveConfig: public MessageBase {
804 SurfaceFlinger& mFlinger;
805 sp<IBinder> mDisplay;
806 int mMode;
807 public:
808 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
809 int mode) :
810 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
811 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700812 Vector<DisplayInfo> configs;
813 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700814 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700815 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700816 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700817 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700818 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700819 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
820 if (hw == NULL) {
821 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700822 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700823 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
824 ALOGW("Attempt to set active config = %d for virtual display",
825 mMode);
826 } else {
827 mFlinger.setActiveConfigInternal(hw, mMode);
828 }
829 return true;
830 }
831 };
832 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
833 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700834 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835}
Michael Wright28f24d02016-07-12 13:30:53 -0700836status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
837 Vector<android_color_mode_t>* outColorModes) {
838 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
839 return BAD_VALUE;
840 }
841
842 if (!display.get()) {
843 return NAME_NOT_FOUND;
844 }
845
846 int32_t type = NAME_NOT_FOUND;
847 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
848 if (display == mBuiltinDisplays[i]) {
849 type = i;
850 break;
851 }
852 }
853
854 if (type < 0) {
855 return type;
856 }
857
858 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
859 outColorModes->clear();
860 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
861
862 return NO_ERROR;
863}
864
865android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
866 sp<DisplayDevice> device(getDisplayDevice(display));
867 if (device != nullptr) {
868 return device->getActiveColorMode();
869 }
870 return static_cast<android_color_mode_t>(BAD_VALUE);
871}
872
873void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
874 android_color_mode_t mode) {
875 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
876 this);
877 int32_t type = hw->getDisplayType();
878 android_color_mode_t currentMode = hw->getActiveColorMode();
879
880 if (mode == currentMode) {
881 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
882 return;
883 }
884
885 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
886 ALOGW("Trying to set config for virtual display");
887 return;
888 }
889
890 hw->setActiveColorMode(mode);
891 getHwComposer().setActiveColorMode(type, mode);
892}
893
894
895status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
896 android_color_mode_t colorMode) {
897 class MessageSetActiveColorMode: public MessageBase {
898 SurfaceFlinger& mFlinger;
899 sp<IBinder> mDisplay;
900 android_color_mode_t mMode;
901 public:
902 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
903 android_color_mode_t mode) :
904 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
905 virtual bool handler() {
906 Vector<android_color_mode_t> modes;
907 mFlinger.getDisplayColorModes(mDisplay, &modes);
908 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
909 if (mMode < 0 || !exists) {
910 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
911 mDisplay.get());
912 return true;
913 }
914 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
915 if (hw == nullptr) {
916 ALOGE("Attempt to set active color mode = %d for null display %p",
917 mMode, mDisplay.get());
918 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
919 ALOGW("Attempt to set active color mode= %d for virtual display",
920 mMode);
921 } else {
922 mFlinger.setActiveColorModeInternal(hw, mMode);
923 }
924 return true;
925 }
926 };
927 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
928 postMessageSync(msg);
929 return NO_ERROR;
930}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700931
Svetoslavd85084b2014-03-20 10:28:31 -0700932status_t SurfaceFlinger::clearAnimationFrameStats() {
933 Mutex::Autolock _l(mStateLock);
934 mAnimFrameTracker.clearStats();
935 return NO_ERROR;
936}
937
938status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
939 Mutex::Autolock _l(mStateLock);
940 mAnimFrameTracker.getStats(outStats);
941 return NO_ERROR;
942}
943
Dan Stozac4f471e2016-03-24 09:31:08 -0700944status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
945 HdrCapabilities* outCapabilities) const {
946 Mutex::Autolock _l(mStateLock);
947
948 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
949 if (displayDevice == nullptr) {
950 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
951 return BAD_VALUE;
952 }
953
954 std::unique_ptr<HdrCapabilities> capabilities =
955 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
956 if (capabilities) {
957 std::swap(*outCapabilities, *capabilities);
958 } else {
959 return BAD_VALUE;
960 }
961
962 return NO_ERROR;
963}
964
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700965status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
966 if (enable == mInjectVSyncs) {
967 return NO_ERROR;
968 }
969
970 if (enable) {
971 mInjectVSyncs = enable;
972 ALOGV("VSync Injections enabled");
973 if (mVSyncInjector.get() == nullptr) {
974 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700975 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700976 }
977 mEventQueue.setEventThread(mInjectorEventThread);
978 } else {
979 mInjectVSyncs = enable;
980 ALOGV("VSync Injections disabled");
981 mEventQueue.setEventThread(mSFEventThread);
982 mVSyncInjector.clear();
983 }
984 return NO_ERROR;
985}
986
987status_t SurfaceFlinger::injectVSync(nsecs_t when) {
988 if (!mInjectVSyncs) {
989 ALOGE("VSync Injections not enabled");
990 return BAD_VALUE;
991 }
992 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
993 ALOGV("Injecting VSync inside SurfaceFlinger");
994 mVSyncInjector->onInjectSyncEvent(when);
995 }
996 return NO_ERROR;
997}
998
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800999// ----------------------------------------------------------------------------
1000
1001sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001002 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001003}
1004
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001006
1007void SurfaceFlinger::waitForEvent() {
1008 mEventQueue.waitMessage();
1009}
1010
1011void SurfaceFlinger::signalTransaction() {
1012 mEventQueue.invalidate();
1013}
1014
1015void SurfaceFlinger::signalLayerUpdate() {
1016 mEventQueue.invalidate();
1017}
1018
1019void SurfaceFlinger::signalRefresh() {
1020 mEventQueue.refresh();
1021}
1022
1023status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue.postMessage(msg, reltime);
1026}
1027
1028status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001029 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001030 status_t res = mEventQueue.postMessage(msg, reltime);
1031 if (res == NO_ERROR) {
1032 msg->wait();
1033 }
1034 return res;
1035}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001037void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001038 do {
1039 waitForEvent();
1040 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041}
1042
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001043void SurfaceFlinger::enableHardwareVsync() {
1044 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001045 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001046 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001047 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1048 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001050 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001051}
1052
Jesse Hall948fe0c2013-10-14 12:56:09 -07001053void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001054 Mutex::Autolock _l(mHWVsyncLock);
1055
Jesse Hall948fe0c2013-10-14 12:56:09 -07001056 if (makeAvailable) {
1057 mHWVsyncAvailable = true;
1058 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001059 // Hardware vsync is not currently available, so abort the resync
1060 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061 return;
1062 }
1063
Dan Stoza9e56aa02015-11-02 13:00:03 -08001064 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1065 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001066
1067 mPrimaryDispSync.reset();
1068 mPrimaryDispSync.setPeriod(period);
1069
1070 if (!mPrimaryHWVsyncEnabled) {
1071 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001072 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1073 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 mPrimaryHWVsyncEnabled = true;
1075 }
1076}
1077
Jesse Hall948fe0c2013-10-14 12:56:09 -07001078void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079 Mutex::Autolock _l(mHWVsyncLock);
1080 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001081 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1082 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 mPrimaryDispSync.endResync();
1084 mPrimaryHWVsyncEnabled = false;
1085 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001086 if (makeUnavailable) {
1087 mHWVsyncAvailable = false;
1088 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089}
1090
Tim Murray4a4e4a22016-04-19 16:29:23 +00001091void SurfaceFlinger::resyncWithRateLimit() {
1092 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1093 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001094 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001095 }
1096}
1097
Steven Thomas3cfac282017-02-06 12:29:30 -08001098void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1099 nsecs_t timestamp) {
1100 Mutex::Autolock lock(mStateLock);
1101 // Ignore any vsyncs from the non-active hardware composer.
1102 if (composer != mHwc) {
1103 return;
1104 }
1105
Jamie Gennisd1700752013-10-14 12:22:52 -07001106 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107
Jamie Gennisd1700752013-10-14 12:22:52 -07001108 { // Scope for the lock
1109 Mutex::Autolock _l(mHWVsyncLock);
1110 if (type == 0 && mPrimaryHWVsyncEnabled) {
1111 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001112 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001113 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001114
1115 if (needsHwVsync) {
1116 enableHardwareVsync();
1117 } else {
1118 disableHardwareVsync(false);
1119 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001120}
1121
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001122void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1123 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1124 *compositorTiming = mCompositorTiming;
1125}
1126
Dan Stoza9e56aa02015-11-02 13:00:03 -08001127void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1128 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1129 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1130 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001131
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 // All non-virtual displays are currently considered secure.
1133 bool isSecure = true;
1134
1135 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001136
1137 // When we're using the vr composer, the assumption is that we've
1138 // already created the IBinder object for the primary display.
1139 if (!mHwc->isUsingVrComposer()) {
1140 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1141 }
1142
Dan Stoza9e56aa02015-11-02 13:00:03 -08001143 wp<IBinder> token = mBuiltinDisplays[type];
1144
1145 sp<IGraphicBufferProducer> producer;
1146 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001147 BufferQueue::createBufferQueue(&producer, &consumer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001148
1149 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1150 DisplayDevice::DISPLAY_PRIMARY, consumer);
1151 sp<DisplayDevice> hw = new DisplayDevice(this,
1152 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1153 producer, mRenderEngine->getEGLConfig());
1154 mDisplays.add(token, hw);
1155 } else {
1156 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001157 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001158 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001160 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001161 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1162 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001163 }
1164 setTransactionFlags(eDisplayTransactionNeeded);
1165
Andy McFadden9e9689c2012-10-10 18:17:51 -07001166 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001167 }
Mathias Agopian86303202012-07-24 22:46:10 -07001168}
1169
Steven Thomas3cfac282017-02-06 12:29:30 -08001170void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1171 Mutex::Autolock lock(mStateLock);
1172 if (composer == mHwc) {
1173 repaintEverything();
1174 } else {
1175 // This isn't from our current hardware composer. If it's a callback
1176 // from the real composer, forward the refresh request to vr
1177 // flinger. Otherwise ignore it.
1178 if (!composer->isUsingVrComposer()) {
1179 mVrFlinger->OnHardwareComposerRefresh();
1180 }
1181 }
1182}
1183
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 getHwComposer().setVsyncEnabled(disp,
1187 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001188}
1189
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001190void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1191 for (size_t i = 0; i < layers.size(); ++i) {
1192 layers[i]->clearHwcLayers();
1193 }
1194}
1195
1196void SurfaceFlinger::resetHwc() {
1197 disableHardwareVsync(true);
1198 clearHwcLayers(mDrawingState.layersSortedByZ);
1199 clearHwcLayers(mCurrentState.layersSortedByZ);
1200 // Clear the drawing state so that the logic inside of
1201 // handleTransactionLocked will fire. It will determine the delta between
1202 // mCurrentState and mDrawingState and re-apply all changes when we make the
1203 // transition.
1204 mDrawingState.displays.clear();
1205 mDisplays.clear();
1206}
1207
1208void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001209 bool enteringVrMode = mEnterVrMode;
1210 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1211 return;
1212 }
1213 if (enteringVrMode && !mVrHwc) {
1214 // Construct new HWComposer without holding any locks.
1215 mVrHwc = new HWComposer(true);
1216 ALOGV("Vr HWC created");
1217 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001218 {
1219 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001220
1221 if (enteringVrMode) {
1222 // Start vrflinger thread, if it hasn't been started already.
1223 if (!mVrFlinger) {
1224 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1225 int err = mVrFlinger->Run(mHwc->getComposer());
1226 if (err != NO_ERROR) {
1227 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1228 mVrFlinger.reset();
1229 mEnterVrMode = false;
1230 return;
1231 }
1232 }
1233
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001234 resetHwc();
1235
1236 mHwc = mVrHwc;
1237 mVrFlinger->EnterVrMode();
1238 } else {
1239 mVrFlinger->ExitVrMode();
1240
1241 resetHwc();
1242
1243 mHwc = mRealHwc;
1244 enableHardwareVsync();
1245 }
1246
1247 mVisibleRegionsDirty = true;
1248 invalidateHwcGeometry();
1249 android_atomic_or(1, &mRepaintEverything);
1250 setTransactionFlags(eDisplayTransactionNeeded);
1251 }
1252 if (mVrHwc) {
1253 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1254 }
1255}
1256
Mathias Agopian4fec8732012-06-29 14:12:52 -07001257void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001258 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001260 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001261 // TODO(eieio): Tied to a conditional until SELinux issues
1262 // are resolved.
1263 if (mVrModeSupported) {
1264 updateVrMode();
1265 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001266
Dan Stoza50182882016-07-08 12:02:20 -07001267 bool frameMissed = !mHadClientComposition &&
1268 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001269 (mPreviousPresentFence->getSignalTime() ==
1270 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001271 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001272 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001273 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001274 signalLayerUpdate();
1275 break;
1276 }
1277
Dan Stoza6b9454d2014-11-07 16:00:59 -08001278 bool refreshNeeded = handleMessageTransaction();
1279 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001280 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001281 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001282 // Signal a refresh if a transaction modified the window state,
1283 // a new buffer was latched, or if HWC has requested a full
1284 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001285 signalRefresh();
1286 }
1287 break;
1288 }
1289 case MessageQueue::REFRESH: {
1290 handleMessageRefresh();
1291 break;
1292 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001293 }
1294}
1295
Dan Stoza6b9454d2014-11-07 16:00:59 -08001296bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001297 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001298 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001299 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001300 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001301 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001302 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001303}
1304
Dan Stoza6b9454d2014-11-07 16:00:59 -08001305bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001306 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001307 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001308}
1309
1310void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001311 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001312
Pablo Ceballos40845df2016-01-25 17:41:15 -08001313 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001314
Brian Andersond6927fb2016-07-23 23:37:30 -07001315 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001316 rebuildLayerStacks();
1317 setUpHWComposer();
1318 doDebugFlashRegions();
1319 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001320 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001321
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001322 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001323
1324 mHadClientComposition = false;
1325 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1326 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1327 mHadClientComposition = mHadClientComposition ||
1328 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1329 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001330
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001332}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001333
Mathias Agopiancd60f992012-08-16 16:28:27 -07001334void SurfaceFlinger::doDebugFlashRegions()
1335{
1336 // is debugging enabled
1337 if (CC_LIKELY(!mDebugRegion))
1338 return;
1339
1340 const bool repaintEverything = mRepaintEverything;
1341 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1342 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001343 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344 // transform the dirty region into this screen's coordinate space
1345 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1346 if (!dirtyRegion.isEmpty()) {
1347 // redraw the whole screen
1348 doComposeSurfaces(hw, Region(hw->bounds()));
1349
1350 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001351 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001352 RenderEngine& engine(getRenderEngine());
1353 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1354
Mathias Agopianda27af92012-09-13 18:17:13 -07001355 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001356 }
1357 }
1358 }
1359
1360 postFramebuffer();
1361
1362 if (mDebugRegion > 1) {
1363 usleep(mDebugRegion * 1000);
1364 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001365
Dan Stoza9e56aa02015-11-02 13:00:03 -08001366 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001367 auto& displayDevice = mDisplays[displayId];
1368 if (!displayDevice->isDisplayOn()) {
1369 continue;
1370 }
1371
1372 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001373 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1374 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001375 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376}
1377
Brian Andersond6927fb2016-07-23 23:37:30 -07001378void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001379{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380 ATRACE_CALL();
1381 ALOGV("preComposition");
1382
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001384 mDrawingState.traverseInZOrder([&](Layer* layer) {
1385 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386 needExtraInvalidate = true;
1387 }
Robert Carr2047fae2016-11-28 14:09:09 -08001388 });
1389
Mathias Agopiancd60f992012-08-16 16:28:27 -07001390 if (needExtraInvalidate) {
1391 signalLayerUpdate();
1392 }
1393}
1394
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395void SurfaceFlinger::updateCompositorTiming(
1396 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1397 std::shared_ptr<FenceTime>& presentFenceTime) {
1398 // Update queue of past composite+present times and determine the
1399 // most recently known composite to present latency.
1400 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1401 nsecs_t compositeToPresentLatency = -1;
1402 while (!mCompositePresentTimes.empty()) {
1403 CompositePresentTime& cpt = mCompositePresentTimes.front();
1404 // Cached values should have been updated before calling this method,
1405 // which helps avoid duplicate syscalls.
1406 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1407 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1408 break;
1409 }
1410 compositeToPresentLatency = displayTime - cpt.composite;
1411 mCompositePresentTimes.pop();
1412 }
1413
1414 // Don't let mCompositePresentTimes grow unbounded, just in case.
1415 while (mCompositePresentTimes.size() > 16) {
1416 mCompositePresentTimes.pop();
1417 }
1418
1419 // Integer division and modulo round toward 0 not -inf, so we need to
1420 // treat negative and positive offsets differently.
1421 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1422 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1423 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1424
1425 // Snap the latency to a value that removes scheduling jitter from the
1426 // composition and present times, which often have >1ms of jitter.
1427 // Reducing jitter is important if an app attempts to extrapolate
1428 // something (such as user input) to an accurate diasplay time.
1429 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1430 // with (presentLatency % interval).
1431 nsecs_t snappedCompositeToPresentLatency = -1;
1432 if (compositeToPresentLatency >= 0) {
1433 nsecs_t bias = vsyncInterval / 2;
1434 int64_t extraVsyncs =
1435 (compositeToPresentLatency - idealLatency + bias) /
1436 vsyncInterval;
1437 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1438 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1439 }
1440
1441 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1442 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1443 mCompositorTiming.interval = vsyncInterval;
1444 if (snappedCompositeToPresentLatency >= 0) {
1445 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1446 }
1447}
1448
1449void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001450{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001451 ATRACE_CALL();
1452 ALOGV("postComposition");
1453
Brian Anderson3546a3f2016-07-14 11:51:14 -07001454 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001455 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001456 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001457 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001458 }
1459
Brian Andersond6927fb2016-07-23 23:37:30 -07001460 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001461
1462 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1463 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1464 glCompositionDoneFenceTime =
1465 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1466 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1467 } else {
1468 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1469 }
1470 mGlCompositionDoneTimeline.updateSignalTimes();
1471
1472 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1473 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1474 mDisplayTimeline.push(displayFenceTime);
1475 mDisplayTimeline.updateSignalTimes();
1476
1477 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1478 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1479 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1480 presentFenceTime = &displayFenceTime;
1481 } else {
1482 retireFenceTime = &displayFenceTime;
1483 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001484
1485 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1486 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1487
1488 // We use the refreshStartTime which might be sampled a little later than
1489 // when we started doing work for this frame, but that should be okay
1490 // since updateCompositorTiming has snapping logic.
1491 updateCompositorTiming(
1492 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1493
Robert Carr2047fae2016-11-28 14:09:09 -08001494 mDrawingState.traverseInZOrder([&](Layer* layer) {
1495 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001497 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001498 recordBufferingStats(layer->getName().string(),
1499 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001500 }
Robert Carr2047fae2016-11-28 14:09:09 -08001501 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001502
Brian Anderson3d4039d2016-09-23 16:31:30 -07001503 if (displayFence->isValid()) {
1504 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001505 enableHardwareVsync();
1506 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001507 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001508 }
1509 }
1510
Andy McFadden5167ec62014-05-22 13:08:43 -07001511 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001512 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001513 enableHardwareVsync();
1514 }
1515 }
1516
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001517 if (mAnimCompositionPending) {
1518 mAnimCompositionPending = false;
1519
Brian Anderson3d4039d2016-09-23 16:31:30 -07001520 if (displayFenceTime->isValid()) {
1521 mAnimFrameTracker.setActualPresentFence(
1522 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001523 } else {
1524 // The HWC doesn't support present fences, so use the refresh
1525 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001526 nsecs_t presentTime =
1527 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001528 mAnimFrameTracker.setActualPresentTime(presentTime);
1529 }
1530 mAnimFrameTracker.advanceFrame();
1531 }
Dan Stozab90cf072015-03-05 11:05:59 -08001532
1533 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1534 return;
1535 }
1536
1537 nsecs_t currentTime = systemTime();
1538 if (mHasPoweredOff) {
1539 mHasPoweredOff = false;
1540 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001541 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001543 if (numPeriods < NUM_BUCKETS - 1) {
1544 mFrameBuckets[numPeriods] += elapsedTime;
1545 } else {
1546 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1547 }
1548 mTotalTime += elapsedTime;
1549 }
1550 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551}
1552
1553void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001554 ATRACE_CALL();
1555 ALOGV("rebuildLayerStacks");
1556
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001558 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1559 ATRACE_CALL();
1560 mVisibleRegionsDirty = false;
1561 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001562
Jeff Sharkey76488112017-02-27 14:15:18 -07001563 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1564 Region opaqueRegion;
1565 Region dirtyRegion;
1566 Vector<sp<Layer>> layersSortedByZ;
1567 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1568 const Transform& tr(displayDevice->getTransform());
1569 const Rect bounds(displayDevice->getBounds());
1570 if (displayDevice->isDisplayOn()) {
1571 computeVisibleRegions(
1572 displayDevice->getLayerStack(), dirtyRegion,
1573 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001574
Jeff Sharkey76488112017-02-27 14:15:18 -07001575 mDrawingState.traverseInZOrder([&](Layer* layer) {
1576 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1577 Region drawRegion(tr.transform(
1578 layer->visibleNonTransparentRegion));
1579 drawRegion.andSelf(bounds);
1580 if (!drawRegion.isEmpty()) {
1581 layersSortedByZ.add(layer);
1582 } else {
1583 // Clear out the HWC layer if this layer was
1584 // previously visible, but no longer is
1585 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1586 nullptr);
1587 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001588 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001589 // WM changes displayDevice->layerStack upon sleep/awake.
1590 // Here we make sure we delete the HWC layers even if
1591 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001592 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1593 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001594 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001595 });
1596 }
1597 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1598 displayDevice->undefinedRegion.set(bounds);
1599 displayDevice->undefinedRegion.subtractSelf(
1600 tr.transform(opaqueRegion));
1601 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001602 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001603 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001605
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001607 ATRACE_CALL();
1608 ALOGV("setUpHWComposer");
1609
Jesse Hall028dc8f2013-08-20 16:35:32 -07001610 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001611 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1612 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1613 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1614
1615 // If nothing has changed (!dirty), don't recompose.
1616 // If something changed, but we don't currently have any visible layers,
1617 // and didn't when we last did a composition, then skip it this time.
1618 // The second rule does two things:
1619 // - When all layers are removed from a display, we'll emit one black
1620 // frame, then nothing more until we get new layers.
1621 // - When a display is created with a private layer stack, we won't
1622 // emit any black frames until a layer is added to the layer stack.
1623 bool mustRecompose = dirty && !(empty && wasEmpty);
1624
1625 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1626 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1627 mustRecompose ? "doing" : "skipping",
1628 dirty ? "+" : "-",
1629 empty ? "+" : "-",
1630 wasEmpty ? "+" : "-");
1631
Dan Stoza71433162014-02-04 16:22:36 -08001632 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001633
1634 if (mustRecompose) {
1635 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1636 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001637 }
1638
Dan Stoza9e56aa02015-11-02 13:00:03 -08001639 // build the h/w work list
1640 if (CC_UNLIKELY(mGeometryInvalid)) {
1641 mGeometryInvalid = false;
1642 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1643 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1644 const auto hwcId = displayDevice->getHwcDisplayId();
1645 if (hwcId >= 0) {
1646 const Vector<sp<Layer>>& currentLayers(
1647 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001648 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001649 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 if (!layer->hasHwcLayer(hwcId)) {
1651 auto hwcLayer = mHwc->createLayer(hwcId);
1652 if (hwcLayer) {
1653 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1654 } else {
1655 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001656 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001657 }
1658 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001659
Robert Carrae060832016-11-28 10:51:00 -08001660 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001661 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001663 }
1664 }
1665 }
1666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001667 }
Riley Andrews03414a12014-07-01 14:22:59 -07001668
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001669
1670 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1671
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 // Set the per-frame data
1673 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1674 auto& displayDevice = mDisplays[displayId];
1675 const auto hwcId = displayDevice->getHwcDisplayId();
1676 if (hwcId < 0) {
1677 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001678 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001679 if (colorMatrix != mPreviousColorMatrix) {
1680 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1681 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1682 "display %zd: %d", displayId, result);
1683 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1685 layer->setPerFrameData(displayDevice);
1686 }
1687 }
1688
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001689 mPreviousColorMatrix = colorMatrix;
1690
Dan Stoza9e56aa02015-11-02 13:00:03 -08001691 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001692 auto& displayDevice = mDisplays[displayId];
1693 if (!displayDevice->isDisplayOn()) {
1694 continue;
1695 }
1696
1697 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1699 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001700 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703void SurfaceFlinger::doComposition() {
1704 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 ALOGV("doComposition");
1706
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001707 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001708 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001709 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001710 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711 // transform the dirty region into this screen's coordinate space
1712 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001713
1714 // repaint the framebuffer (if needed)
1715 doDisplayComposition(hw, dirtyRegion);
1716
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717 hw->dirtyRegion.clear();
1718 hw->flip(hw->swapRegion);
1719 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001720 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001722 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723}
1724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725void SurfaceFlinger::postFramebuffer()
1726{
Mathias Agopian841cde52012-03-01 15:44:37 -08001727 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001729
Mathias Agopiana44b0412011-10-16 18:46:35 -07001730 const nsecs_t now = systemTime();
1731 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001732
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1734 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001735 if (!displayDevice->isDisplayOn()) {
1736 continue;
1737 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 const auto hwcId = displayDevice->getHwcDisplayId();
1739 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001740 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001741 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001742 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001743 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1745 sp<Fence> releaseFence = Fence::NO_FENCE;
1746 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1747 releaseFence = displayDevice->getClientTargetAcquireFence();
1748 } else {
1749 auto hwcLayer = layer->getHwcLayer(hwcId);
1750 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001751 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 layer->onLayerDisplayed(releaseFence);
1753 }
1754 if (hwcId >= 0) {
1755 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001756 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001757 }
1758
Mathias Agopiana44b0412011-10-16 18:46:35 -07001759 mLastSwapBufferTime = systemTime() - now;
1760 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001761
1762 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1763 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1764 logFrameStats();
1765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001766}
1767
Mathias Agopian87baae12012-07-31 12:38:26 -07001768void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769{
Mathias Agopian841cde52012-03-01 15:44:37 -08001770 ATRACE_CALL();
1771
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001772 // here we keep a copy of the drawing state (that is the state that's
1773 // going to be overwritten by handleTransactionLocked()) outside of
1774 // mStateLock so that the side-effects of the State assignment
1775 // don't happen with mStateLock held (which can cause deadlocks).
1776 State drawingState(mDrawingState);
1777
Mathias Agopianca4d3602011-05-19 15:38:14 -07001778 Mutex::Autolock _l(mStateLock);
1779 const nsecs_t now = systemTime();
1780 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781
Mathias Agopianca4d3602011-05-19 15:38:14 -07001782 // Here we're guaranteed that some transaction flags are set
1783 // so we can call handleTransactionLocked() unconditionally.
1784 // We call getTransactionFlags(), which will also clear the flags,
1785 // with mStateLock held to guarantee that mCurrentState won't change
1786 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001787
Mathias Agopiane57f2922012-08-09 16:29:12 -07001788 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001789 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001790
Mathias Agopianca4d3602011-05-19 15:38:14 -07001791 mLastTransactionTime = systemTime() - now;
1792 mDebugInTransaction = 0;
1793 invalidateHwcGeometry();
1794 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001795}
1796
Mathias Agopian87baae12012-07-31 12:38:26 -07001797void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001798{
Dan Stoza7dde5992015-05-22 09:51:44 -07001799 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001800 mCurrentState.traverseInZOrder([](Layer* layer) {
1801 layer->notifyAvailableFrames();
1802 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 /*
1805 * Traversal of the children
1806 * (perform the transaction for each of them if needed)
1807 */
1808
Mathias Agopian3559b072012-08-15 13:46:03 -07001809 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001810 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001812 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813
1814 const uint32_t flags = layer->doTransaction(0);
1815 if (flags & Layer::eVisibleRegion)
1816 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001817 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001818 }
1819
1820 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001821 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822 */
1823
Mathias Agopiane57f2922012-08-09 16:29:12 -07001824 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001825 // here we take advantage of Vector's copy-on-write semantics to
1826 // improve performance by skipping the transaction entirely when
1827 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001828 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1829 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001830 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001833 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834
1835 // find the displays that were removed
1836 // (ie: in drawing state but not in current state)
1837 // also handle displays that changed
1838 // (ie: displays that are in both lists)
1839 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001840 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1841 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001842 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001843 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001844 // Call makeCurrent() on the primary display so we can
1845 // be sure that nothing associated with this display
1846 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001847 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001848 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001849 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1850 if (hw != NULL)
1851 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001852 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001853 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001854 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001855 } else {
1856 ALOGW("trying to remove the main display");
1857 }
1858 } else {
1859 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001860 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001861 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001862 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1863 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001864 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001865 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001866 // recreating the DisplayDevice, so we just remove it
1867 // from the drawing state, so that it get re-added
1868 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001869 sp<DisplayDevice> hw(getDisplayDevice(display));
1870 if (hw != NULL)
1871 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001872 mDisplays.removeItem(display);
1873 mDrawingState.displays.removeItemsAt(i);
1874 dc--; i--;
1875 // at this point we must loop to the next item
1876 continue;
1877 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001878
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001879 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001880 if (disp != NULL) {
1881 if (state.layerStack != draw[i].layerStack) {
1882 disp->setLayerStack(state.layerStack);
1883 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001884 if ((state.orientation != draw[i].orientation)
1885 || (state.viewport != draw[i].viewport)
1886 || (state.frame != draw[i].frame))
1887 {
1888 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001889 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001890 }
Michael Lentine47e45402014-07-18 15:34:25 -07001891 if (state.width != draw[i].width || state.height != draw[i].height) {
1892 disp->setDisplaySize(state.width, state.height);
1893 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001894 }
1895 }
1896 }
1897
1898 // find displays that were added
1899 // (ie: in current state but not in drawing state)
1900 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001901 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001902 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001903
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001904 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001905 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001906 sp<IGraphicBufferProducer> bqProducer;
1907 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001908 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001909
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001911 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001912 // Virtual displays without a surface are dormant:
1913 // they have external state (layer stack, projection,
1914 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001915 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001916
Dan Stoza8cf150a2016-08-02 10:27:31 -07001917 if (mUseHwcVirtualDisplays) {
1918 int width = 0;
1919 int status = state.surface->query(
1920 NATIVE_WINDOW_WIDTH, &width);
1921 ALOGE_IF(status != NO_ERROR,
1922 "Unable to query width (%d)", status);
1923 int height = 0;
1924 status = state.surface->query(
1925 NATIVE_WINDOW_HEIGHT, &height);
1926 ALOGE_IF(status != NO_ERROR,
1927 "Unable to query height (%d)", status);
1928 int intFormat = 0;
1929 status = state.surface->query(
1930 NATIVE_WINDOW_FORMAT, &intFormat);
1931 ALOGE_IF(status != NO_ERROR,
1932 "Unable to query format (%d)", status);
1933 auto format = static_cast<android_pixel_format_t>(
1934 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001935
Dan Stoza8cf150a2016-08-02 10:27:31 -07001936 mHwc->allocateVirtualDisplay(width, height, &format,
1937 &hwcId);
1938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939
Dan Stoza5cf424b2016-05-20 14:02:39 -07001940 // TODO: Plumb requested format back up to consumer
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 sp<VirtualDisplaySurface> vds =
1943 new VirtualDisplaySurface(*mHwc,
1944 hwcId, state.surface, bqProducer,
1945 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001946
1947 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001948 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001949 }
1950 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001951 ALOGE_IF(state.surface!=NULL,
1952 "adding a supported display, but rendering "
1953 "surface is provided (%p), ignoring it",
1954 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001955
1956 hwcId = state.type;
1957 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1958 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001959 }
1960
1961 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001962 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001963 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 state.type, hwcId, state.isSecure, display,
1965 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001966 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001967 hw->setLayerStack(state.layerStack);
1968 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001969 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001970 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001971 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001973 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001974 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001975 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001976 }
1977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001978 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980
Mathias Agopian84300952012-11-21 16:02:13 -08001981 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1982 // The transform hint might have changed for some layers
1983 // (either because a display has changed, or because a layer
1984 // as changed).
1985 //
1986 // Walk through all the layers in currentLayers,
1987 // and update their transform hint.
1988 //
1989 // If a layer is visible only on a single display, then that
1990 // display is used to calculate the hint, otherwise we use the
1991 // default display.
1992 //
1993 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1994 // the hint is set before we acquire a buffer from the surface texture.
1995 //
1996 // NOTE: layer transactions have taken place already, so we use their
1997 // drawing state. However, SurfaceFlinger's own transaction has not
1998 // happened yet, so we must use the current state layer list
1999 // (soon to become the drawing state list).
2000 //
2001 sp<const DisplayDevice> disp;
2002 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002003 bool first = true;
2004 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002005 // NOTE: we rely on the fact that layers are sorted by
2006 // layerStack first (so we don't have to traverse the list
2007 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002008 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002009 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002010 currentlayerStack = layerStack;
2011 // figure out if this layerstack is mirrored
2012 // (more than one display) if so, pick the default display,
2013 // if not, pick the only display it's on.
2014 disp.clear();
2015 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2016 sp<const DisplayDevice> hw(mDisplays[dpy]);
2017 if (hw->getLayerStack() == currentlayerStack) {
2018 if (disp == NULL) {
2019 disp = hw;
2020 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002021 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002022 break;
2023 }
2024 }
2025 }
2026 }
Chet Haase91d25932013-04-11 15:24:55 -07002027 if (disp == NULL) {
2028 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2029 // redraw after transform hint changes. See bug 8508397.
2030
2031 // could be null when this layer is using a layerStack
2032 // that is not visible on any display. Also can occur at
2033 // screen off/on times.
2034 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002035 }
Chet Haase91d25932013-04-11 15:24:55 -07002036 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002037
2038 first = false;
2039 });
Mathias Agopian84300952012-11-21 16:02:13 -08002040 }
2041
2042
Mathias Agopian3559b072012-08-15 13:46:03 -07002043 /*
2044 * Perform our own transaction if needed
2045 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002046
2047 if (mLayersAdded) {
2048 mLayersAdded = false;
2049 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002050 mVisibleRegionsDirty = true;
2051 }
2052
2053 // some layers might have been removed, so
2054 // we need to update the regions they're exposing.
2055 if (mLayersRemoved) {
2056 mLayersRemoved = false;
2057 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002058 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002059 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002060 // this layer is not visible anymore
2061 // TODO: we could traverse the tree from front to back and
2062 // compute the actual visible region
2063 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002064 Region visibleReg;
2065 visibleReg.set(layer->computeScreenBounds());
2066 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002067 }
Robert Carr2047fae2016-11-28 14:09:09 -08002068 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069 }
2070
2071 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002072
2073 updateCursorAsync();
2074}
2075
2076void SurfaceFlinger::updateCursorAsync()
2077{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2079 auto& displayDevice = mDisplays[displayId];
2080 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002081 continue;
2082 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083
2084 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2085 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002086 }
2087 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002088}
2089
2090void SurfaceFlinger::commitTransaction()
2091{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002092 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002093 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094 for (const auto& l : mLayersPendingRemoval) {
2095 recordBufferingStats(l->getName().string(),
2096 l->getOccupancyHistory(true));
2097 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 }
2099 mLayersPendingRemoval.clear();
2100 }
2101
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 // If this transaction is part of a window animation then the next frame
2103 // we composite should be considered an animation as well.
2104 mAnimCompositionPending = mAnimTransactionPending;
2105
Mathias Agopian4fec8732012-06-29 14:12:52 -07002106 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002107 mDrawingState.traverseInZOrder([](Layer* layer) {
2108 layer->commitChildList();
2109 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002110 mTransactionPending = false;
2111 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002112 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113}
2114
Robert Carr2047fae2016-11-28 14:09:09 -08002115void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117{
Mathias Agopian841cde52012-03-01 15:44:37 -08002118 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 Region aboveOpaqueLayers;
2122 Region aboveCoveredLayers;
2123 Region dirty;
2124
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126
Robert Carr2047fae2016-11-28 14:09:09 -08002127 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002129 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130
Jesse Hall01e29052013-02-19 16:13:35 -08002131 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002132 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002133 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002134
Mathias Agopianab028732010-03-16 16:41:46 -07002135 /*
2136 * opaqueRegion: area of a surface that is fully opaque.
2137 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002139
2140 /*
2141 * visibleRegion: area of a surface that is visible on screen
2142 * and not fully transparent. This is essentially the layer's
2143 * footprint minus the opaque regions above it.
2144 * Areas covered by a translucent surface are considered visible.
2145 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002147
2148 /*
2149 * coveredRegion: area of a surface that is covered by all
2150 * visible regions above it (which includes the translucent areas).
2151 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002153
Jesse Halla8026d22012-09-25 13:25:04 -07002154 /*
2155 * transparentRegion: area of a surface that is hinted to be completely
2156 * transparent. This is only used to tell when the layer has no visible
2157 * non-transparent regions and can be removed from the layer list. It
2158 * does not affect the visibleRegion of this layer or any layers
2159 * beneath it. The hint may not be correct if apps don't respect the
2160 * SurfaceView restrictions (which, sadly, some don't).
2161 */
2162 Region transparentRegion;
2163
Mathias Agopianab028732010-03-16 16:41:46 -07002164
2165 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002166 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002167 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002168 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002170 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002171 if (!visibleRegion.isEmpty()) {
2172 // Remove the transparent area from the visible region
2173 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002174 if (tr.preserveRects()) {
2175 // transform the transparent region
2176 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002177 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002178 // transformation too complex, can't do the
2179 // transparent region optimization.
2180 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002181 }
Mathias Agopianab028732010-03-16 16:41:46 -07002182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183
Mathias Agopianab028732010-03-16 16:41:46 -07002184 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002185 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002187 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2188 // the opaque region is the layer's footprint
2189 opaqueRegion = visibleRegion;
2190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191 }
2192 }
2193
Mathias Agopianab028732010-03-16 16:41:46 -07002194 // Clip the covered region to the visible region
2195 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2196
2197 // Update aboveCoveredLayers for next (lower) layer
2198 aboveCoveredLayers.orSelf(visibleRegion);
2199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 // subtract the opaque region covered by the layers above us
2201 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202
2203 // compute this layer's dirty region
2204 if (layer->contentDirty) {
2205 // we need to invalidate the whole region
2206 dirty = visibleRegion;
2207 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002208 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209 layer->contentDirty = false;
2210 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002211 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002212 * the exposed region consists of two components:
2213 * 1) what's VISIBLE now and was COVERED before
2214 * 2) what's EXPOSED now less what was EXPOSED before
2215 *
2216 * note that (1) is conservative, we start with the whole
2217 * visible region but only keep what used to be covered by
2218 * something -- which mean it may have been exposed.
2219 *
2220 * (2) handles areas that were not covered by anything but got
2221 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002222 */
Mathias Agopianab028732010-03-16 16:41:46 -07002223 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 const Region oldVisibleRegion = layer->visibleRegion;
2225 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002226 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2227 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 }
2229 dirty.subtractSelf(aboveOpaqueLayers);
2230
2231 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002232 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233
Mathias Agopianab028732010-03-16 16:41:46 -07002234 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002236
Jesse Halla8026d22012-09-25 13:25:04 -07002237 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 layer->setVisibleRegion(visibleRegion);
2239 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002240 layer->setVisibleNonTransparentRegion(
2241 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002242 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Mathias Agopian87baae12012-07-31 12:38:26 -07002244 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245}
2246
Mathias Agopian87baae12012-07-31 12:38:26 -07002247void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2248 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002249 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002250 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2251 if (hw->getLayerStack() == layerStack) {
2252 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002253 }
2254 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002255}
2256
Dan Stoza6b9454d2014-11-07 16:00:59 -08002257bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 ALOGV("handlePageFlip");
2260
Brian Andersond6927fb2016-07-23 23:37:30 -07002261 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262
Mathias Agopian4fec8732012-06-29 14:12:52 -07002263 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002264 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002265
2266 // Store the set of layers that need updates. This set must not change as
2267 // buffers are being latched, as this could result in a deadlock.
2268 // Example: Two producers share the same command stream and:
2269 // 1.) Layer 0 is latched
2270 // 2.) Layer 0 gets a new frame
2271 // 2.) Layer 1 gets a new frame
2272 // 3.) Layer 1 is latched.
2273 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2274 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002275 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002276 if (layer->hasQueuedFrame()) {
2277 frameQueued = true;
2278 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002279 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002280 } else {
2281 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002282 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002283 } else {
2284 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 }
Robert Carr2047fae2016-11-28 14:09:09 -08002286 });
2287
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002289 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002290 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002292 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002293
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002294 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002295
2296 // If we will need to wake up at some time in the future to deal with a
2297 // queued frame that shouldn't be displayed during this vsync period, wake
2298 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002300 signalLayerUpdate();
2301 }
2302
2303 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305}
2306
Mathias Agopianad456f92011-01-13 17:53:01 -08002307void SurfaceFlinger::invalidateHwcGeometry()
2308{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002310}
2311
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002312
Fabien Sanglard830b8472016-11-30 16:35:58 -08002313void SurfaceFlinger::doDisplayComposition(
2314 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002315 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316{
Dan Stoza71433162014-02-04 16:22:36 -08002317 // We only need to actually compose the display if:
2318 // 1) It is being handled by hardware composer, which may need this to
2319 // keep its virtual display state machine in sync, or
2320 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002321 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002322 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002323 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002324 return;
2325 }
2326
Dan Stoza9e56aa02015-11-02 13:00:03 -08002327 ALOGV("doDisplayComposition");
2328
Mathias Agopian87baae12012-07-31 12:38:26 -07002329 Region dirtyRegion(inDirtyRegion);
2330
Mathias Agopianb8a55602009-06-26 19:06:36 -07002331 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333
Fabien Sanglard830b8472016-11-30 16:35:58 -08002334 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002335 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002336 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2337 // takes a rectangle, we must make sure to update that whole
2338 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002340 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002341 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002342 // We need to redraw the rectangle that will be updated
2343 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002344 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002345 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002346 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002347 } else {
2348 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 dirtyRegion.set(displayDevice->bounds());
2350 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 }
2352 }
2353
Fabien Sanglard830b8472016-11-30 16:35:58 -08002354 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002356 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002358
2359 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002360 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361}
2362
Dan Stoza9e56aa02015-11-02 13:00:03 -08002363bool SurfaceFlinger::doComposeSurfaces(
2364 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002365{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002367
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002369
2370 mat4 oldColorMatrix;
2371 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2372 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2373 if (applyColorMatrix) {
2374 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2375 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2376 }
2377
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2379 if (hasClientComposition) {
2380 ALOGV("hasClientComposition");
2381
2382 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002383 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002384 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002385 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2386 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2387 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2388 }
2389 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002390 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002391
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002392 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2394 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002395 // when using overlays, we assume a fully transparent framebuffer
2396 // NOTE: we could reduce how much we need to clear, for instance
2397 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002398 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002399 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002400 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002401 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002402 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002404
2405 // we remove the scissor part
2406 // we're left with the letterbox region
2407 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002409
2410 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002412
2413 // but limit it to the dirty region
2414 region.andSelf(dirty);
2415
Mathias Agopianb9494d52012-04-18 02:28:45 -07002416 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002417 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002418 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002420 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002421 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002422
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002424 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002425 // scissor on the main display. It should never be needed
2426 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 const Rect& bounds(displayDevice->getBounds());
2428 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002429 if (scissor != bounds) {
2430 // scissor doesn't match the screen's dimensions, so we
2431 // need to clear everything outside of it and enable
2432 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002433
Mathias Agopianf45c5102012-10-24 16:29:17 -07002434 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 const uint32_t height = displayDevice->getHeight();
2436 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002437 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002438 }
2439 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002440 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002441
Mathias Agopian85d751c2012-08-29 16:59:24 -07002442 /*
2443 * and then, render the layers targeted at the framebuffer
2444 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002445
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 ALOGV("Rendering client layers");
2447 const Transform& displayTransform = displayDevice->getTransform();
2448 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002449 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 bool firstLayer = true;
2451 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2452 const Region clip(dirty.intersect(
2453 displayTransform.transform(layer->visibleRegion)));
2454 ALOGV("Layer: %s", layer->getName().string());
2455 ALOGV(" Composition type: %s",
2456 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002457 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 switch (layer->getCompositionType(hwcId)) {
2459 case HWC2::Composition::Cursor:
2460 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002461 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002463 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2465 layer->isOpaque(state) && (state.alpha == 1.0f)
2466 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002467 // never clear the very first layer since we're
2468 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002469 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002471 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002472 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 case HWC2::Composition::Client: {
2474 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 break;
2476 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002478 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002479 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 } else {
2481 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002484 }
2485 } else {
2486 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002488 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002490 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002492 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002493 }
2494 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002495
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002496 if (applyColorMatrix) {
2497 getRenderEngine().setupColorTransform(oldColorMatrix);
2498 }
2499
Mathias Agopianf45c5102012-10-24 16:29:17 -07002500 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002502 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503}
2504
Fabien Sanglard830b8472016-11-30 16:35:58 -08002505void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2506 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002507 RenderEngine& engine(getRenderEngine());
2508 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509}
2510
Dan Stoza7d89d062015-04-30 13:29:25 -07002511status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002512 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002513 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 const sp<Layer>& lbc,
2515 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002516{
Dan Stoza7d89d062015-04-30 13:29:25 -07002517 // add this layer to the current state list
2518 {
2519 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002521 return NO_MEMORY;
2522 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002523 if (parent == nullptr) {
2524 mCurrentState.layersSortedByZ.add(lbc);
2525 } else {
2526 parent->addChild(lbc);
2527 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002528 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 mLayersAdded = true;
2530 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002531 }
2532
Mathias Agopian96f08192010-06-02 23:28:45 -07002533 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002534 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002535
Dan Stoza7d89d062015-04-30 13:29:25 -07002536 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002537}
2538
Robert Carr9524cb32017-02-13 11:32:32 -08002539status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002540 Mutex::Autolock _l(mStateLock);
2541
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 const auto& p = layer->getParent();
2543 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2544 mCurrentState.layersSortedByZ.remove(layer);
2545
Robert Carr136e2f62017-02-08 17:54:29 -08002546 // As a matter of normal operation, the LayerCleaner will produce a second
2547 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2548 // so we will succeed in promoting it, but it's already been removed
2549 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2550 // otherwise something has gone wrong and we are leaking the layer.
2551 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2553 layer->getName().string(),
2554 (p != nullptr) ? p->getName().string() : "no-parent");
2555 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002556 } else if (index < 0) {
2557 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002558 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002559
2560 mLayersPendingRemoval.add(layer);
2561 mLayersRemoved = true;
2562 mNumLayers--;
2563 setTransactionFlags(eTransactionNeeded);
2564 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565}
2566
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002567uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002568 return android_atomic_release_load(&mTransactionFlags);
2569}
2570
Mathias Agopian3f844832013-08-07 21:24:32 -07002571uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2573}
2574
Mathias Agopian3f844832013-08-07 21:24:32 -07002575uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2577 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002578 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 }
2580 return old;
2581}
2582
Mathias Agopian8b33f032012-07-24 20:43:54 -07002583void SurfaceFlinger::setTransactionState(
2584 const Vector<ComposerState>& state,
2585 const Vector<DisplayState>& displays,
2586 uint32_t flags)
2587{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002588 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002589 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002590 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002592 if (flags & eAnimation) {
2593 // For window updates that are part of an animation we must wait for
2594 // previous animation "frames" to be handled.
2595 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002596 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002597 if (CC_UNLIKELY(err != NO_ERROR)) {
2598 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002599 // caller after a few seconds.
2600 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2601 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002602 mAnimTransactionPending = false;
2603 break;
2604 }
2605 }
2606 }
2607
Mathias Agopiane57f2922012-08-09 16:29:12 -07002608 size_t count = displays.size();
2609 for (size_t i=0 ; i<count ; i++) {
2610 const DisplayState& s(displays[i]);
2611 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002612 }
2613
Mathias Agopiane57f2922012-08-09 16:29:12 -07002614 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002615 for (size_t i=0 ; i<count ; i++) {
2616 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002617 // Here we need to check that the interface we're given is indeed
2618 // one of our own. A malicious client could give us a NULL
2619 // IInterface, or one of its own or even one of our own but a
2620 // different type. All these situations would cause us to crash.
2621 //
2622 // NOTE: it would be better to use RTTI as we could directly check
2623 // that we have a Client*. however, RTTI is disabled in Android.
2624 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002625 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002626 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002627 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002628 sp<Client> client( static_cast<Client *>(s.client.get()) );
2629 transactionFlags |= setClientStateLocked(client, s.state);
2630 }
2631 }
2632 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002633 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002634
Robert Carr2a7dbb42016-05-24 11:41:28 -07002635 // If a synchronous transaction is explicitly requested without any changes,
2636 // force a transaction anyway. This can be used as a flush mechanism for
2637 // previous async transactions.
2638 if (transactionFlags == 0 && (flags & eSynchronous)) {
2639 transactionFlags = eTransactionNeeded;
2640 }
2641
Mathias Agopian386aa982011-11-07 21:58:03 -08002642 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002643 if (mInterceptor.isEnabled()) {
2644 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2645 }
Irvel468051e2016-06-13 16:44:44 -07002646
Mathias Agopian386aa982011-11-07 21:58:03 -08002647 // this triggers the transaction
2648 setTransactionFlags(transactionFlags);
2649
2650 // if this is a synchronous transaction, wait for it to take effect
2651 // before returning.
2652 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002653 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002654 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002655 if (flags & eAnimation) {
2656 mAnimTransactionPending = true;
2657 }
2658 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002659 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2660 if (CC_UNLIKELY(err != NO_ERROR)) {
2661 // just in case something goes wrong in SF, return to the
2662 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002663 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2664 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002665 break;
2666 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 }
2669}
2670
Mathias Agopiane57f2922012-08-09 16:29:12 -07002671uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2672{
Jesse Hall9a143922012-10-04 16:29:19 -07002673 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2674 if (dpyIdx < 0)
2675 return 0;
2676
Mathias Agopiane57f2922012-08-09 16:29:12 -07002677 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002678 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002679 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002680 const uint32_t what = s.what;
2681 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002682 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 disp.surface = s.surface;
2684 flags |= eDisplayTransactionNeeded;
2685 }
2686 }
2687 if (what & DisplayState::eLayerStackChanged) {
2688 if (disp.layerStack != s.layerStack) {
2689 disp.layerStack = s.layerStack;
2690 flags |= eDisplayTransactionNeeded;
2691 }
2692 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002693 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002694 if (disp.orientation != s.orientation) {
2695 disp.orientation = s.orientation;
2696 flags |= eDisplayTransactionNeeded;
2697 }
2698 if (disp.frame != s.frame) {
2699 disp.frame = s.frame;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 if (disp.viewport != s.viewport) {
2703 disp.viewport = s.viewport;
2704 flags |= eDisplayTransactionNeeded;
2705 }
2706 }
Michael Lentine47e45402014-07-18 15:34:25 -07002707 if (what & DisplayState::eDisplaySizeChanged) {
2708 if (disp.width != s.width) {
2709 disp.width = s.width;
2710 flags |= eDisplayTransactionNeeded;
2711 }
2712 if (disp.height != s.height) {
2713 disp.height = s.height;
2714 flags |= eDisplayTransactionNeeded;
2715 }
2716 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002717 }
2718 return flags;
2719}
2720
2721uint32_t SurfaceFlinger::setClientStateLocked(
2722 const sp<Client>& client,
2723 const layer_state_t& s)
2724{
2725 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002726 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002727 if (layer != 0) {
2728 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002729 bool geometryAppliesWithResize =
2730 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002732 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002733 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002734 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 }
2736 if (what & layer_state_t::eLayerChanged) {
2737 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 const auto& p = layer->getParent();
2739 if (p == nullptr) {
2740 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2741 if (layer->setLayer(s.z) && idx >= 0) {
2742 mCurrentState.layersSortedByZ.removeAt(idx);
2743 mCurrentState.layersSortedByZ.add(layer);
2744 // we need traversal (state changed)
2745 // AND transaction (list changed)
2746 flags |= eTransactionNeeded|eTraversalNeeded;
2747 }
2748 } else {
2749 if (p->setChildLayer(layer, s.z)) {
2750 flags |= eTransactionNeeded|eTraversalNeeded;
2751 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002752 }
2753 }
2754 if (what & layer_state_t::eSizeChanged) {
2755 if (layer->setSize(s.w, s.h)) {
2756 flags |= eTraversalNeeded;
2757 }
2758 }
2759 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002761 flags |= eTraversalNeeded;
2762 }
2763 if (what & layer_state_t::eMatrixChanged) {
2764 if (layer->setMatrix(s.matrix))
2765 flags |= eTraversalNeeded;
2766 }
2767 if (what & layer_state_t::eTransparentRegionChanged) {
2768 if (layer->setTransparentRegionHint(s.transparentRegion))
2769 flags |= eTraversalNeeded;
2770 }
Dan Stoza23116082015-06-18 14:58:39 -07002771 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002772 if (layer->setFlags(s.flags, s.mask))
2773 flags |= eTraversalNeeded;
2774 }
2775 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002776 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002777 flags |= eTraversalNeeded;
2778 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002779 if (what & layer_state_t::eFinalCropChanged) {
2780 if (layer->setFinalCrop(s.finalCrop))
2781 flags |= eTraversalNeeded;
2782 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002783 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002784 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785 // We only allow setting layer stacks for top level layers,
2786 // everything else inherits layer stack from its parent.
2787 if (layer->hasParent()) {
2788 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2789 layer->getName().string());
2790 } else if (idx < 0) {
2791 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2792 "that also does not appear in the top level layer list. Something"
2793 " has gone wrong.", layer->getName().string());
2794 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002795 mCurrentState.layersSortedByZ.removeAt(idx);
2796 mCurrentState.layersSortedByZ.add(layer);
2797 // we need traversal (state changed)
2798 // AND transaction (list changed)
2799 flags |= eTransactionNeeded|eTraversalNeeded;
2800 }
2801 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002802 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002803 if (s.barrierHandle != nullptr) {
2804 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2805 } else if (s.barrierGbp != nullptr) {
2806 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2807 if (authenticateSurfaceTextureLocked(gbp)) {
2808 const auto& otherLayer =
2809 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2810 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2811 } else {
2812 ALOGE("Attempt to defer transaction to to an"
2813 " unrecognized GraphicBufferProducer");
2814 }
2815 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002816 // We don't trigger a traversal here because if no other state is
2817 // changed, we don't want this to cause any more work
2818 }
Robert Carr1db73f62016-12-21 12:58:51 -08002819 if (what & layer_state_t::eReparentChildren) {
2820 if (layer->reparentChildren(s.reparentHandle)) {
2821 flags |= eTransactionNeeded|eTraversalNeeded;
2822 }
2823 }
Robert Carr9524cb32017-02-13 11:32:32 -08002824 if (what & layer_state_t::eDetachChildren) {
2825 layer->detachChildren();
2826 }
Robert Carrc3574f72016-03-24 12:19:32 -07002827 if (what & layer_state_t::eOverrideScalingModeChanged) {
2828 layer->setOverrideScalingMode(s.overrideScalingMode);
2829 // We don't trigger a traversal here because if no other state is
2830 // changed, we don't want this to cause any more work
2831 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002832 }
2833 return flags;
2834}
2835
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002836status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002837 const String8& name,
2838 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002839 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002840 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2841 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002843 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002844 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002845 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002846 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002847 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002848
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002849 status_t result = NO_ERROR;
2850
2851 sp<Layer> layer;
2852
Mathias Agopian3165cc22012-08-08 19:42:09 -07002853 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2854 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002855 result = createNormalLayer(client,
2856 name, w, h, flags, format,
2857 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002859 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002860 result = createDimLayer(client,
2861 name, w, h, flags,
2862 handle, gbp, &layer);
2863 break;
2864 default:
2865 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 break;
2867 }
2868
Dan Stoza7d89d062015-04-30 13:29:25 -07002869 if (result != NO_ERROR) {
2870 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002872
Albert Chaulk479c60c2017-01-27 14:21:34 -05002873 layer->setInfo(windowType, ownerUid);
2874
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002876 if (result != NO_ERROR) {
2877 return result;
2878 }
Irvelffc9efc2016-07-27 15:16:37 -07002879 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002880
2881 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002882 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883}
2884
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002885status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2886 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2887 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888{
2889 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002890 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 case PIXEL_FORMAT_TRANSPARENT:
2892 case PIXEL_FORMAT_TRANSLUCENT:
2893 format = PIXEL_FORMAT_RGBA_8888;
2894 break;
2895 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002896 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 break;
2898 }
2899
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002900 *outLayer = new Layer(this, client, name, w, h, flags);
2901 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2902 if (err == NO_ERROR) {
2903 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002904 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002906
2907 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2908 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909}
2910
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002911status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2912 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2913 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002915 *outLayer = new LayerDim(this, client, name, w, h, flags);
2916 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002917 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002918 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002919}
2920
Mathias Agopianac9fa422013-02-11 16:40:36 -08002921status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922{
Robert Carr9524cb32017-02-13 11:32:32 -08002923 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002924 status_t err = NO_ERROR;
2925 sp<Layer> l(client->getLayerUser(handle));
2926 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002927 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002928 err = removeLayer(l);
2929 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2930 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002931 }
2932 return err;
2933}
2934
Mathias Agopian13127d82013-03-05 17:47:11 -08002935status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002936{
Mathias Agopian67106042013-03-14 19:18:13 -07002937 // called by ~LayerCleaner() when all references to the IBinder (handle)
2938 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002939 sp<Layer> l = layer.promote();
2940 if (l == nullptr) {
2941 // The layer has already been removed, carry on
2942 return NO_ERROR;
2943 } if (l->getParent() != nullptr) {
2944 // If we have a parent, then we can continue to live as long as it does.
2945 return NO_ERROR;
2946 }
2947 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948}
2949
Mathias Agopianb60314a2012-04-10 22:09:54 -07002950// ---------------------------------------------------------------------------
2951
Andy McFadden13a082e2012-08-24 10:16:42 -07002952void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002953 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002954 Vector<ComposerState> state;
2955 Vector<DisplayState> displays;
2956 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002957 d.what = DisplayState::eDisplayProjectionChanged |
2958 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002959 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002960 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002961 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002962 d.frame.makeInvalid();
2963 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002964 d.width = 0;
2965 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002966 displays.add(d);
2967 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002968 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002969
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2971 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002972 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002973
2974 {
2975 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2976 mCompositorTiming.interval = period;
2977 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002978}
2979
2980void SurfaceFlinger::initializeDisplays() {
2981 class MessageScreenInitialized : public MessageBase {
2982 SurfaceFlinger* flinger;
2983 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002984 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002985 virtual bool handler() {
2986 flinger->onInitializeDisplays();
2987 return true;
2988 }
2989 };
2990 sp<MessageBase> msg = new MessageScreenInitialized(this);
2991 postMessageAsync(msg); // we may be called from main thread, use async message
2992}
2993
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002994void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2995 int mode) {
2996 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2997 this);
2998 int32_t type = hw->getDisplayType();
2999 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003000
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003001 if (mode == currentMode) {
3002 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003003 return;
3004 }
3005
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 hw->setPowerMode(mode);
3007 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3008 ALOGW("Trying to set power mode for virtual display");
3009 return;
3010 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003011
Irvelffc9efc2016-07-27 15:16:37 -07003012 if (mInterceptor.isEnabled()) {
3013 Mutex::Autolock _l(mStateLock);
3014 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3015 if (idx < 0) {
3016 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3017 return;
3018 }
3019 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3020 }
3021
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003022 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003023 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003024 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003025 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3026 // FIXME: eventthread only knows about the main display right now
3027 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003028 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003029 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003031 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003032 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003033 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003034
3035 struct sched_param param = {0};
3036 param.sched_priority = 1;
3037 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3038 ALOGW("Couldn't set SCHED_FIFO on display on");
3039 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003041 // Turn off the display
3042 struct sched_param param = {0};
3043 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3044 ALOGW("Couldn't set SCHED_OTHER on display off");
3045 }
3046
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003047 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003048 disableHardwareVsync(true); // also cancels any in-progress resync
3049
Mathias Agopiancde87a32012-09-13 14:09:01 -07003050 // FIXME: eventthread only knows about the main display right now
3051 mEventThread->onScreenReleased();
3052 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003053
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003054 getHwComposer().setPowerMode(type, mode);
3055 mVisibleRegionsDirty = true;
3056 // from this point on, SF will stop drawing on this display
3057 } else {
3058 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003059 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003060}
3061
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003062void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3063 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003064 SurfaceFlinger& mFlinger;
3065 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003066 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003068 MessageSetPowerMode(SurfaceFlinger& flinger,
3069 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3070 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003071 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003072 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003073 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003075 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003076 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003077 ALOGW("Attempt to set power mode = %d for virtual display",
3078 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003079 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003080 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003081 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003082 return true;
3083 }
3084 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003085 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003086 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003087}
3088
3089// ---------------------------------------------------------------------------
3090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3092{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003094
Mathias Agopianbd115332013-04-18 16:41:04 -07003095 IPCThreadState* ipc = IPCThreadState::self();
3096 const int pid = ipc->getCallingPid();
3097 const int uid = ipc->getCallingUid();
3098 if ((uid != AID_SHELL) &&
3099 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003100 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003101 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003103 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003104 // (this would indicate SF is stuck, but we want to be able to
3105 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003106 status_t err = mStateLock.timedLock(s2ns(1));
3107 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003108 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003109 result.appendFormat(
3110 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3111 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003112 }
3113
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003114 bool dumpAll = true;
3115 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003116 size_t numArgs = args.size();
3117 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003118 if ((index < numArgs) &&
3119 (args[index] == String16("--list"))) {
3120 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003121 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003122 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003123 }
3124
3125 if ((index < numArgs) &&
3126 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003127 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003128 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003129 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003130 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003131
3132 if ((index < numArgs) &&
3133 (args[index] == String16("--latency-clear"))) {
3134 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003135 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003136 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003137 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003138
3139 if ((index < numArgs) &&
3140 (args[index] == String16("--dispsync"))) {
3141 index++;
3142 mPrimaryDispSync.dump(result);
3143 dumpAll = false;
3144 }
Dan Stozab90cf072015-03-05 11:05:59 -08003145
3146 if ((index < numArgs) &&
3147 (args[index] == String16("--static-screen"))) {
3148 index++;
3149 dumpStaticScreenStats(result);
3150 dumpAll = false;
3151 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003152
3153 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003154 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003155 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003156 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003157 dumpAll = false;
3158 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003160
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003161 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003162 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003163 }
3164
Mathias Agopian9795c422009-08-26 16:36:26 -07003165 if (locked) {
3166 mStateLock.unlock();
3167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 write(fd, result.string(), result.size());
3170 return NO_ERROR;
3171}
3172
Dan Stozac7014012014-02-14 15:03:43 -08003173void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3174 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003175{
Robert Carr2047fae2016-11-28 14:09:09 -08003176 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003177 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003178 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003179}
3180
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003181void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003182 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003183{
3184 String8 name;
3185 if (index < args.size()) {
3186 name = String8(args[index]);
3187 index++;
3188 }
3189
Dan Stoza9e56aa02015-11-02 13:00:03 -08003190 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3191 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003192 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003193
3194 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003195 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003196 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003197 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003198 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003199 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003200 }
Robert Carr2047fae2016-11-28 14:09:09 -08003201 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003202 }
3203}
3204
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003205void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003206 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003207{
3208 String8 name;
3209 if (index < args.size()) {
3210 name = String8(args[index]);
3211 index++;
3212 }
3213
Robert Carr2047fae2016-11-28 14:09:09 -08003214 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003215 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003216 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003217 }
Robert Carr2047fae2016-11-28 14:09:09 -08003218 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003219
Svetoslavd85084b2014-03-20 10:28:31 -07003220 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003221}
3222
Jamie Gennis6547ff42013-07-16 20:12:42 -07003223// This should only be called from the main thread. Otherwise it would need
3224// the lock and should use mCurrentState rather than mDrawingState.
3225void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003227 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003228 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003229
3230 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3231}
3232
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003233void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003234{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003235 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003236#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003237 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003238#endif
3239#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003240 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003241#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003242 if (isLayerTripleBufferingDisabled())
3243 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003244 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003245}
3246
Dan Stozab90cf072015-03-05 11:05:59 -08003247void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3248{
3249 result.appendFormat("Static screen stats:\n");
3250 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3251 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3252 float percent = 100.0f *
3253 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3254 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3255 b + 1, bucketTimeSec, percent);
3256 }
3257 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3258 float percent = 100.0f *
3259 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3260 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3261 NUM_BUCKETS - 1, bucketTimeSec, percent);
3262}
3263
Dan Stozae77c7662016-05-13 11:37:28 -07003264void SurfaceFlinger::recordBufferingStats(const char* layerName,
3265 std::vector<OccupancyTracker::Segment>&& history) {
3266 Mutex::Autolock lock(mBufferingStatsMutex);
3267 auto& stats = mBufferingStats[layerName];
3268 for (const auto& segment : history) {
3269 if (!segment.usedThirdBuffer) {
3270 stats.twoBufferTime += segment.totalTime;
3271 }
3272 if (segment.occupancyAverage < 1.0f) {
3273 stats.doubleBufferedTime += segment.totalTime;
3274 } else if (segment.occupancyAverage < 2.0f) {
3275 stats.tripleBufferedTime += segment.totalTime;
3276 }
3277 ++stats.numSegments;
3278 stats.totalTime += segment.totalTime;
3279 }
3280}
3281
Brian Andersond6927fb2016-07-23 23:37:30 -07003282void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3283 result.appendFormat("Layer frame timestamps:\n");
3284
3285 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3286 const size_t count = currentLayers.size();
3287 for (size_t i=0 ; i<count ; i++) {
3288 currentLayers[i]->dumpFrameEvents(result);
3289 }
3290}
3291
Dan Stozae77c7662016-05-13 11:37:28 -07003292void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3293 result.append("Buffering stats:\n");
3294 result.append(" [Layer name] <Active time> <Two buffer> "
3295 "<Double buffered> <Triple buffered>\n");
3296 Mutex::Autolock lock(mBufferingStatsMutex);
3297 typedef std::tuple<std::string, float, float, float> BufferTuple;
3298 std::map<float, BufferTuple, std::greater<float>> sorted;
3299 for (const auto& statsPair : mBufferingStats) {
3300 const char* name = statsPair.first.c_str();
3301 const BufferingStats& stats = statsPair.second;
3302 if (stats.numSegments == 0) {
3303 continue;
3304 }
3305 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3306 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3307 stats.totalTime;
3308 float doubleBufferRatio = static_cast<float>(
3309 stats.doubleBufferedTime) / stats.totalTime;
3310 float tripleBufferRatio = static_cast<float>(
3311 stats.tripleBufferedTime) / stats.totalTime;
3312 sorted.insert({activeTime, {name, twoBufferRatio,
3313 doubleBufferRatio, tripleBufferRatio}});
3314 }
3315 for (const auto& sortedPair : sorted) {
3316 float activeTime = sortedPair.first;
3317 const BufferTuple& values = sortedPair.second;
3318 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3319 std::get<0>(values).c_str(), activeTime,
3320 std::get<1>(values), std::get<2>(values),
3321 std::get<3>(values));
3322 }
3323 result.append("\n");
3324}
3325
3326
Mathias Agopian74d211a2013-04-22 16:55:35 +02003327void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3328 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003329{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003330 bool colorize = false;
3331 if (index < args.size()
3332 && (args[index] == String16("--color"))) {
3333 colorize = true;
3334 index++;
3335 }
3336
3337 Colorizer colorizer(colorize);
3338
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003339 // figure out if we're stuck somewhere
3340 const nsecs_t now = systemTime();
3341 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3342 const nsecs_t inTransaction(mDebugInTransaction);
3343 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3344 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3345
3346 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003347 * Dump library configuration.
3348 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003349
3350 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003351 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003352 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003353 appendSfConfigString(result);
3354 appendUiConfigString(result);
3355 appendGuiConfigString(result);
3356 result.append("\n");
3357
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003358 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003359 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003361 result.append(SyncFeatures::getInstance().toString());
3362 result.append("\n");
3363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3365
Andy McFadden41d67d72014-04-25 16:58:34 -07003366 colorizer.bold(result);
3367 result.append("DispSync configuration: ");
3368 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003369 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3370 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003371 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3372 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003373 result.append("\n");
3374
Dan Stozab90cf072015-03-05 11:05:59 -08003375 // Dump static screen stats
3376 result.append("\n");
3377 dumpStaticScreenStats(result);
3378 result.append("\n");
3379
Dan Stozae77c7662016-05-13 11:37:28 -07003380 dumpBufferingStats(result);
3381
Andy McFadden4803b742012-09-24 19:07:20 -07003382 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003383 * Dump the visible layer list
3384 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003386 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003387 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003388 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003389 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003390 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003391
3392 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003393 * Dump Display state
3394 */
3395
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003396 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003397 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003398 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003399 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3400 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003402 }
3403
3404 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405 * Dump SurfaceFlinger global state
3406 */
3407
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003408 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003409 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003410 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411
Mathias Agopian888c8222012-08-04 21:10:38 -07003412 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003413 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003414
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003415 colorizer.bold(result);
3416 result.appendFormat("EGL implementation : %s\n",
3417 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3418 colorizer.reset(result);
3419 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003420 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003421
Mathias Agopian875d8e12013-06-07 15:35:48 -07003422 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423
Mathias Agopian42977342012-08-05 00:40:46 -07003424 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003425 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3426 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003427 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428 " last eglSwapBuffers() time: %f us\n"
3429 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003430 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431 " refresh-rate : %f fps\n"
3432 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003433 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003434 " gpu_to_cpu_unsupported : %d\n"
3435 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436 mLastSwapBufferTime/1000.0,
3437 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003438 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003439 1e9 / activeConfig->getVsyncPeriod(),
3440 activeConfig->getDpiX(),
3441 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003442 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443
Mathias Agopian74d211a2013-04-22 16:55:35 +02003444 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003445 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003446
Mathias Agopian74d211a2013-04-22 16:55:35 +02003447 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003449
3450 /*
3451 * VSYNC state
3452 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003454 result.append("\n");
3455
3456 /*
3457 * HWC layer minidump
3458 */
3459 for (size_t d = 0; d < mDisplays.size(); d++) {
3460 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3461 int32_t hwcId = displayDevice->getHwcDisplayId();
3462 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3463 continue;
3464 }
3465
3466 result.appendFormat("Display %d HWC layers:\n", hwcId);
3467 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003468 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003469 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003470 });
Dan Stozae22aec72016-08-01 13:20:59 -07003471 result.append("\n");
3472 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003473
3474 /*
3475 * Dump HWComposer state
3476 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003477 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003478 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003479 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003480 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003481 result.appendFormat(" h/w composer %s\n",
3482 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003483 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003484
3485 /*
3486 * Dump gralloc state
3487 */
3488 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3489 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003490}
3491
Mathias Agopian13127d82013-03-05 17:47:11 -08003492const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003493SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003494 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003495 wp<IBinder> dpy;
3496 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3497 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3498 dpy = mDisplays.keyAt(i);
3499 break;
3500 }
3501 }
3502 if (dpy == NULL) {
3503 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3504 // Just use the primary display so we have something to return
3505 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3506 }
3507 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003508}
3509
Keun young Park63f165f2012-08-31 10:53:36 -07003510bool SurfaceFlinger::startDdmConnection()
3511{
3512 void* libddmconnection_dso =
3513 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3514 if (!libddmconnection_dso) {
3515 return false;
3516 }
3517 void (*DdmConnection_start)(const char* name);
3518 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003519 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003520 if (!DdmConnection_start) {
3521 dlclose(libddmconnection_dso);
3522 return false;
3523 }
3524 (*DdmConnection_start)(getServiceName());
3525 return true;
3526}
3527
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003528status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 switch (code) {
3530 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003531 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003533 case CLEAR_ANIMATION_FRAME_STATS:
3534 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003535 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003536 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 {
3538 // codes that require permission check
3539 IPCThreadState* ipc = IPCThreadState::self();
3540 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003541 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003542 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003543 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003544 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003545 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003547 break;
3548 }
Robert Carr1db73f62016-12-21 12:58:51 -08003549 /*
3550 * Calling setTransactionState is safe, because you need to have been
3551 * granted a reference to Client* and Handle* to do anything with it.
3552 *
3553 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3554 */
3555 case SET_TRANSACTION_STATE:
3556 case CREATE_SCOPED_CONNECTION:
3557 {
3558 return OK;
3559 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003560 case CAPTURE_SCREEN:
3561 {
3562 // codes that require permission check
3563 IPCThreadState* ipc = IPCThreadState::self();
3564 const int pid = ipc->getCallingPid();
3565 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003566 if ((uid != AID_GRAPHICS) &&
3567 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003568 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003569 return PERMISSION_DENIED;
3570 }
3571 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003574 return OK;
3575}
3576
3577status_t SurfaceFlinger::onTransact(
3578 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3579{
3580 status_t credentialCheck = CheckTransactCodeCredentials(code);
3581 if (credentialCheck != OK) {
3582 return credentialCheck;
3583 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3586 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003587 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003588 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003589 IPCThreadState* ipc = IPCThreadState::self();
3590 const int pid = ipc->getCallingPid();
3591 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003592 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003593 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 return PERMISSION_DENIED;
3595 }
3596 int n;
3597 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003598 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003599 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 return NO_ERROR;
3601 case 1002: // SHOW_UPDATES
3602 n = data.readInt32();
3603 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003604 invalidateHwcGeometry();
3605 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003608 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003611 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003612 setTransactionFlags(
3613 eTransactionNeeded|
3614 eDisplayTransactionNeeded|
3615 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003616 return NO_ERROR;
3617 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003618 case 1006:{ // send empty update
3619 signalRefresh();
3620 return NO_ERROR;
3621 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003622 case 1008: // toggle use of hw composer
3623 n = data.readInt32();
3624 mDebugDisableHWC = n ? 1 : 0;
3625 invalidateHwcGeometry();
3626 repaintEverything();
3627 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003628 case 1009: // toggle use of transform hint
3629 n = data.readInt32();
3630 mDebugDisableTransformHint = n ? 1 : 0;
3631 invalidateHwcGeometry();
3632 repaintEverything();
3633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003635 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 reply->writeInt32(0);
3637 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003638 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003639 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640 return NO_ERROR;
3641 case 1013: {
3642 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003643 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3644 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003645 return NO_ERROR;
3646 }
3647 case 1014: {
3648 // daltonize
3649 n = data.readInt32();
3650 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003651 case 1:
3652 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3653 break;
3654 case 2:
3655 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3656 break;
3657 case 3:
3658 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3659 break;
3660 default:
3661 mDaltonizer.setType(ColorBlindnessType::None);
3662 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003663 }
3664 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003665 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003666 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003667 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003668 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003669 invalidateHwcGeometry();
3670 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003671 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003673 case 1015: {
3674 // apply a color matrix
3675 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003676 if (n) {
3677 // color matrix is sent as mat3 matrix followed by vec3
3678 // offset, then packed into a mat4 where the last row is
3679 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003680 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003681 for (size_t j = 0; j < 4; j++) {
3682 mColorMatrix[i][j] = data.readFloat();
3683 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003684 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003685 } else {
3686 mColorMatrix = mat4();
3687 }
3688 invalidateHwcGeometry();
3689 repaintEverything();
3690 return NO_ERROR;
3691 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003692 // This is an experimental interface
3693 // Needs to be shifted to proper binder interface when we productize
3694 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003695 n = data.readInt32();
3696 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003697 return NO_ERROR;
3698 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003699 case 1017: {
3700 n = data.readInt32();
3701 mForceFullDamage = static_cast<bool>(n);
3702 return NO_ERROR;
3703 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003704 case 1018: { // Modify Choreographer's phase offset
3705 n = data.readInt32();
3706 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3707 return NO_ERROR;
3708 }
3709 case 1019: { // Modify SurfaceFlinger's phase offset
3710 n = data.readInt32();
3711 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3712 return NO_ERROR;
3713 }
Irvel468051e2016-06-13 16:44:44 -07003714 case 1020: { // Layer updates interceptor
3715 n = data.readInt32();
3716 if (n) {
3717 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003718 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003719 }
3720 else{
3721 ALOGV("Interceptor disabled");
3722 mInterceptor.disable();
3723 }
3724 return NO_ERROR;
3725 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003726 case 1021: { // Disable HWC virtual displays
3727 n = data.readInt32();
3728 mUseHwcVirtualDisplays = !n;
3729 return NO_ERROR;
3730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 }
3732 }
3733 return err;
3734}
3735
Mathias Agopian53331da2011-08-22 21:44:41 -07003736void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003737 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003738 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003739}
3740
Mathias Agopian59119e62010-10-11 12:37:43 -07003741// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003742// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003743// ---------------------------------------------------------------------------
3744
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003745/* The code below is here to handle b/8734824
3746 *
3747 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003748 * from the surfaceflinger thread to the calling binder thread, where they
3749 * are executed. This allows the calling thread in the calling process to be
3750 * reused and not depend on having "enough" binder threads to handle the
3751 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003752 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003754 /* Parts of GraphicProducerWrapper are run on two different threads,
3755 * communicating by sending messages via Looper but also by shared member
3756 * data. Coherence maintenance is subtle and in places implicit (ugh).
3757 *
3758 * Don't rely on Looper's sendMessage/handleMessage providing
3759 * release/acquire semantics for any data not actually in the Message.
3760 * Data going from surfaceflinger to binder threads needs to be
3761 * synchronized explicitly.
3762 *
3763 * Barrier open/wait do provide release/acquire semantics. This provides
3764 * implicit synchronization for data coming back from binder to
3765 * surfaceflinger threads.
3766 */
3767
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003768 sp<IGraphicBufferProducer> impl;
3769 sp<Looper> looper;
3770 status_t result;
3771 bool exitPending;
3772 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003773 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003774 uint32_t code;
3775 Parcel const* data;
3776 Parcel* reply;
3777
3778 enum {
3779 MSG_API_CALL,
3780 MSG_EXIT
3781 };
3782
3783 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003784 * Called on surfaceflinger thread. This is called by our "fake"
3785 * BpGraphicBufferProducer. We package the data and reply Parcel and
3786 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 */
3788 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003789 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003790 this->code = code;
3791 this->data = &data;
3792 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003794 // if we've exited, we run the message synchronously right here.
3795 // note (JH): as far as I can tell from looking at the code, this
3796 // never actually happens. if it does, i'm not sure if it happens
3797 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 handleMessage(Message(MSG_API_CALL));
3799 } else {
3800 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003801 // Prevent stores to this->{code, data, reply} from being
3802 // reordered later than the construction of Message.
3803 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003804 looper->sendMessage(this, Message(MSG_API_CALL));
3805 barrier.wait();
3806 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003807 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003808 }
3809
3810 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003811 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 * call the real BpGraphicBufferProducer.
3813 */
3814 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003815 int what = message.what;
3816 // Prevent reads below from happening before the read from Message
3817 atomic_thread_fence(memory_order_acquire);
3818 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003819 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003821 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 exitRequested = true;
3823 }
3824 }
3825
3826public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003827 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003828 : impl(impl),
3829 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003830 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003831 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003832 exitRequested(false),
3833 code(0),
3834 data(NULL),
3835 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003836 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003837
Jesse Hallb154c422014-07-13 12:47:02 -07003838 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003839 status_t waitForResponse() {
3840 do {
3841 looper->pollOnce(-1);
3842 } while (!exitRequested);
3843 return result;
3844 }
3845
Jesse Hallb154c422014-07-13 12:47:02 -07003846 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003847 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003848 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003849 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003850 // Ensure this->result is visible to the binder thread before it
3851 // handles the message.
3852 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003853 looper->sendMessage(this, Message(MSG_EXIT));
3854 }
3855};
3856
3857
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003858status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3859 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003860 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003861 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003862 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003863
3864 if (CC_UNLIKELY(display == 0))
3865 return BAD_VALUE;
3866
3867 if (CC_UNLIKELY(producer == 0))
3868 return BAD_VALUE;
3869
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003870 // if we have secure windows on this display, never allow the screen capture
3871 // unless the producer interface is local (i.e.: we can take a screenshot for
3872 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003873 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003874
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003875 // Convert to surfaceflinger's internal rotation type.
3876 Transform::orientation_flags rotationFlags;
3877 switch (rotation) {
3878 case ISurfaceComposer::eRotateNone:
3879 rotationFlags = Transform::ROT_0;
3880 break;
3881 case ISurfaceComposer::eRotate90:
3882 rotationFlags = Transform::ROT_90;
3883 break;
3884 case ISurfaceComposer::eRotate180:
3885 rotationFlags = Transform::ROT_180;
3886 break;
3887 case ISurfaceComposer::eRotate270:
3888 rotationFlags = Transform::ROT_270;
3889 break;
3890 default:
3891 rotationFlags = Transform::ROT_0;
3892 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3893 break;
3894 }
3895
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003896 class MessageCaptureScreen : public MessageBase {
3897 SurfaceFlinger* flinger;
3898 sp<IBinder> display;
3899 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003900 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003901 uint32_t reqWidth, reqHeight;
3902 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003903 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003904 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003905 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003906 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 public:
3908 MessageCaptureScreen(SurfaceFlinger* flinger,
3909 const sp<IBinder>& display,
3910 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003911 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003912 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003913 bool useIdentityTransform,
3914 Transform::orientation_flags rotation,
3915 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003916 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003917 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003918 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003919 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003920 rotation(rotation), result(PERMISSION_DENIED),
3921 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003922 {
3923 }
3924 status_t getResult() const {
3925 return result;
3926 }
3927 virtual bool handler() {
3928 Mutex::Autolock _l(flinger->mStateLock);
3929 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003930 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003931 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003932 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003933 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003934 return true;
3935 }
3936 };
3937
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938 // this creates a "fake" BBinder which will serve as a "fake" remote
3939 // binder to receive the marshaled calls and forward them to the
3940 // real remote (a BpGraphicBufferProducer)
3941 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3942
3943 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3944 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003945 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003947 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003948 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003949
3950 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003951 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003952 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003953 }
3954 return res;
3955}
3956
Mathias Agopian180f10d2013-04-10 22:55:41 -07003957
3958void SurfaceFlinger::renderScreenImplLocked(
3959 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003960 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003961 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003962 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003963{
3964 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003965 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003966
3967 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003968 const int32_t hw_w = hw->getWidth();
3969 const int32_t hw_h = hw->getHeight();
3970 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003971 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003972
Dan Stozac1879002014-05-22 15:59:05 -07003973 // if a default or invalid sourceCrop is passed in, set reasonable values
3974 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3975 !sourceCrop.isValid()) {
3976 sourceCrop.setLeftTop(Point(0, 0));
3977 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3978 }
3979
3980 // ensure that sourceCrop is inside screen
3981 if (sourceCrop.left < 0) {
3982 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3983 }
Dan Stozabe31f442014-06-11 11:20:54 -07003984 if (sourceCrop.right > hw_w) {
3985 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003986 }
3987 if (sourceCrop.top < 0) {
3988 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3989 }
Dan Stozabe31f442014-06-11 11:20:54 -07003990 if (sourceCrop.bottom > hw_h) {
3991 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003992 }
3993
Mathias Agopian180f10d2013-04-10 22:55:41 -07003994 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003995 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003996
3997 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003998 engine.setViewportAndProjection(
3999 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004000 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001
4002 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004003 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004004
Robert Carr1f0a16a2016-10-24 16:27:39 -07004005 // We loop through the first level of layers without traversing,
4006 // as we need to interpret min/max layer Z in the top level Z space.
4007 for (const auto& layer : mDrawingState.layersSortedByZ) {
4008 if (layer->getLayerStack() != hw->getLayerStack()) {
4009 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004010 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004011 const Layer::State& state(layer->getDrawingState());
4012 if (state.z < minLayerZ || state.z > maxLayerZ) {
4013 continue;
4014 }
4015 layer->traverseInZOrder([&](Layer* layer) {
4016 if (!layer->isVisible()) {
4017 return;
4018 }
4019 if (filtering) layer->setFiltering(true);
4020 layer->draw(hw, useIdentityTransform);
4021 if (filtering) layer->setFiltering(false);
4022 });
4023 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004024
Mathias Agopian931bda12013-08-28 18:11:46 -07004025 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004026}
4027
4028
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004029status_t SurfaceFlinger::captureScreenImplLocked(
4030 const sp<const DisplayDevice>& hw,
4031 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004032 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004033 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004034 bool useIdentityTransform, Transform::orientation_flags rotation,
4035 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004036{
4037 ATRACE_CALL();
4038
Mathias Agopian180f10d2013-04-10 22:55:41 -07004039 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004040 uint32_t hw_w = hw->getWidth();
4041 uint32_t hw_h = hw->getHeight();
4042
4043 if (rotation & Transform::ROT_90) {
4044 std::swap(hw_w, hw_h);
4045 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004046
Mathias Agopian180f10d2013-04-10 22:55:41 -07004047 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4048 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4049 reqWidth, reqHeight, hw_w, hw_h);
4050 return BAD_VALUE;
4051 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004052
Mathias Agopian180f10d2013-04-10 22:55:41 -07004053 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4054 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4055
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004056 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004057 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004058 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004059 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4060 (state.z < minLayerZ || state.z > maxLayerZ)) {
4061 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004062 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004063 layer->traverseInZOrder([&](Layer *layer) {
4064 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4065 layer->isSecure());
4066 });
4067 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004068
4069 if (!isLocalScreenshot && secureLayerIsVisible) {
4070 ALOGW("FB is protected: PERMISSION_DENIED");
4071 return PERMISSION_DENIED;
4072 }
4073
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 // create a surface (because we're a producer, and we need to
4075 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004076 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004077
4078 // Put the screenshot Surface into async mode so that
4079 // Layer::headFenceHasSignaled will always return true and we'll latch the
4080 // first buffer regardless of whether or not its acquire fence has
4081 // signaled. This is needed to avoid a race condition in the rotation
4082 // animation. See b/30209608
4083 sur->setAsyncMode(true);
4084
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004085 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004086
Michael Lentine5a16a622015-05-21 13:48:24 -07004087 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4088 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004089 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4090 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004091
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004092 int err = 0;
4093 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004094 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004095 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4096 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004097
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004098 if (err == NO_ERROR) {
4099 ANativeWindowBuffer* buffer;
4100 /* TODO: Once we have the sync framework everywhere this can use
4101 * server-side waits on the fence that dequeueBuffer returns.
4102 */
4103 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4104 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004105 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004106 // create an EGLImage from the buffer so we can later
4107 // turn it into a texture
4108 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4109 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4110 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004111 // this binds the given EGLImage as a framebuffer for the
4112 // duration of this scope.
4113 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4114 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004115 // this will in fact render into our dequeued buffer
4116 // via an FBO, which means we didn't have to create
4117 // an EGLSurface and therefore we're not
4118 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004119 renderScreenImplLocked(
4120 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4121 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004122
Riley Andrews86639902014-08-15 12:27:24 -07004123 // Attempt to create a sync khr object that can produce a sync point. If that
4124 // isn't available, create a non-dupable sync object in the fallback path and
4125 // wait on it directly.
4126 EGLSyncKHR sync;
4127 if (!DEBUG_SCREENSHOTS) {
4128 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004129 // native fence fd will not be populated until flush() is done.
4130 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004131 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004132 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004133 }
Riley Andrews86639902014-08-15 12:27:24 -07004134 if (sync != EGL_NO_SYNC_KHR) {
4135 // get the sync fd
4136 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4137 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4138 ALOGW("captureScreen: failed to dup sync khr object");
4139 syncFd = -1;
4140 }
4141 eglDestroySyncKHR(mEGLDisplay, sync);
4142 } else {
4143 // fallback path
4144 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4145 if (sync != EGL_NO_SYNC_KHR) {
4146 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4147 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4148 EGLint eglErr = eglGetError();
4149 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4150 ALOGW("captureScreen: fence wait timed out");
4151 } else {
4152 ALOGW_IF(eglErr != EGL_SUCCESS,
4153 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4154 }
4155 eglDestroySyncKHR(mEGLDisplay, sync);
4156 } else {
4157 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4158 }
4159 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004160 if (DEBUG_SCREENSHOTS) {
4161 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4162 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4163 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4164 hw, minLayerZ, maxLayerZ);
4165 delete [] pixels;
4166 }
4167
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004168 } else {
4169 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4170 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004171 window->cancelBuffer(window, buffer, syncFd);
4172 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004173 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004174 // destroy our image
4175 eglDestroyImageKHR(mEGLDisplay, image);
4176 } else {
4177 result = BAD_VALUE;
4178 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004179 if (buffer) {
4180 // queueBuffer takes ownership of syncFd
4181 result = window->queueBuffer(window, buffer, syncFd);
4182 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004183 }
4184 } else {
4185 result = BAD_VALUE;
4186 }
4187 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4188 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004189
Mathias Agopian74c40c02010-09-29 13:02:36 -07004190 return result;
4191}
4192
Mathias Agopiand5556842013-09-19 17:08:37 -07004193void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004194 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004196 for (size_t y=0 ; y<h ; y++) {
4197 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4198 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004199 if (p[x] != 0xFF000000) return;
4200 }
4201 }
4202 ALOGE("*** we just took a black screenshot ***\n"
4203 "requested minz=%d, maxz=%d, layerStack=%d",
4204 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205
Robert Carr2047fae2016-11-28 14:09:09 -08004206 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004207 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004208 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004209 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4210 state.z <= maxLayerZ) {
4211 layer->traverseInZOrder([&](Layer* layer) {
4212 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4213 layer->isVisible() ? '+' : '-',
4214 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004215 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004216 i++;
4217 });
4218 }
4219 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004220 }
4221}
4222
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004223// ---------------------------------------------------------------------------
4224
Robert Carr2047fae2016-11-28 14:09:09 -08004225void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4226 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004227}
4228
Robert Carr2047fae2016-11-28 14:09:09 -08004229void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4230 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004231}
4232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004234
4235
4236#if defined(__gl_h_)
4237#error "don't include gl/gl.h in this file"
4238#endif
4239
4240#if defined(__gl2_h_)
4241#error "don't include gl2/gl2.h in this file"
4242#endif