blob: 2f354bb47a93f463f612d49e928b982ab60d46f2 [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070043#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080048#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080077#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopiana4912602012-07-12 14:25:33 -070079#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070080#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070081#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include "Effects/Daltonizer.h"
84
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070087
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090089#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106// This is the phase offset in nanoseconds of the software vsync event
107// relative to the vsync event reported by HWComposer. The software vsync
108// event is when SurfaceFlinger and Choreographer-based applications run each
109// frame.
110//
111// This phase offset allows adjustment of the minimum latency from application
112// wake-up (by Choregographer) time to the time at which the resulting window
113// image is displayed. This value may be either positive (after the HW vsync)
114// or negative (before the HW vsync). Setting it to 0 will result in a
115// minimum latency of two vsync periods because the app and SurfaceFlinger
116// will run just after the HW vsync. Setting it to a positive number will
117// result in the minimum latency being:
118//
119// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
120//
121// Note that reducing this latency makes it more likely for the applications
122// to not have their window content image ready in time. When this happens
123// the latency will end up being an additional vsync period, and animations
124// will hiccup. Therefore, this latency should be tuned somewhat
125// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900126static int64_t vsyncPhaseOffsetNs = getInt64<
127 ISurfaceFlingerConfigs,
128 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700129
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700130// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800131static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133// ---------------------------------------------------------------------------
134
Mathias Agopian99b49842011-06-27 16:05:52 -0700135const String16 sHardwareTest("android.permission.HARDWARE_TEST");
136const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
137const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
138const String16 sDump("android.permission.DUMP");
139
140// ---------------------------------------------------------------------------
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700143 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700145 mTransactionPending(false),
146 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700147 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700148 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700149 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800150 mHwc(nullptr),
151 mRealHwc(nullptr),
152 mVrHwc(nullptr),
153 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800155 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800157 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800158 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800159 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700161 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700162 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700163 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700164 mDebugInSwapBuffers(0),
165 mLastSwapBufferTime(0),
166 mDebugInTransaction(0),
167 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700168 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700169 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800170 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000171 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700172 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700173 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800174 mHasColorMatrix(false),
175 mHasPoweredOff(false),
176 mFrameBuckets(),
177 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700178 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800179 mNumLayers(0)
180#ifdef USE_HWC2
181 ,mEnterVrMode(false)
182#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183{
Steve Blocka19954a2012-01-04 20:05:49 +0000184 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185
186 // debugging stuff...
187 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700188
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800189 // TODO (urbanus): remove once b/35319396 is fixed.
190 property_get("ro.boot.vr", value, "0");
191 mVrModeSupported = atoi(value);
192
Mathias Agopianb4b17302013-03-20 18:36:41 -0700193 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700194 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 property_get("debug.sf.showupdates", value, "0");
197 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700198
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199 property_get("debug.sf.ddms", value, "0");
200 mDebugDDMS = atoi(value);
201 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700202 if (!startDdmConnection()) {
203 // start failed, and DDMS debugging not enabled
204 mDebugDDMS = 0;
205 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700207 ALOGI_IF(mDebugRegion, "showupdates enabled");
208 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700209
210 property_get("debug.sf.disable_backpressure", value, "0");
211 mPropagateBackpressure = !atoi(value);
212 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700213
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800214 property_get("debug.sf.enable_hwc_vds", value, "0");
215 mUseHwcVirtualDisplays = atoi(value);
216 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800217
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800218 property_get("ro.sf.disable_triple_buffer", value, "1");
219 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800220 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221}
222
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800223void SurfaceFlinger::onFirstRef()
224{
225 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800226}
227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228SurfaceFlinger::~SurfaceFlinger()
229{
Mathias Agopiana4912602012-07-12 14:25:33 -0700230 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
231 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
232 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800233
234 if (mVrStateCallbacks.get()) {
235 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
236 defaultServiceManager()->checkService(String16("vrmanager")));
237 if (vrManagerService.get()) {
238 vrManagerService->unregisterListener(mVrStateCallbacks);
239 }
240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241}
242
Dan Stozac7014012014-02-14 15:03:43 -0800243void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800244{
245 // the window manager died on us. prepare its eulogy.
246
Andy McFadden13a082e2012-08-24 10:16:42 -0700247 // restore initial conditions (default device unblank, etc)
248 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800249
250 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700251 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252}
253
Robert Carr1db73f62016-12-21 12:58:51 -0800254static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700255 status_t err = client->initCheck();
256 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 }
Robert Carr1db73f62016-12-21 12:58:51 -0800259 return nullptr;
260}
261
262sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
263 return initClient(new Client(this));
264}
265
266sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
267 const sp<IGraphicBufferProducer>& gbp) {
268 if (authenticateSurfaceTexture(gbp) == false) {
269 return nullptr;
270 }
271 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
272 if (layer == nullptr) {
273 return nullptr;
274 }
275
276 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277}
278
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700279sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
280 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281{
282 class DisplayToken : public BBinder {
283 sp<SurfaceFlinger> flinger;
284 virtual ~DisplayToken() {
285 // no more references, this display must be terminated
286 Mutex::Autolock _l(flinger->mStateLock);
287 flinger->mCurrentState.displays.removeItem(this);
288 flinger->setTransactionFlags(eDisplayTransactionNeeded);
289 }
290 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700291 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700292 : flinger(flinger) {
293 }
294 };
295
296 sp<BBinder> token = new DisplayToken(this);
297
298 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700299 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700300 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700302 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700303 return token;
304}
305
Jesse Hall6c913be2013-08-08 12:15:49 -0700306void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
307 Mutex::Autolock _l(mStateLock);
308
309 ssize_t idx = mCurrentState.displays.indexOfKey(display);
310 if (idx < 0) {
311 ALOGW("destroyDisplay: invalid display token");
312 return;
313 }
314
315 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
316 if (!info.isVirtualDisplay()) {
317 ALOGE("destroyDisplay called for non-virtual display");
318 return;
319 }
Irvelffc9efc2016-07-27 15:16:37 -0700320 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700321 mCurrentState.displays.removeItemsAt(idx);
322 setTransactionFlags(eDisplayTransactionNeeded);
323}
324
Jesse Hall692c7232012-11-08 15:41:56 -0800325void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800326 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800327 ALOGW_IF(mBuiltinDisplays[type],
328 "Overwriting display token for display type %d", type);
329 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800330 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700331 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800332 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700333 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800334}
335
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700337 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
339 return NULL;
340 }
Jesse Hall692c7232012-11-08 15:41:56 -0800341 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700342}
343
Jamie Gennis9a78c902011-01-12 18:30:40 -0800344sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
345{
346 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
347 return gba;
348}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350void SurfaceFlinger::bootFinished()
351{
Wei Wangb254fa32017-01-31 17:43:23 -0800352 if (mStartBootAnimThread->join() != NO_ERROR) {
353 ALOGE("Join StartBootAnimThread failed!");
354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355 const nsecs_t now = systemTime();
356 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000357 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700358 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359
360 // wait patiently for the window manager death
361 const String16 name("window");
362 sp<IBinder> window(defaultServiceManager()->getService(name));
363 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700364 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700365 }
366
367 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700368 // formerly we would just kill the process, but we now ask it to exit so it
369 // can choose where to stop the animation.
370 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700371
372 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
373 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
374 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800375
376 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
377 defaultServiceManager()->checkService(String16("vrmanager")));
378 if (vrManagerService.get()) {
379 mVrStateCallbacks = new VrStateCallbacks(*this);
380 vrManagerService->registerListener(mVrStateCallbacks);
381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382}
383
Mathias Agopian3f844832013-08-07 21:24:32 -0700384void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 RenderEngine& engine;
387 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700388 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
390 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700391 }
392 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394 return true;
395 }
396 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700397 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700398}
399
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700400class DispSyncSource : public VSyncSource, private DispSync::Callback {
401public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700402 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 const char* name) :
404 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700405 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700406 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000407 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
408 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700409 mDispSync(dispSync),
410 mCallbackMutex(),
411 mCallback(),
412 mVsyncMutex(),
413 mPhaseOffset(phaseOffset),
414 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700415
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 virtual ~DispSyncSource() {}
417
418 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700419 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000421 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700422 static_cast<DispSync::Callback*>(this));
423 if (err != NO_ERROR) {
424 ALOGE("error registering vsync callback: %s (%d)",
425 strerror(-err), err);
426 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700427 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 } else {
429 status_t err = mDispSync->removeEventListener(
430 static_cast<DispSync::Callback*>(this));
431 if (err != NO_ERROR) {
432 ALOGE("error unregistering vsync callback: %s (%d)",
433 strerror(-err), err);
434 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 }
439
440 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 mCallback = callback;
443 }
444
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 virtual void setPhaseOffset(nsecs_t phaseOffset) {
446 Mutex::Autolock lock(mVsyncMutex);
447
448 // Normalize phaseOffset to [0, period)
449 auto period = mDispSync->getPeriod();
450 phaseOffset %= period;
451 if (phaseOffset < 0) {
452 // If we're here, then phaseOffset is in (-period, 0). After this
453 // operation, it will be in (0, period)
454 phaseOffset += period;
455 }
456 mPhaseOffset = phaseOffset;
457
458 // If we're not enabled, we don't need to mess with the listeners
459 if (!mEnabled) {
460 return;
461 }
462
463 // Remove the listener with the old offset
464 status_t err = mDispSync->removeEventListener(
465 static_cast<DispSync::Callback*>(this));
466 if (err != NO_ERROR) {
467 ALOGE("error unregistering vsync callback: %s (%d)",
468 strerror(-err), err);
469 }
470
471 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000472 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 static_cast<DispSync::Callback*>(this));
474 if (err != NO_ERROR) {
475 ALOGE("error registering vsync callback: %s (%d)",
476 strerror(-err), err);
477 }
478 }
479
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480private:
481 virtual void onDispSyncEvent(nsecs_t when) {
482 sp<VSyncSource::Callback> callback;
483 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700484 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 callback = mCallback;
486
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700487 if (mTraceVsync) {
488 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700489 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700490 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700491 }
492
493 if (callback != NULL) {
494 callback->onVSyncEvent(when);
495 }
496 }
497
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 const char* const mName;
499
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 int mValue;
501
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700503 const String8 mVsyncOnLabel;
504 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700507
508 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700510
511 Mutex mVsyncMutex; // Protects the following
512 nsecs_t mPhaseOffset;
513 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514};
515
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700516class InjectVSyncSource : public VSyncSource {
517public:
518 InjectVSyncSource() {}
519
520 virtual ~InjectVSyncSource() {}
521
522 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
523 std::lock_guard<std::mutex> lock(mCallbackMutex);
524 mCallback = callback;
525 }
526
527 virtual void onInjectSyncEvent(nsecs_t when) {
528 std::lock_guard<std::mutex> lock(mCallbackMutex);
529 mCallback->onVSyncEvent(when);
530 }
531
532 virtual void setVSyncEnabled(bool) {}
533 virtual void setPhaseOffset(nsecs_t) {}
534
535private:
536 std::mutex mCallbackMutex; // Protects the following
537 sp<VSyncSource::Callback> mCallback;
538};
539
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700541 ALOGI( "SurfaceFlinger's main thread ready to run. "
542 "Initializing graphics H/W...");
543
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900544 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
545
Dan Stoza9e56aa02015-11-02 13:00:03 -0800546 { // Autolock scope
547 Mutex::Autolock _l(mStateLock);
548
549 // initialize EGL for the default display
550 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
551 eglInitialize(mEGLDisplay, NULL, NULL);
552
553 // start the EventThread
554 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
555 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700556 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800557 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
558 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700559 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800560 mEventQueue.setEventThread(mSFEventThread);
561
Tim Murrayacff43d2016-07-29 13:57:24 -0700562 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700563 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700564 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700565 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
566 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
567 }
568
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569 // Get a RenderEngine for the given display / config (can't fail)
570 mRenderEngine = RenderEngine::create(mEGLDisplay,
571 HAL_PIXEL_FORMAT_RGBA_8888);
572 }
573
574 // Drop the state lock while we initialize the hardware composer. We drop
575 // the lock because on creation, it will call back into SurfaceFlinger to
576 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800577 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800578 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800579 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
581
Jesse Hall692c7232012-11-08 15:41:56 -0800582 Mutex::Autolock _l(mStateLock);
583
Mathias Agopian875d8e12013-06-07 15:35:48 -0700584 // retrieve the EGL context that was selected/created
585 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700586
Mathias Agopianda27af92012-09-13 18:17:13 -0700587 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
588 "couldn't create EGLContext");
589
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 // make the GLContext current so that we can create textures when creating
591 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700592 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
593
Jamie Gennisd1700752013-10-14 12:22:52 -0700594 mEventControlThread = new EventControlThread(this);
595 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
596
Mathias Agopian92a979a2012-08-02 18:32:23 -0700597 // initialize our drawing state
598 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700599
Andy McFadden13a082e2012-08-24 10:16:42 -0700600 // set initial conditions (e.g. unblank default device)
601 initializeDisplays();
602
Dan Stoza4e637772016-07-28 13:31:51 -0700603 mRenderEngine->primeCache();
604
Wei Wangb254fa32017-01-31 17:43:23 -0800605 mStartBootAnimThread = new StartBootAnimThread();
606 if (mStartBootAnimThread->Start() != NO_ERROR) {
607 ALOGE("Run StartBootAnimThread failed!");
608 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800609
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700611}
612
Mathias Agopiana67e4182012-06-19 17:26:12 -0700613void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800614 // Start boot animation service by setting a property mailbox
615 // if property setting thread is already running, Start() will be just a NOP
616 mStartBootAnimThread->Start();
617 // Wait until property was set
618 if (mStartBootAnimThread->join() != NO_ERROR) {
619 ALOGE("Join StartBootAnimThread failed!");
620 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700621}
622
Mathias Agopian875d8e12013-06-07 15:35:48 -0700623size_t SurfaceFlinger::getMaxTextureSize() const {
624 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700625}
626
Mathias Agopian875d8e12013-06-07 15:35:48 -0700627size_t SurfaceFlinger::getMaxViewportDims() const {
628 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700629}
630
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800631// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800632
Jamie Gennis582270d2011-08-17 18:19:00 -0700633bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800634 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800635 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800636 return authenticateSurfaceTextureLocked(bufferProducer);
637}
638
639bool SurfaceFlinger::authenticateSurfaceTextureLocked(
640 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800641 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700642 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800643}
644
Brian Anderson069b3652016-07-22 10:32:47 -0700645status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700646 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700647 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700648 FrameEvent::REQUESTED_PRESENT,
649 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700650 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700651 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700652 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700653 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700654 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700655 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700656 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700657 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700658 };
659 return NO_ERROR;
660}
661
Dan Stoza7f7da322014-05-02 15:26:25 -0700662status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
663 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700664 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700665 return BAD_VALUE;
666 }
667
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500668 if (!display.get())
669 return NAME_NOT_FOUND;
670
Jesse Hall692c7232012-11-08 15:41:56 -0800671 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700672 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800673 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700674 type = i;
675 break;
676 }
677 }
678
679 if (type < 0) {
680 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700681 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700682
Mathias Agopian8b736f12012-08-13 17:54:26 -0700683 // TODO: Not sure if display density should handled by SF any longer
684 class Density {
685 static int getDensityFromProperty(char const* propName) {
686 char property[PROPERTY_VALUE_MAX];
687 int density = 0;
688 if (property_get(propName, property, NULL) > 0) {
689 density = atoi(property);
690 }
691 return density;
692 }
693 public:
694 static int getEmuDensity() {
695 return getDensityFromProperty("qemu.sf.lcd_density"); }
696 static int getBuildDensity() {
697 return getDensityFromProperty("ro.sf.lcd_density"); }
698 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700699
Dan Stoza7f7da322014-05-02 15:26:25 -0700700 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700701
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700703 DisplayInfo info = DisplayInfo();
704
Dan Stoza9e56aa02015-11-02 13:00:03 -0800705 float xdpi = hwConfig->getDpiX();
706 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700707
708 if (type == DisplayDevice::DISPLAY_PRIMARY) {
709 // The density of the device is provided by a build property
710 float density = Density::getBuildDensity() / 160.0f;
711 if (density == 0) {
712 // the build doesn't provide a density -- this is wrong!
713 // use xdpi instead
714 ALOGE("ro.sf.lcd_density must be defined as a build property");
715 density = xdpi / 160.0f;
716 }
717 if (Density::getEmuDensity()) {
718 // if "qemu.sf.lcd_density" is specified, it overrides everything
719 xdpi = ydpi = density = Density::getEmuDensity();
720 density /= 160.0f;
721 }
722 info.density = density;
723
724 // TODO: this needs to go away (currently needed only by webkit)
725 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
726 info.orientation = hw->getOrientation();
727 } else {
728 // TODO: where should this value come from?
729 static const int TV_DENSITY = 213;
730 info.density = TV_DENSITY / 160.0f;
731 info.orientation = 0;
732 }
733
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734 info.w = hwConfig->getWidth();
735 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700736 info.xdpi = xdpi;
737 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800738 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900739 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740
Andy McFadden91b2ca82014-06-13 14:04:23 -0700741 // This is how far in advance a buffer must be queued for
742 // presentation at a given time. If you want a buffer to appear
743 // on the screen at time N, you must submit the buffer before
744 // (N - presentationDeadline).
745 //
746 // Normally it's one full refresh period (to give SF a chance to
747 // latch the buffer), but this can be reduced by configuring a
748 // DispSync offset. Any additional delays introduced by the hardware
749 // composer or panel must be accounted for here.
750 //
751 // We add an additional 1ms to allow for processing time and
752 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 info.presentationDeadline = hwConfig->getVsyncPeriod() -
754 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700755
756 // All non-virtual displays are currently considered secure.
757 info.secure = true;
758
Michael Wright28f24d02016-07-12 13:30:53 -0700759 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 }
761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 return NO_ERROR;
763}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700764
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800765status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700766 DisplayStatInfo* stats) {
767 if (stats == NULL) {
768 return BAD_VALUE;
769 }
770
771 // FIXME for now we always return stats for the primary display
772 memset(stats, 0, sizeof(*stats));
773 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
774 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
775 return NO_ERROR;
776}
777
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700778int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800779 if (display == NULL) {
780 ALOGE("%s : display is NULL", __func__);
781 return BAD_VALUE;
782 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700783 sp<DisplayDevice> device(getDisplayDevice(display));
784 if (device != NULL) {
785 return device->getActiveConfig();
786 }
787 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700788}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700789
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700790void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
791 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
792 this);
793 int32_t type = hw->getDisplayType();
794 int currentMode = hw->getActiveConfig();
795
796 if (mode == currentMode) {
797 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
798 return;
799 }
800
801 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
802 ALOGW("Trying to set config for virtual display");
803 return;
804 }
805
806 hw->setActiveConfig(mode);
807 getHwComposer().setActiveConfig(type, mode);
808}
809
810status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
811 class MessageSetActiveConfig: public MessageBase {
812 SurfaceFlinger& mFlinger;
813 sp<IBinder> mDisplay;
814 int mMode;
815 public:
816 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
817 int mode) :
818 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
819 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700820 Vector<DisplayInfo> configs;
821 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700822 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700823 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700824 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700825 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700826 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700827 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
828 if (hw == NULL) {
829 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700830 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700831 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
832 ALOGW("Attempt to set active config = %d for virtual display",
833 mMode);
834 } else {
835 mFlinger.setActiveConfigInternal(hw, mMode);
836 }
837 return true;
838 }
839 };
840 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
841 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700842 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700843}
Michael Wright28f24d02016-07-12 13:30:53 -0700844status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
845 Vector<android_color_mode_t>* outColorModes) {
846 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
847 return BAD_VALUE;
848 }
849
850 if (!display.get()) {
851 return NAME_NOT_FOUND;
852 }
853
854 int32_t type = NAME_NOT_FOUND;
855 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
856 if (display == mBuiltinDisplays[i]) {
857 type = i;
858 break;
859 }
860 }
861
862 if (type < 0) {
863 return type;
864 }
865
866 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
867 outColorModes->clear();
868 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
869
870 return NO_ERROR;
871}
872
873android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
874 sp<DisplayDevice> device(getDisplayDevice(display));
875 if (device != nullptr) {
876 return device->getActiveColorMode();
877 }
878 return static_cast<android_color_mode_t>(BAD_VALUE);
879}
880
881void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
882 android_color_mode_t mode) {
883 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
884 this);
885 int32_t type = hw->getDisplayType();
886 android_color_mode_t currentMode = hw->getActiveColorMode();
887
888 if (mode == currentMode) {
889 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
890 return;
891 }
892
893 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
894 ALOGW("Trying to set config for virtual display");
895 return;
896 }
897
898 hw->setActiveColorMode(mode);
899 getHwComposer().setActiveColorMode(type, mode);
900}
901
902
903status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
904 android_color_mode_t colorMode) {
905 class MessageSetActiveColorMode: public MessageBase {
906 SurfaceFlinger& mFlinger;
907 sp<IBinder> mDisplay;
908 android_color_mode_t mMode;
909 public:
910 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
911 android_color_mode_t mode) :
912 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
913 virtual bool handler() {
914 Vector<android_color_mode_t> modes;
915 mFlinger.getDisplayColorModes(mDisplay, &modes);
916 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
917 if (mMode < 0 || !exists) {
918 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
919 mDisplay.get());
920 return true;
921 }
922 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
923 if (hw == nullptr) {
924 ALOGE("Attempt to set active color mode = %d for null display %p",
925 mMode, mDisplay.get());
926 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
927 ALOGW("Attempt to set active color mode= %d for virtual display",
928 mMode);
929 } else {
930 mFlinger.setActiveColorModeInternal(hw, mMode);
931 }
932 return true;
933 }
934 };
935 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
936 postMessageSync(msg);
937 return NO_ERROR;
938}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700939
Svetoslavd85084b2014-03-20 10:28:31 -0700940status_t SurfaceFlinger::clearAnimationFrameStats() {
941 Mutex::Autolock _l(mStateLock);
942 mAnimFrameTracker.clearStats();
943 return NO_ERROR;
944}
945
946status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
947 Mutex::Autolock _l(mStateLock);
948 mAnimFrameTracker.getStats(outStats);
949 return NO_ERROR;
950}
951
Dan Stozac4f471e2016-03-24 09:31:08 -0700952status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
953 HdrCapabilities* outCapabilities) const {
954 Mutex::Autolock _l(mStateLock);
955
956 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
957 if (displayDevice == nullptr) {
958 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
959 return BAD_VALUE;
960 }
961
962 std::unique_ptr<HdrCapabilities> capabilities =
963 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
964 if (capabilities) {
965 std::swap(*outCapabilities, *capabilities);
966 } else {
967 return BAD_VALUE;
968 }
969
970 return NO_ERROR;
971}
972
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700973status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
974 if (enable == mInjectVSyncs) {
975 return NO_ERROR;
976 }
977
978 if (enable) {
979 mInjectVSyncs = enable;
980 ALOGV("VSync Injections enabled");
981 if (mVSyncInjector.get() == nullptr) {
982 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700983 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700984 }
985 mEventQueue.setEventThread(mInjectorEventThread);
986 } else {
987 mInjectVSyncs = enable;
988 ALOGV("VSync Injections disabled");
989 mEventQueue.setEventThread(mSFEventThread);
990 mVSyncInjector.clear();
991 }
992 return NO_ERROR;
993}
994
995status_t SurfaceFlinger::injectVSync(nsecs_t when) {
996 if (!mInjectVSyncs) {
997 ALOGE("VSync Injections not enabled");
998 return BAD_VALUE;
999 }
1000 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1001 ALOGV("Injecting VSync inside SurfaceFlinger");
1002 mVSyncInjector->onInjectSyncEvent(when);
1003 }
1004 return NO_ERROR;
1005}
1006
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001007// ----------------------------------------------------------------------------
1008
1009sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001010 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001011}
1012
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001014
1015void SurfaceFlinger::waitForEvent() {
1016 mEventQueue.waitMessage();
1017}
1018
1019void SurfaceFlinger::signalTransaction() {
1020 mEventQueue.invalidate();
1021}
1022
1023void SurfaceFlinger::signalLayerUpdate() {
1024 mEventQueue.invalidate();
1025}
1026
1027void SurfaceFlinger::signalRefresh() {
1028 mEventQueue.refresh();
1029}
1030
1031status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001032 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001033 return mEventQueue.postMessage(msg, reltime);
1034}
1035
1036status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001037 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001038 status_t res = mEventQueue.postMessage(msg, reltime);
1039 if (res == NO_ERROR) {
1040 msg->wait();
1041 }
1042 return res;
1043}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001044
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001045void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001046 do {
1047 waitForEvent();
1048 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001049}
1050
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001051void SurfaceFlinger::enableHardwareVsync() {
1052 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001053 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001054 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1056 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001057 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001058 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059}
1060
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001062 Mutex::Autolock _l(mHWVsyncLock);
1063
Jesse Hall948fe0c2013-10-14 12:56:09 -07001064 if (makeAvailable) {
1065 mHWVsyncAvailable = true;
1066 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001067 // Hardware vsync is not currently available, so abort the resync
1068 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069 return;
1070 }
1071
Dan Stoza9e56aa02015-11-02 13:00:03 -08001072 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1073 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074
1075 mPrimaryDispSync.reset();
1076 mPrimaryDispSync.setPeriod(period);
1077
1078 if (!mPrimaryHWVsyncEnabled) {
1079 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001080 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1081 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 mPrimaryHWVsyncEnabled = true;
1083 }
1084}
1085
Jesse Hall948fe0c2013-10-14 12:56:09 -07001086void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087 Mutex::Autolock _l(mHWVsyncLock);
1088 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001089 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1090 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001091 mPrimaryDispSync.endResync();
1092 mPrimaryHWVsyncEnabled = false;
1093 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001094 if (makeUnavailable) {
1095 mHWVsyncAvailable = false;
1096 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001097}
1098
Tim Murray4a4e4a22016-04-19 16:29:23 +00001099void SurfaceFlinger::resyncWithRateLimit() {
1100 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1101 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001102 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001103 }
1104}
1105
Steven Thomas3cfac282017-02-06 12:29:30 -08001106void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1107 nsecs_t timestamp) {
1108 Mutex::Autolock lock(mStateLock);
1109 // Ignore any vsyncs from the non-active hardware composer.
1110 if (composer != mHwc) {
1111 return;
1112 }
1113
Jamie Gennisd1700752013-10-14 12:22:52 -07001114 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115
Jamie Gennisd1700752013-10-14 12:22:52 -07001116 { // Scope for the lock
1117 Mutex::Autolock _l(mHWVsyncLock);
1118 if (type == 0 && mPrimaryHWVsyncEnabled) {
1119 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001120 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001121 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001122
1123 if (needsHwVsync) {
1124 enableHardwareVsync();
1125 } else {
1126 disableHardwareVsync(false);
1127 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001128}
1129
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001130void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1131 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1132 *compositorTiming = mCompositorTiming;
1133}
1134
Dan Stoza9e56aa02015-11-02 13:00:03 -08001135void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1136 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1137 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1138 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001139
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140 // All non-virtual displays are currently considered secure.
1141 bool isSecure = true;
1142
1143 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001144
1145 // When we're using the vr composer, the assumption is that we've
1146 // already created the IBinder object for the primary display.
1147 if (!mHwc->isUsingVrComposer()) {
1148 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1149 }
1150
Dan Stoza9e56aa02015-11-02 13:00:03 -08001151 wp<IBinder> token = mBuiltinDisplays[type];
1152
1153 sp<IGraphicBufferProducer> producer;
1154 sp<IGraphicBufferConsumer> consumer;
1155 BufferQueue::createBufferQueue(&producer, &consumer,
1156 new GraphicBufferAlloc());
1157
1158 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1159 DisplayDevice::DISPLAY_PRIMARY, consumer);
1160 sp<DisplayDevice> hw = new DisplayDevice(this,
1161 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1162 producer, mRenderEngine->getEGLConfig());
1163 mDisplays.add(token, hw);
1164 } else {
1165 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001166 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001167 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001168 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001169 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001170 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1171 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001172 }
1173 setTransactionFlags(eDisplayTransactionNeeded);
1174
Andy McFadden9e9689c2012-10-10 18:17:51 -07001175 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001176 }
Mathias Agopian86303202012-07-24 22:46:10 -07001177}
1178
Steven Thomas3cfac282017-02-06 12:29:30 -08001179void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1180 Mutex::Autolock lock(mStateLock);
1181 if (composer == mHwc) {
1182 repaintEverything();
1183 } else {
1184 // This isn't from our current hardware composer. If it's a callback
1185 // from the real composer, forward the refresh request to vr
1186 // flinger. Otherwise ignore it.
1187 if (!composer->isUsingVrComposer()) {
1188 mVrFlinger->OnHardwareComposerRefresh();
1189 }
1190 }
1191}
1192
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001195 getHwComposer().setVsyncEnabled(disp,
1196 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001197}
1198
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001199void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1200 for (size_t i = 0; i < layers.size(); ++i) {
1201 layers[i]->clearHwcLayers();
1202 }
1203}
1204
1205void SurfaceFlinger::resetHwc() {
1206 disableHardwareVsync(true);
1207 clearHwcLayers(mDrawingState.layersSortedByZ);
1208 clearHwcLayers(mCurrentState.layersSortedByZ);
1209 // Clear the drawing state so that the logic inside of
1210 // handleTransactionLocked will fire. It will determine the delta between
1211 // mCurrentState and mDrawingState and re-apply all changes when we make the
1212 // transition.
1213 mDrawingState.displays.clear();
1214 mDisplays.clear();
1215}
1216
1217void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001218 bool enteringVrMode = mEnterVrMode;
1219 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1220 return;
1221 }
1222 if (enteringVrMode && !mVrHwc) {
1223 // Construct new HWComposer without holding any locks.
1224 mVrHwc = new HWComposer(true);
1225 ALOGV("Vr HWC created");
1226 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001227 {
1228 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001229
1230 if (enteringVrMode) {
1231 // Start vrflinger thread, if it hasn't been started already.
1232 if (!mVrFlinger) {
1233 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1234 int err = mVrFlinger->Run(mHwc->getComposer());
1235 if (err != NO_ERROR) {
1236 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1237 mVrFlinger.reset();
1238 mEnterVrMode = false;
1239 return;
1240 }
1241 }
1242
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001243 resetHwc();
1244
1245 mHwc = mVrHwc;
1246 mVrFlinger->EnterVrMode();
1247 } else {
1248 mVrFlinger->ExitVrMode();
1249
1250 resetHwc();
1251
1252 mHwc = mRealHwc;
1253 enableHardwareVsync();
1254 }
1255
1256 mVisibleRegionsDirty = true;
1257 invalidateHwcGeometry();
1258 android_atomic_or(1, &mRepaintEverything);
1259 setTransactionFlags(eDisplayTransactionNeeded);
1260 }
1261 if (mVrHwc) {
1262 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1263 }
1264}
1265
Mathias Agopian4fec8732012-06-29 14:12:52 -07001266void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001267 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001269 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001270 // TODO(eieio): Tied to a conditional until SELinux issues
1271 // are resolved.
1272 if (mVrModeSupported) {
1273 updateVrMode();
1274 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001275
Dan Stoza50182882016-07-08 12:02:20 -07001276 bool frameMissed = !mHadClientComposition &&
1277 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001278 (mPreviousPresentFence->getSignalTime() ==
1279 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001280 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001281 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001282 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001283 signalLayerUpdate();
1284 break;
1285 }
1286
Dan Stoza6b9454d2014-11-07 16:00:59 -08001287 bool refreshNeeded = handleMessageTransaction();
1288 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001289 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001290 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001291 // Signal a refresh if a transaction modified the window state,
1292 // a new buffer was latched, or if HWC has requested a full
1293 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001294 signalRefresh();
1295 }
1296 break;
1297 }
1298 case MessageQueue::REFRESH: {
1299 handleMessageRefresh();
1300 break;
1301 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001302 }
1303}
1304
Dan Stoza6b9454d2014-11-07 16:00:59 -08001305bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001306 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001307 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001308 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001309 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001310 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001311 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001312}
1313
Dan Stoza6b9454d2014-11-07 16:00:59 -08001314bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001315 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001316 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001317}
1318
1319void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001320 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001321
Pablo Ceballos40845df2016-01-25 17:41:15 -08001322 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001323
Brian Andersond6927fb2016-07-23 23:37:30 -07001324 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001325 rebuildLayerStacks();
1326 setUpHWComposer();
1327 doDebugFlashRegions();
1328 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001329 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001330
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001331 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001332
1333 mHadClientComposition = false;
1334 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1335 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1336 mHadClientComposition = mHadClientComposition ||
1337 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1338 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001339
Dan Stoza9e56aa02015-11-02 13:00:03 -08001340 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001341}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001342
Mathias Agopiancd60f992012-08-16 16:28:27 -07001343void SurfaceFlinger::doDebugFlashRegions()
1344{
1345 // is debugging enabled
1346 if (CC_LIKELY(!mDebugRegion))
1347 return;
1348
1349 const bool repaintEverything = mRepaintEverything;
1350 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1351 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001352 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001353 // transform the dirty region into this screen's coordinate space
1354 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1355 if (!dirtyRegion.isEmpty()) {
1356 // redraw the whole screen
1357 doComposeSurfaces(hw, Region(hw->bounds()));
1358
1359 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001360 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001361 RenderEngine& engine(getRenderEngine());
1362 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1363
Mathias Agopianda27af92012-09-13 18:17:13 -07001364 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365 }
1366 }
1367 }
1368
1369 postFramebuffer();
1370
1371 if (mDebugRegion > 1) {
1372 usleep(mDebugRegion * 1000);
1373 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001374
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001376 auto& displayDevice = mDisplays[displayId];
1377 if (!displayDevice->isDisplayOn()) {
1378 continue;
1379 }
1380
1381 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1383 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001384 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385}
1386
Brian Andersond6927fb2016-07-23 23:37:30 -07001387void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001388{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001389 ATRACE_CALL();
1390 ALOGV("preComposition");
1391
Mathias Agopiancd60f992012-08-16 16:28:27 -07001392 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001393 mDrawingState.traverseInZOrder([&](Layer* layer) {
1394 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001395 needExtraInvalidate = true;
1396 }
Robert Carr2047fae2016-11-28 14:09:09 -08001397 });
1398
Mathias Agopiancd60f992012-08-16 16:28:27 -07001399 if (needExtraInvalidate) {
1400 signalLayerUpdate();
1401 }
1402}
1403
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001404void SurfaceFlinger::updateCompositorTiming(
1405 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1406 std::shared_ptr<FenceTime>& presentFenceTime) {
1407 // Update queue of past composite+present times and determine the
1408 // most recently known composite to present latency.
1409 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1410 nsecs_t compositeToPresentLatency = -1;
1411 while (!mCompositePresentTimes.empty()) {
1412 CompositePresentTime& cpt = mCompositePresentTimes.front();
1413 // Cached values should have been updated before calling this method,
1414 // which helps avoid duplicate syscalls.
1415 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1416 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1417 break;
1418 }
1419 compositeToPresentLatency = displayTime - cpt.composite;
1420 mCompositePresentTimes.pop();
1421 }
1422
1423 // Don't let mCompositePresentTimes grow unbounded, just in case.
1424 while (mCompositePresentTimes.size() > 16) {
1425 mCompositePresentTimes.pop();
1426 }
1427
1428 // Integer division and modulo round toward 0 not -inf, so we need to
1429 // treat negative and positive offsets differently.
1430 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1431 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1432 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1433
1434 // Snap the latency to a value that removes scheduling jitter from the
1435 // composition and present times, which often have >1ms of jitter.
1436 // Reducing jitter is important if an app attempts to extrapolate
1437 // something (such as user input) to an accurate diasplay time.
1438 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1439 // with (presentLatency % interval).
1440 nsecs_t snappedCompositeToPresentLatency = -1;
1441 if (compositeToPresentLatency >= 0) {
1442 nsecs_t bias = vsyncInterval / 2;
1443 int64_t extraVsyncs =
1444 (compositeToPresentLatency - idealLatency + bias) /
1445 vsyncInterval;
1446 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1447 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1448 }
1449
1450 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1451 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1452 mCompositorTiming.interval = vsyncInterval;
1453 if (snappedCompositeToPresentLatency >= 0) {
1454 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1455 }
1456}
1457
1458void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001459{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001460 ATRACE_CALL();
1461 ALOGV("postComposition");
1462
Brian Anderson3546a3f2016-07-14 11:51:14 -07001463 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001464 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001465 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001466 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001467 }
1468
Brian Andersond6927fb2016-07-23 23:37:30 -07001469 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001470
1471 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1472 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1473 glCompositionDoneFenceTime =
1474 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1475 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1476 } else {
1477 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1478 }
1479 mGlCompositionDoneTimeline.updateSignalTimes();
1480
1481 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1482 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1483 mDisplayTimeline.push(displayFenceTime);
1484 mDisplayTimeline.updateSignalTimes();
1485
1486 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1487 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1488 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1489 presentFenceTime = &displayFenceTime;
1490 } else {
1491 retireFenceTime = &displayFenceTime;
1492 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493
1494 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1495 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1496
1497 // We use the refreshStartTime which might be sampled a little later than
1498 // when we started doing work for this frame, but that should be okay
1499 // since updateCompositorTiming has snapping logic.
1500 updateCompositorTiming(
1501 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1502
Robert Carr2047fae2016-11-28 14:09:09 -08001503 mDrawingState.traverseInZOrder([&](Layer* layer) {
1504 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001506 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001507 recordBufferingStats(layer->getName().string(),
1508 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001509 }
Robert Carr2047fae2016-11-28 14:09:09 -08001510 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001511
Brian Anderson3d4039d2016-09-23 16:31:30 -07001512 if (displayFence->isValid()) {
1513 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001514 enableHardwareVsync();
1515 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001516 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001517 }
1518 }
1519
Andy McFadden5167ec62014-05-22 13:08:43 -07001520 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001521 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001522 enableHardwareVsync();
1523 }
1524 }
1525
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001526 if (mAnimCompositionPending) {
1527 mAnimCompositionPending = false;
1528
Brian Anderson3d4039d2016-09-23 16:31:30 -07001529 if (displayFenceTime->isValid()) {
1530 mAnimFrameTracker.setActualPresentFence(
1531 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001532 } else {
1533 // The HWC doesn't support present fences, so use the refresh
1534 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 nsecs_t presentTime =
1536 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001537 mAnimFrameTracker.setActualPresentTime(presentTime);
1538 }
1539 mAnimFrameTracker.advanceFrame();
1540 }
Dan Stozab90cf072015-03-05 11:05:59 -08001541
1542 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1543 return;
1544 }
1545
1546 nsecs_t currentTime = systemTime();
1547 if (mHasPoweredOff) {
1548 mHasPoweredOff = false;
1549 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001550 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001552 if (numPeriods < NUM_BUCKETS - 1) {
1553 mFrameBuckets[numPeriods] += elapsedTime;
1554 } else {
1555 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1556 }
1557 mTotalTime += elapsedTime;
1558 }
1559 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560}
1561
1562void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001563 ATRACE_CALL();
1564 ALOGV("rebuildLayerStacks");
1565
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001567 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1568 ATRACE_CALL();
1569 mVisibleRegionsDirty = false;
1570 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001571
Jeff Sharkey76488112017-02-27 14:15:18 -07001572 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1573 Region opaqueRegion;
1574 Region dirtyRegion;
1575 Vector<sp<Layer>> layersSortedByZ;
1576 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1577 const Transform& tr(displayDevice->getTransform());
1578 const Rect bounds(displayDevice->getBounds());
1579 if (displayDevice->isDisplayOn()) {
1580 computeVisibleRegions(
1581 displayDevice->getLayerStack(), dirtyRegion,
1582 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001583
Jeff Sharkey76488112017-02-27 14:15:18 -07001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1586 Region drawRegion(tr.transform(
1587 layer->visibleNonTransparentRegion));
1588 drawRegion.andSelf(bounds);
1589 if (!drawRegion.isEmpty()) {
1590 layersSortedByZ.add(layer);
1591 } else {
1592 // Clear out the HWC layer if this layer was
1593 // previously visible, but no longer is
1594 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1595 nullptr);
1596 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001597 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001598 // WM changes displayDevice->layerStack upon sleep/awake.
1599 // Here we make sure we delete the HWC layers even if
1600 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001601 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1602 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001603 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001604 });
1605 }
1606 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1607 displayDevice->undefinedRegion.set(bounds);
1608 displayDevice->undefinedRegion.subtractSelf(
1609 tr.transform(opaqueRegion));
1610 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001611 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001612 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001614
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001616 ATRACE_CALL();
1617 ALOGV("setUpHWComposer");
1618
Jesse Hall028dc8f2013-08-20 16:35:32 -07001619 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001620 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1621 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1622 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1623
1624 // If nothing has changed (!dirty), don't recompose.
1625 // If something changed, but we don't currently have any visible layers,
1626 // and didn't when we last did a composition, then skip it this time.
1627 // The second rule does two things:
1628 // - When all layers are removed from a display, we'll emit one black
1629 // frame, then nothing more until we get new layers.
1630 // - When a display is created with a private layer stack, we won't
1631 // emit any black frames until a layer is added to the layer stack.
1632 bool mustRecompose = dirty && !(empty && wasEmpty);
1633
1634 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1635 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1636 mustRecompose ? "doing" : "skipping",
1637 dirty ? "+" : "-",
1638 empty ? "+" : "-",
1639 wasEmpty ? "+" : "-");
1640
Dan Stoza71433162014-02-04 16:22:36 -08001641 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001642
1643 if (mustRecompose) {
1644 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1645 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001646 }
1647
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 // build the h/w work list
1649 if (CC_UNLIKELY(mGeometryInvalid)) {
1650 mGeometryInvalid = false;
1651 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1652 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1653 const auto hwcId = displayDevice->getHwcDisplayId();
1654 if (hwcId >= 0) {
1655 const Vector<sp<Layer>>& currentLayers(
1656 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001657 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001658 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 if (!layer->hasHwcLayer(hwcId)) {
1660 auto hwcLayer = mHwc->createLayer(hwcId);
1661 if (hwcLayer) {
1662 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1663 } else {
1664 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001665 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001666 }
1667 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001668
Robert Carrae060832016-11-28 10:51:00 -08001669 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001670 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001672 }
1673 }
1674 }
1675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001676 }
Riley Andrews03414a12014-07-01 14:22:59 -07001677
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001678
1679 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1680
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 // Set the per-frame data
1682 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1683 auto& displayDevice = mDisplays[displayId];
1684 const auto hwcId = displayDevice->getHwcDisplayId();
1685 if (hwcId < 0) {
1686 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001687 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001688 if (colorMatrix != mPreviousColorMatrix) {
1689 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1690 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1691 "display %zd: %d", displayId, result);
1692 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001693 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1694 layer->setPerFrameData(displayDevice);
1695 }
1696 }
1697
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001698 mPreviousColorMatrix = colorMatrix;
1699
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001701 auto& displayDevice = mDisplays[displayId];
1702 if (!displayDevice->isDisplayOn()) {
1703 continue;
1704 }
1705
1706 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1708 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001709 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001711
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712void SurfaceFlinger::doComposition() {
1713 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001714 ALOGV("doComposition");
1715
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001716 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001717 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001718 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001719 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001720 // transform the dirty region into this screen's coordinate space
1721 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001722
1723 // repaint the framebuffer (if needed)
1724 doDisplayComposition(hw, dirtyRegion);
1725
Mathias Agopiancd60f992012-08-16 16:28:27 -07001726 hw->dirtyRegion.clear();
1727 hw->flip(hw->swapRegion);
1728 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001729 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001730 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001731 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001732}
1733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001734void SurfaceFlinger::postFramebuffer()
1735{
Mathias Agopian841cde52012-03-01 15:44:37 -08001736 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001738
Mathias Agopiana44b0412011-10-16 18:46:35 -07001739 const nsecs_t now = systemTime();
1740 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001741
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1743 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001744 if (!displayDevice->isDisplayOn()) {
1745 continue;
1746 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 const auto hwcId = displayDevice->getHwcDisplayId();
1748 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001749 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001750 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001751 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001752 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1754 sp<Fence> releaseFence = Fence::NO_FENCE;
1755 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1756 releaseFence = displayDevice->getClientTargetAcquireFence();
1757 } else {
1758 auto hwcLayer = layer->getHwcLayer(hwcId);
1759 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001760 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 layer->onLayerDisplayed(releaseFence);
1762 }
1763 if (hwcId >= 0) {
1764 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001765 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001766 }
1767
Mathias Agopiana44b0412011-10-16 18:46:35 -07001768 mLastSwapBufferTime = systemTime() - now;
1769 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001770
1771 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1772 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1773 logFrameStats();
1774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001775}
1776
Mathias Agopian87baae12012-07-31 12:38:26 -07001777void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001778{
Mathias Agopian841cde52012-03-01 15:44:37 -08001779 ATRACE_CALL();
1780
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001781 // here we keep a copy of the drawing state (that is the state that's
1782 // going to be overwritten by handleTransactionLocked()) outside of
1783 // mStateLock so that the side-effects of the State assignment
1784 // don't happen with mStateLock held (which can cause deadlocks).
1785 State drawingState(mDrawingState);
1786
Mathias Agopianca4d3602011-05-19 15:38:14 -07001787 Mutex::Autolock _l(mStateLock);
1788 const nsecs_t now = systemTime();
1789 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790
Mathias Agopianca4d3602011-05-19 15:38:14 -07001791 // Here we're guaranteed that some transaction flags are set
1792 // so we can call handleTransactionLocked() unconditionally.
1793 // We call getTransactionFlags(), which will also clear the flags,
1794 // with mStateLock held to guarantee that mCurrentState won't change
1795 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001796
Mathias Agopiane57f2922012-08-09 16:29:12 -07001797 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001798 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001799
Mathias Agopianca4d3602011-05-19 15:38:14 -07001800 mLastTransactionTime = systemTime() - now;
1801 mDebugInTransaction = 0;
1802 invalidateHwcGeometry();
1803 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001804}
1805
Mathias Agopian87baae12012-07-31 12:38:26 -07001806void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001807{
Dan Stoza7dde5992015-05-22 09:51:44 -07001808 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001809 mCurrentState.traverseInZOrder([](Layer* layer) {
1810 layer->notifyAvailableFrames();
1811 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813 /*
1814 * Traversal of the children
1815 * (perform the transaction for each of them if needed)
1816 */
1817
Mathias Agopian3559b072012-08-15 13:46:03 -07001818 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001819 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001821 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822
1823 const uint32_t flags = layer->doTransaction(0);
1824 if (flags & Layer::eVisibleRegion)
1825 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001826 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001827 }
1828
1829 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001830 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 */
1832
Mathias Agopiane57f2922012-08-09 16:29:12 -07001833 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834 // here we take advantage of Vector's copy-on-write semantics to
1835 // improve performance by skipping the transaction entirely when
1836 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001837 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1838 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001840 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001841 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001842 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001843
1844 // find the displays that were removed
1845 // (ie: in drawing state but not in current state)
1846 // also handle displays that changed
1847 // (ie: displays that are in both lists)
1848 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001849 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1850 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001851 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001852 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001853 // Call makeCurrent() on the primary display so we can
1854 // be sure that nothing associated with this display
1855 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001856 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001857 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001858 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1859 if (hw != NULL)
1860 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001861 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001862 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001863 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001864 } else {
1865 ALOGW("trying to remove the main display");
1866 }
1867 } else {
1868 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001869 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001870 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001871 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1872 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001873 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001874 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001875 // recreating the DisplayDevice, so we just remove it
1876 // from the drawing state, so that it get re-added
1877 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001878 sp<DisplayDevice> hw(getDisplayDevice(display));
1879 if (hw != NULL)
1880 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001881 mDisplays.removeItem(display);
1882 mDrawingState.displays.removeItemsAt(i);
1883 dc--; i--;
1884 // at this point we must loop to the next item
1885 continue;
1886 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001887
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001888 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001889 if (disp != NULL) {
1890 if (state.layerStack != draw[i].layerStack) {
1891 disp->setLayerStack(state.layerStack);
1892 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001893 if ((state.orientation != draw[i].orientation)
1894 || (state.viewport != draw[i].viewport)
1895 || (state.frame != draw[i].frame))
1896 {
1897 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001898 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001899 }
Michael Lentine47e45402014-07-18 15:34:25 -07001900 if (state.width != draw[i].width || state.height != draw[i].height) {
1901 disp->setDisplaySize(state.width, state.height);
1902 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001903 }
1904 }
1905 }
1906
1907 // find displays that were added
1908 // (ie: in current state but not in drawing state)
1909 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001910 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001911 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001912
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001913 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001914 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001915 sp<IGraphicBufferProducer> bqProducer;
1916 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001917 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1918 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001919
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001921 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001922 // Virtual displays without a surface are dormant:
1923 // they have external state (layer stack, projection,
1924 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001925 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001926
Dan Stoza8cf150a2016-08-02 10:27:31 -07001927 if (mUseHwcVirtualDisplays) {
1928 int width = 0;
1929 int status = state.surface->query(
1930 NATIVE_WINDOW_WIDTH, &width);
1931 ALOGE_IF(status != NO_ERROR,
1932 "Unable to query width (%d)", status);
1933 int height = 0;
1934 status = state.surface->query(
1935 NATIVE_WINDOW_HEIGHT, &height);
1936 ALOGE_IF(status != NO_ERROR,
1937 "Unable to query height (%d)", status);
1938 int intFormat = 0;
1939 status = state.surface->query(
1940 NATIVE_WINDOW_FORMAT, &intFormat);
1941 ALOGE_IF(status != NO_ERROR,
1942 "Unable to query format (%d)", status);
1943 auto format = static_cast<android_pixel_format_t>(
1944 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001945
Dan Stoza8cf150a2016-08-02 10:27:31 -07001946 mHwc->allocateVirtualDisplay(width, height, &format,
1947 &hwcId);
1948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949
Dan Stoza5cf424b2016-05-20 14:02:39 -07001950 // TODO: Plumb requested format back up to consumer
1951
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 sp<VirtualDisplaySurface> vds =
1953 new VirtualDisplaySurface(*mHwc,
1954 hwcId, state.surface, bqProducer,
1955 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001956
1957 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001958 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001959 }
1960 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001961 ALOGE_IF(state.surface!=NULL,
1962 "adding a supported display, but rendering "
1963 "surface is provided (%p), ignoring it",
1964 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001965
1966 hwcId = state.type;
1967 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1968 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001969 }
1970
1971 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001972 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001973 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 state.type, hwcId, state.isSecure, display,
1975 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001976 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001977 hw->setLayerStack(state.layerStack);
1978 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001979 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001980 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001981 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001983 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001984 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001985 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001986 }
1987 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001989 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990
Mathias Agopian84300952012-11-21 16:02:13 -08001991 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1992 // The transform hint might have changed for some layers
1993 // (either because a display has changed, or because a layer
1994 // as changed).
1995 //
1996 // Walk through all the layers in currentLayers,
1997 // and update their transform hint.
1998 //
1999 // If a layer is visible only on a single display, then that
2000 // display is used to calculate the hint, otherwise we use the
2001 // default display.
2002 //
2003 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2004 // the hint is set before we acquire a buffer from the surface texture.
2005 //
2006 // NOTE: layer transactions have taken place already, so we use their
2007 // drawing state. However, SurfaceFlinger's own transaction has not
2008 // happened yet, so we must use the current state layer list
2009 // (soon to become the drawing state list).
2010 //
2011 sp<const DisplayDevice> disp;
2012 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002013 bool first = true;
2014 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002015 // NOTE: we rely on the fact that layers are sorted by
2016 // layerStack first (so we don't have to traverse the list
2017 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002018 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002019 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002020 currentlayerStack = layerStack;
2021 // figure out if this layerstack is mirrored
2022 // (more than one display) if so, pick the default display,
2023 // if not, pick the only display it's on.
2024 disp.clear();
2025 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2026 sp<const DisplayDevice> hw(mDisplays[dpy]);
2027 if (hw->getLayerStack() == currentlayerStack) {
2028 if (disp == NULL) {
2029 disp = hw;
2030 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002031 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002032 break;
2033 }
2034 }
2035 }
2036 }
Chet Haase91d25932013-04-11 15:24:55 -07002037 if (disp == NULL) {
2038 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2039 // redraw after transform hint changes. See bug 8508397.
2040
2041 // could be null when this layer is using a layerStack
2042 // that is not visible on any display. Also can occur at
2043 // screen off/on times.
2044 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002045 }
Chet Haase91d25932013-04-11 15:24:55 -07002046 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002047
2048 first = false;
2049 });
Mathias Agopian84300952012-11-21 16:02:13 -08002050 }
2051
2052
Mathias Agopian3559b072012-08-15 13:46:03 -07002053 /*
2054 * Perform our own transaction if needed
2055 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002056
2057 if (mLayersAdded) {
2058 mLayersAdded = false;
2059 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002060 mVisibleRegionsDirty = true;
2061 }
2062
2063 // some layers might have been removed, so
2064 // we need to update the regions they're exposing.
2065 if (mLayersRemoved) {
2066 mLayersRemoved = false;
2067 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002068 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002069 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002070 // this layer is not visible anymore
2071 // TODO: we could traverse the tree from front to back and
2072 // compute the actual visible region
2073 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002074 Region visibleReg;
2075 visibleReg.set(layer->computeScreenBounds());
2076 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002077 }
Robert Carr2047fae2016-11-28 14:09:09 -08002078 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079 }
2080
2081 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002082
2083 updateCursorAsync();
2084}
2085
2086void SurfaceFlinger::updateCursorAsync()
2087{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2089 auto& displayDevice = mDisplays[displayId];
2090 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002091 continue;
2092 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093
2094 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2095 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002096 }
2097 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098}
2099
2100void SurfaceFlinger::commitTransaction()
2101{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002102 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002104 for (const auto& l : mLayersPendingRemoval) {
2105 recordBufferingStats(l->getName().string(),
2106 l->getOccupancyHistory(true));
2107 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002108 }
2109 mLayersPendingRemoval.clear();
2110 }
2111
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002112 // If this transaction is part of a window animation then the next frame
2113 // we composite should be considered an animation as well.
2114 mAnimCompositionPending = mAnimTransactionPending;
2115
Mathias Agopian4fec8732012-06-29 14:12:52 -07002116 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002117 mDrawingState.traverseInZOrder([](Layer* layer) {
2118 layer->commitChildList();
2119 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002120 mTransactionPending = false;
2121 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002122 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123}
2124
Robert Carr2047fae2016-11-28 14:09:09 -08002125void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002126 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002127{
Mathias Agopian841cde52012-03-01 15:44:37 -08002128 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 Region aboveOpaqueLayers;
2132 Region aboveCoveredLayers;
2133 Region dirty;
2134
Mathias Agopian87baae12012-07-31 12:38:26 -07002135 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136
Robert Carr2047fae2016-11-28 14:09:09 -08002137 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002139 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140
Jesse Hall01e29052013-02-19 16:13:35 -08002141 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002142 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002143 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002144
Mathias Agopianab028732010-03-16 16:41:46 -07002145 /*
2146 * opaqueRegion: area of a surface that is fully opaque.
2147 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002149
2150 /*
2151 * visibleRegion: area of a surface that is visible on screen
2152 * and not fully transparent. This is essentially the layer's
2153 * footprint minus the opaque regions above it.
2154 * Areas covered by a translucent surface are considered visible.
2155 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002157
2158 /*
2159 * coveredRegion: area of a surface that is covered by all
2160 * visible regions above it (which includes the translucent areas).
2161 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002163
Jesse Halla8026d22012-09-25 13:25:04 -07002164 /*
2165 * transparentRegion: area of a surface that is hinted to be completely
2166 * transparent. This is only used to tell when the layer has no visible
2167 * non-transparent regions and can be removed from the layer list. It
2168 * does not affect the visibleRegion of this layer or any layers
2169 * beneath it. The hint may not be correct if apps don't respect the
2170 * SurfaceView restrictions (which, sadly, some don't).
2171 */
2172 Region transparentRegion;
2173
Mathias Agopianab028732010-03-16 16:41:46 -07002174
2175 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002176 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002177 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002178 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002180 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002181 if (!visibleRegion.isEmpty()) {
2182 // Remove the transparent area from the visible region
2183 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002184 if (tr.preserveRects()) {
2185 // transform the transparent region
2186 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002187 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002188 // transformation too complex, can't do the
2189 // transparent region optimization.
2190 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002191 }
Mathias Agopianab028732010-03-16 16:41:46 -07002192 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
Mathias Agopianab028732010-03-16 16:41:46 -07002194 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002195 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002197 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2198 // the opaque region is the layer's footprint
2199 opaqueRegion = visibleRegion;
2200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201 }
2202 }
2203
Mathias Agopianab028732010-03-16 16:41:46 -07002204 // Clip the covered region to the visible region
2205 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2206
2207 // Update aboveCoveredLayers for next (lower) layer
2208 aboveCoveredLayers.orSelf(visibleRegion);
2209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210 // subtract the opaque region covered by the layers above us
2211 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212
2213 // compute this layer's dirty region
2214 if (layer->contentDirty) {
2215 // we need to invalidate the whole region
2216 dirty = visibleRegion;
2217 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002218 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219 layer->contentDirty = false;
2220 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002221 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002222 * the exposed region consists of two components:
2223 * 1) what's VISIBLE now and was COVERED before
2224 * 2) what's EXPOSED now less what was EXPOSED before
2225 *
2226 * note that (1) is conservative, we start with the whole
2227 * visible region but only keep what used to be covered by
2228 * something -- which mean it may have been exposed.
2229 *
2230 * (2) handles areas that were not covered by anything but got
2231 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002232 */
Mathias Agopianab028732010-03-16 16:41:46 -07002233 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002234 const Region oldVisibleRegion = layer->visibleRegion;
2235 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002236 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2237 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 }
2239 dirty.subtractSelf(aboveOpaqueLayers);
2240
2241 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002242 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Mathias Agopianab028732010-03-16 16:41:46 -07002244 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002246
Jesse Halla8026d22012-09-25 13:25:04 -07002247 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248 layer->setVisibleRegion(visibleRegion);
2249 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002250 layer->setVisibleNonTransparentRegion(
2251 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002252 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopian87baae12012-07-31 12:38:26 -07002254 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255}
2256
Mathias Agopian87baae12012-07-31 12:38:26 -07002257void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2258 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002259 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002260 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2261 if (hw->getLayerStack() == layerStack) {
2262 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002263 }
2264 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002265}
2266
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 ALOGV("handlePageFlip");
2270
Brian Andersond6927fb2016-07-23 23:37:30 -07002271 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272
Mathias Agopian4fec8732012-06-29 14:12:52 -07002273 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002274 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002275
2276 // Store the set of layers that need updates. This set must not change as
2277 // buffers are being latched, as this could result in a deadlock.
2278 // Example: Two producers share the same command stream and:
2279 // 1.) Layer 0 is latched
2280 // 2.) Layer 0 gets a new frame
2281 // 2.) Layer 1 gets a new frame
2282 // 3.) Layer 1 is latched.
2283 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2284 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002285 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286 if (layer->hasQueuedFrame()) {
2287 frameQueued = true;
2288 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002289 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002290 } else {
2291 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002292 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002293 } else {
2294 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002295 }
Robert Carr2047fae2016-11-28 14:09:09 -08002296 });
2297
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002299 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002300 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002302 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002303
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002304 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002305
2306 // If we will need to wake up at some time in the future to deal with a
2307 // queued frame that shouldn't be displayed during this vsync period, wake
2308 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002310 signalLayerUpdate();
2311 }
2312
2313 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315}
2316
Mathias Agopianad456f92011-01-13 17:53:01 -08002317void SurfaceFlinger::invalidateHwcGeometry()
2318{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002319 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002320}
2321
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002322
Fabien Sanglard830b8472016-11-30 16:35:58 -08002323void SurfaceFlinger::doDisplayComposition(
2324 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002325 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326{
Dan Stoza71433162014-02-04 16:22:36 -08002327 // We only need to actually compose the display if:
2328 // 1) It is being handled by hardware composer, which may need this to
2329 // keep its virtual display state machine in sync, or
2330 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002332 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002333 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002334 return;
2335 }
2336
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 ALOGV("doDisplayComposition");
2338
Mathias Agopian87baae12012-07-31 12:38:26 -07002339 Region dirtyRegion(inDirtyRegion);
2340
Mathias Agopianb8a55602009-06-26 19:06:36 -07002341 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002342 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343
Fabien Sanglard830b8472016-11-30 16:35:58 -08002344 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002345 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002346 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2347 // takes a rectangle, we must make sure to update that whole
2348 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002350 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002351 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002352 // We need to redraw the rectangle that will be updated
2353 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002354 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002355 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002356 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002357 } else {
2358 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002359 dirtyRegion.set(displayDevice->bounds());
2360 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 }
2362 }
2363
Fabien Sanglard830b8472016-11-30 16:35:58 -08002364 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002366 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002367 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002368
2369 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002370 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371}
2372
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373bool SurfaceFlinger::doComposeSurfaces(
2374 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002377
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002379
2380 mat4 oldColorMatrix;
2381 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2382 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2383 if (applyColorMatrix) {
2384 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2385 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2386 }
2387
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2389 if (hasClientComposition) {
2390 ALOGV("hasClientComposition");
2391
2392 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002393 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002395 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2396 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2397 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2398 }
2399 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002400 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002401
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2404 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002405 // when using overlays, we assume a fully transparent framebuffer
2406 // NOTE: we could reduce how much we need to clear, for instance
2407 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002408 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002411 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002412 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002414
2415 // we remove the scissor part
2416 // we're left with the letterbox region
2417 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002419
2420 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002422
2423 // but limit it to the dirty region
2424 region.andSelf(dirty);
2425
Mathias Agopianb9494d52012-04-18 02:28:45 -07002426 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002427 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002428 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002430 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002431 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002432
Dan Stoza9e56aa02015-11-02 13:00:03 -08002433 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002434 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002435 // scissor on the main display. It should never be needed
2436 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 const Rect& bounds(displayDevice->getBounds());
2438 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002439 if (scissor != bounds) {
2440 // scissor doesn't match the screen's dimensions, so we
2441 // need to clear everything outside of it and enable
2442 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002443
Mathias Agopianf45c5102012-10-24 16:29:17 -07002444 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 const uint32_t height = displayDevice->getHeight();
2446 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002447 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002448 }
2449 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002450 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002451
Mathias Agopian85d751c2012-08-29 16:59:24 -07002452 /*
2453 * and then, render the layers targeted at the framebuffer
2454 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002455
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 ALOGV("Rendering client layers");
2457 const Transform& displayTransform = displayDevice->getTransform();
2458 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002459 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 bool firstLayer = true;
2461 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2462 const Region clip(dirty.intersect(
2463 displayTransform.transform(layer->visibleRegion)));
2464 ALOGV("Layer: %s", layer->getName().string());
2465 ALOGV(" Composition type: %s",
2466 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002467 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 switch (layer->getCompositionType(hwcId)) {
2469 case HWC2::Composition::Cursor:
2470 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002471 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002473 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2475 layer->isOpaque(state) && (state.alpha == 1.0f)
2476 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002477 // never clear the very first layer since we're
2478 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002479 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002480 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 case HWC2::Composition::Client: {
2484 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002485 break;
2486 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002488 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002489 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 } else {
2491 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002492 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002494 }
2495 } else {
2496 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002498 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002500 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002502 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002503 }
2504 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002505
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002506 if (applyColorMatrix) {
2507 getRenderEngine().setupColorTransform(oldColorMatrix);
2508 }
2509
Mathias Agopianf45c5102012-10-24 16:29:17 -07002510 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002512 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513}
2514
Fabien Sanglard830b8472016-11-30 16:35:58 -08002515void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2516 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002517 RenderEngine& engine(getRenderEngine());
2518 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519}
2520
Dan Stoza7d89d062015-04-30 13:29:25 -07002521status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002522 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002523 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 const sp<Layer>& lbc,
2525 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002526{
Dan Stoza7d89d062015-04-30 13:29:25 -07002527 // add this layer to the current state list
2528 {
2529 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002531 return NO_MEMORY;
2532 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002533 if (parent == nullptr) {
2534 mCurrentState.layersSortedByZ.add(lbc);
2535 } else {
2536 parent->addChild(lbc);
2537 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002538 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 mLayersAdded = true;
2540 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002541 }
2542
Mathias Agopian96f08192010-06-02 23:28:45 -07002543 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002544 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002545
Dan Stoza7d89d062015-04-30 13:29:25 -07002546 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002547}
2548
Robert Carr9524cb32017-02-13 11:32:32 -08002549status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 const auto& p = layer->getParent();
2551 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2552 mCurrentState.layersSortedByZ.remove(layer);
2553
Robert Carr136e2f62017-02-08 17:54:29 -08002554 // As a matter of normal operation, the LayerCleaner will produce a second
2555 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2556 // so we will succeed in promoting it, but it's already been removed
2557 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2558 // otherwise something has gone wrong and we are leaking the layer.
2559 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002560 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2561 layer->getName().string(),
2562 (p != nullptr) ? p->getName().string() : "no-parent");
2563 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002564 } else if (index < 0) {
2565 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002566 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567
2568 mLayersPendingRemoval.add(layer);
2569 mLayersRemoved = true;
2570 mNumLayers--;
2571 setTransactionFlags(eTransactionNeeded);
2572 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573}
2574
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002575uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002576 return android_atomic_release_load(&mTransactionFlags);
2577}
2578
Mathias Agopian3f844832013-08-07 21:24:32 -07002579uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2581}
2582
Mathias Agopian3f844832013-08-07 21:24:32 -07002583uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2585 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002586 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588 return old;
2589}
2590
Mathias Agopian8b33f032012-07-24 20:43:54 -07002591void SurfaceFlinger::setTransactionState(
2592 const Vector<ComposerState>& state,
2593 const Vector<DisplayState>& displays,
2594 uint32_t flags)
2595{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002596 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002597 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002598 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002599
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002600 if (flags & eAnimation) {
2601 // For window updates that are part of an animation we must wait for
2602 // previous animation "frames" to be handled.
2603 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002604 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002605 if (CC_UNLIKELY(err != NO_ERROR)) {
2606 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002607 // caller after a few seconds.
2608 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2609 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002610 mAnimTransactionPending = false;
2611 break;
2612 }
2613 }
2614 }
2615
Mathias Agopiane57f2922012-08-09 16:29:12 -07002616 size_t count = displays.size();
2617 for (size_t i=0 ; i<count ; i++) {
2618 const DisplayState& s(displays[i]);
2619 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002620 }
2621
Mathias Agopiane57f2922012-08-09 16:29:12 -07002622 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002623 for (size_t i=0 ; i<count ; i++) {
2624 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002625 // Here we need to check that the interface we're given is indeed
2626 // one of our own. A malicious client could give us a NULL
2627 // IInterface, or one of its own or even one of our own but a
2628 // different type. All these situations would cause us to crash.
2629 //
2630 // NOTE: it would be better to use RTTI as we could directly check
2631 // that we have a Client*. however, RTTI is disabled in Android.
2632 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002633 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002634 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002635 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002636 sp<Client> client( static_cast<Client *>(s.client.get()) );
2637 transactionFlags |= setClientStateLocked(client, s.state);
2638 }
2639 }
2640 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002641 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002642
Robert Carr2a7dbb42016-05-24 11:41:28 -07002643 // If a synchronous transaction is explicitly requested without any changes,
2644 // force a transaction anyway. This can be used as a flush mechanism for
2645 // previous async transactions.
2646 if (transactionFlags == 0 && (flags & eSynchronous)) {
2647 transactionFlags = eTransactionNeeded;
2648 }
2649
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002651 if (mInterceptor.isEnabled()) {
2652 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2653 }
Irvel468051e2016-06-13 16:44:44 -07002654
Mathias Agopian386aa982011-11-07 21:58:03 -08002655 // this triggers the transaction
2656 setTransactionFlags(transactionFlags);
2657
2658 // if this is a synchronous transaction, wait for it to take effect
2659 // before returning.
2660 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002661 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002662 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002663 if (flags & eAnimation) {
2664 mAnimTransactionPending = true;
2665 }
2666 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002667 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2668 if (CC_UNLIKELY(err != NO_ERROR)) {
2669 // just in case something goes wrong in SF, return to the
2670 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002671 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2672 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002673 break;
2674 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 }
2677}
2678
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2680{
Jesse Hall9a143922012-10-04 16:29:19 -07002681 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2682 if (dpyIdx < 0)
2683 return 0;
2684
Mathias Agopiane57f2922012-08-09 16:29:12 -07002685 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002686 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002687 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002688 const uint32_t what = s.what;
2689 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002690 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002691 disp.surface = s.surface;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 }
2695 if (what & DisplayState::eLayerStackChanged) {
2696 if (disp.layerStack != s.layerStack) {
2697 disp.layerStack = s.layerStack;
2698 flags |= eDisplayTransactionNeeded;
2699 }
2700 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002701 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002702 if (disp.orientation != s.orientation) {
2703 disp.orientation = s.orientation;
2704 flags |= eDisplayTransactionNeeded;
2705 }
2706 if (disp.frame != s.frame) {
2707 disp.frame = s.frame;
2708 flags |= eDisplayTransactionNeeded;
2709 }
2710 if (disp.viewport != s.viewport) {
2711 disp.viewport = s.viewport;
2712 flags |= eDisplayTransactionNeeded;
2713 }
2714 }
Michael Lentine47e45402014-07-18 15:34:25 -07002715 if (what & DisplayState::eDisplaySizeChanged) {
2716 if (disp.width != s.width) {
2717 disp.width = s.width;
2718 flags |= eDisplayTransactionNeeded;
2719 }
2720 if (disp.height != s.height) {
2721 disp.height = s.height;
2722 flags |= eDisplayTransactionNeeded;
2723 }
2724 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002725 }
2726 return flags;
2727}
2728
2729uint32_t SurfaceFlinger::setClientStateLocked(
2730 const sp<Client>& client,
2731 const layer_state_t& s)
2732{
2733 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002734 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 if (layer != 0) {
2736 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002737 bool geometryAppliesWithResize =
2738 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002739 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002740 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002742 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 }
2744 if (what & layer_state_t::eLayerChanged) {
2745 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 const auto& p = layer->getParent();
2747 if (p == nullptr) {
2748 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2749 if (layer->setLayer(s.z) && idx >= 0) {
2750 mCurrentState.layersSortedByZ.removeAt(idx);
2751 mCurrentState.layersSortedByZ.add(layer);
2752 // we need traversal (state changed)
2753 // AND transaction (list changed)
2754 flags |= eTransactionNeeded|eTraversalNeeded;
2755 }
2756 } else {
2757 if (p->setChildLayer(layer, s.z)) {
2758 flags |= eTransactionNeeded|eTraversalNeeded;
2759 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002760 }
2761 }
2762 if (what & layer_state_t::eSizeChanged) {
2763 if (layer->setSize(s.w, s.h)) {
2764 flags |= eTraversalNeeded;
2765 }
2766 }
2767 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002769 flags |= eTraversalNeeded;
2770 }
2771 if (what & layer_state_t::eMatrixChanged) {
2772 if (layer->setMatrix(s.matrix))
2773 flags |= eTraversalNeeded;
2774 }
2775 if (what & layer_state_t::eTransparentRegionChanged) {
2776 if (layer->setTransparentRegionHint(s.transparentRegion))
2777 flags |= eTraversalNeeded;
2778 }
Dan Stoza23116082015-06-18 14:58:39 -07002779 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 if (layer->setFlags(s.flags, s.mask))
2781 flags |= eTraversalNeeded;
2782 }
2783 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002784 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002785 flags |= eTraversalNeeded;
2786 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002787 if (what & layer_state_t::eFinalCropChanged) {
2788 if (layer->setFinalCrop(s.finalCrop))
2789 flags |= eTraversalNeeded;
2790 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 // We only allow setting layer stacks for top level layers,
2794 // everything else inherits layer stack from its parent.
2795 if (layer->hasParent()) {
2796 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2797 layer->getName().string());
2798 } else if (idx < 0) {
2799 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2800 "that also does not appear in the top level layer list. Something"
2801 " has gone wrong.", layer->getName().string());
2802 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002803 mCurrentState.layersSortedByZ.removeAt(idx);
2804 mCurrentState.layersSortedByZ.add(layer);
2805 // we need traversal (state changed)
2806 // AND transaction (list changed)
2807 flags |= eTransactionNeeded|eTraversalNeeded;
2808 }
2809 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002810 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002811 if (s.barrierHandle != nullptr) {
2812 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2813 } else if (s.barrierGbp != nullptr) {
2814 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2815 if (authenticateSurfaceTextureLocked(gbp)) {
2816 const auto& otherLayer =
2817 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2818 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2819 } else {
2820 ALOGE("Attempt to defer transaction to to an"
2821 " unrecognized GraphicBufferProducer");
2822 }
2823 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002824 // We don't trigger a traversal here because if no other state is
2825 // changed, we don't want this to cause any more work
2826 }
Robert Carr1db73f62016-12-21 12:58:51 -08002827 if (what & layer_state_t::eReparentChildren) {
2828 if (layer->reparentChildren(s.reparentHandle)) {
2829 flags |= eTransactionNeeded|eTraversalNeeded;
2830 }
2831 }
Robert Carr9524cb32017-02-13 11:32:32 -08002832 if (what & layer_state_t::eDetachChildren) {
2833 layer->detachChildren();
2834 }
Robert Carrc3574f72016-03-24 12:19:32 -07002835 if (what & layer_state_t::eOverrideScalingModeChanged) {
2836 layer->setOverrideScalingMode(s.overrideScalingMode);
2837 // We don't trigger a traversal here because if no other state is
2838 // changed, we don't want this to cause any more work
2839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 }
2841 return flags;
2842}
2843
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002844status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002845 const String8& name,
2846 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002847 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002848 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2849 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002851 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002852 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002853 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002854 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002855 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002856
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002857 status_t result = NO_ERROR;
2858
2859 sp<Layer> layer;
2860
Mathias Agopian3165cc22012-08-08 19:42:09 -07002861 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2862 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002863 result = createNormalLayer(client,
2864 name, w, h, flags, format,
2865 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002867 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002868 result = createDimLayer(client,
2869 name, w, h, flags,
2870 handle, gbp, &layer);
2871 break;
2872 default:
2873 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 break;
2875 }
2876
Dan Stoza7d89d062015-04-30 13:29:25 -07002877 if (result != NO_ERROR) {
2878 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002880
Albert Chaulk479c60c2017-01-27 14:21:34 -05002881 layer->setInfo(windowType, ownerUid);
2882
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002884 if (result != NO_ERROR) {
2885 return result;
2886 }
Irvelffc9efc2016-07-27 15:16:37 -07002887 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002888
2889 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002890 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2894 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2895 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
2897 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002898 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899 case PIXEL_FORMAT_TRANSPARENT:
2900 case PIXEL_FORMAT_TRANSLUCENT:
2901 format = PIXEL_FORMAT_RGBA_8888;
2902 break;
2903 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002904 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 break;
2906 }
2907
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002908 *outLayer = new Layer(this, client, name, w, h, flags);
2909 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2910 if (err == NO_ERROR) {
2911 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002912 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002914
2915 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2916 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917}
2918
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002919status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2920 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2921 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002923 *outLayer = new LayerDim(this, client, name, w, h, flags);
2924 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002925 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002926 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002927}
2928
Mathias Agopianac9fa422013-02-11 16:40:36 -08002929status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930{
Robert Carr9524cb32017-02-13 11:32:32 -08002931 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002932 status_t err = NO_ERROR;
2933 sp<Layer> l(client->getLayerUser(handle));
2934 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002935 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002936 err = removeLayer(l);
2937 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2938 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002939 }
2940 return err;
2941}
2942
Mathias Agopian13127d82013-03-05 17:47:11 -08002943status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002944{
Mathias Agopian67106042013-03-14 19:18:13 -07002945 // called by ~LayerCleaner() when all references to the IBinder (handle)
2946 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002947 sp<Layer> l = layer.promote();
2948 if (l == nullptr) {
2949 // The layer has already been removed, carry on
2950 return NO_ERROR;
2951 } if (l->getParent() != nullptr) {
2952 // If we have a parent, then we can continue to live as long as it does.
2953 return NO_ERROR;
2954 }
2955 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956}
2957
Mathias Agopianb60314a2012-04-10 22:09:54 -07002958// ---------------------------------------------------------------------------
2959
Andy McFadden13a082e2012-08-24 10:16:42 -07002960void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002961 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002962 Vector<ComposerState> state;
2963 Vector<DisplayState> displays;
2964 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002965 d.what = DisplayState::eDisplayProjectionChanged |
2966 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002967 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002968 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002969 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002970 d.frame.makeInvalid();
2971 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002972 d.width = 0;
2973 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002974 displays.add(d);
2975 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002977
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2979 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002980 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002981
2982 {
2983 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2984 mCompositorTiming.interval = period;
2985 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002986}
2987
2988void SurfaceFlinger::initializeDisplays() {
2989 class MessageScreenInitialized : public MessageBase {
2990 SurfaceFlinger* flinger;
2991 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002992 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002993 virtual bool handler() {
2994 flinger->onInitializeDisplays();
2995 return true;
2996 }
2997 };
2998 sp<MessageBase> msg = new MessageScreenInitialized(this);
2999 postMessageAsync(msg); // we may be called from main thread, use async message
3000}
3001
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003002void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3003 int mode) {
3004 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3005 this);
3006 int32_t type = hw->getDisplayType();
3007 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003008
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003009 if (mode == currentMode) {
3010 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003011 return;
3012 }
3013
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003014 hw->setPowerMode(mode);
3015 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3016 ALOGW("Trying to set power mode for virtual display");
3017 return;
3018 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003019
Irvelffc9efc2016-07-27 15:16:37 -07003020 if (mInterceptor.isEnabled()) {
3021 Mutex::Autolock _l(mStateLock);
3022 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3023 if (idx < 0) {
3024 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3025 return;
3026 }
3027 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3028 }
3029
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003030 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003031 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003032 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3034 // FIXME: eventthread only knows about the main display right now
3035 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003036 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003039 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003040 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003042
3043 struct sched_param param = {0};
3044 param.sched_priority = 1;
3045 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3046 ALOGW("Couldn't set SCHED_FIFO on display on");
3047 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003049 // Turn off the display
3050 struct sched_param param = {0};
3051 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3052 ALOGW("Couldn't set SCHED_OTHER on display off");
3053 }
3054
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003055 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003056 disableHardwareVsync(true); // also cancels any in-progress resync
3057
Mathias Agopiancde87a32012-09-13 14:09:01 -07003058 // FIXME: eventthread only knows about the main display right now
3059 mEventThread->onScreenReleased();
3060 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003061
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003062 getHwComposer().setPowerMode(type, mode);
3063 mVisibleRegionsDirty = true;
3064 // from this point on, SF will stop drawing on this display
3065 } else {
3066 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003068}
3069
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003070void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3071 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003072 SurfaceFlinger& mFlinger;
3073 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003074 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003075 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003076 MessageSetPowerMode(SurfaceFlinger& flinger,
3077 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3078 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003079 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003080 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003081 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003082 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003083 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003084 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003085 ALOGW("Attempt to set power mode = %d for virtual display",
3086 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003087 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003089 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003090 return true;
3091 }
3092 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003093 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003094 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003095}
3096
3097// ---------------------------------------------------------------------------
3098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3100{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003102
Mathias Agopianbd115332013-04-18 16:41:04 -07003103 IPCThreadState* ipc = IPCThreadState::self();
3104 const int pid = ipc->getCallingPid();
3105 const int uid = ipc->getCallingUid();
3106 if ((uid != AID_SHELL) &&
3107 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003108 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003109 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003111 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003112 // (this would indicate SF is stuck, but we want to be able to
3113 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003114 status_t err = mStateLock.timedLock(s2ns(1));
3115 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003116 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003117 result.appendFormat(
3118 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3119 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003120 }
3121
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003122 bool dumpAll = true;
3123 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003124 size_t numArgs = args.size();
3125 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003126 if ((index < numArgs) &&
3127 (args[index] == String16("--list"))) {
3128 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003129 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003130 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003131 }
3132
3133 if ((index < numArgs) &&
3134 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003136 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003137 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003138 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003139
3140 if ((index < numArgs) &&
3141 (args[index] == String16("--latency-clear"))) {
3142 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003143 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003144 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003145 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003146
3147 if ((index < numArgs) &&
3148 (args[index] == String16("--dispsync"))) {
3149 index++;
3150 mPrimaryDispSync.dump(result);
3151 dumpAll = false;
3152 }
Dan Stozab90cf072015-03-05 11:05:59 -08003153
3154 if ((index < numArgs) &&
3155 (args[index] == String16("--static-screen"))) {
3156 index++;
3157 dumpStaticScreenStats(result);
3158 dumpAll = false;
3159 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003160
3161 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003162 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003163 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003164 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003165 dumpAll = false;
3166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003168
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003169 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003170 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003171 }
3172
Mathias Agopian9795c422009-08-26 16:36:26 -07003173 if (locked) {
3174 mStateLock.unlock();
3175 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 }
3177 write(fd, result.string(), result.size());
3178 return NO_ERROR;
3179}
3180
Dan Stozac7014012014-02-14 15:03:43 -08003181void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3182 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003183{
Robert Carr2047fae2016-11-28 14:09:09 -08003184 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003185 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003186 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003187}
3188
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003189void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003190 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003191{
3192 String8 name;
3193 if (index < args.size()) {
3194 name = String8(args[index]);
3195 index++;
3196 }
3197
Dan Stoza9e56aa02015-11-02 13:00:03 -08003198 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3199 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003200 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003201
3202 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003203 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003204 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003206 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003207 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003208 }
Robert Carr2047fae2016-11-28 14:09:09 -08003209 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003210 }
3211}
3212
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003213void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003214 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003215{
3216 String8 name;
3217 if (index < args.size()) {
3218 name = String8(args[index]);
3219 index++;
3220 }
3221
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003223 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003224 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003225 }
Robert Carr2047fae2016-11-28 14:09:09 -08003226 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003227
Svetoslavd85084b2014-03-20 10:28:31 -07003228 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003229}
3230
Jamie Gennis6547ff42013-07-16 20:12:42 -07003231// This should only be called from the main thread. Otherwise it would need
3232// the lock and should use mCurrentState rather than mDrawingState.
3233void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003234 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003235 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003236 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003237
3238 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3239}
3240
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003241void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003242{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003243 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003244#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003245 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003246#endif
3247#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003248 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003249#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003250 if (isLayerTripleBufferingDisabled())
3251 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003252 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003253}
3254
Dan Stozab90cf072015-03-05 11:05:59 -08003255void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3256{
3257 result.appendFormat("Static screen stats:\n");
3258 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3259 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3260 float percent = 100.0f *
3261 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3262 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3263 b + 1, bucketTimeSec, percent);
3264 }
3265 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3266 float percent = 100.0f *
3267 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3268 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3269 NUM_BUCKETS - 1, bucketTimeSec, percent);
3270}
3271
Dan Stozae77c7662016-05-13 11:37:28 -07003272void SurfaceFlinger::recordBufferingStats(const char* layerName,
3273 std::vector<OccupancyTracker::Segment>&& history) {
3274 Mutex::Autolock lock(mBufferingStatsMutex);
3275 auto& stats = mBufferingStats[layerName];
3276 for (const auto& segment : history) {
3277 if (!segment.usedThirdBuffer) {
3278 stats.twoBufferTime += segment.totalTime;
3279 }
3280 if (segment.occupancyAverage < 1.0f) {
3281 stats.doubleBufferedTime += segment.totalTime;
3282 } else if (segment.occupancyAverage < 2.0f) {
3283 stats.tripleBufferedTime += segment.totalTime;
3284 }
3285 ++stats.numSegments;
3286 stats.totalTime += segment.totalTime;
3287 }
3288}
3289
Brian Andersond6927fb2016-07-23 23:37:30 -07003290void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3291 result.appendFormat("Layer frame timestamps:\n");
3292
3293 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3294 const size_t count = currentLayers.size();
3295 for (size_t i=0 ; i<count ; i++) {
3296 currentLayers[i]->dumpFrameEvents(result);
3297 }
3298}
3299
Dan Stozae77c7662016-05-13 11:37:28 -07003300void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3301 result.append("Buffering stats:\n");
3302 result.append(" [Layer name] <Active time> <Two buffer> "
3303 "<Double buffered> <Triple buffered>\n");
3304 Mutex::Autolock lock(mBufferingStatsMutex);
3305 typedef std::tuple<std::string, float, float, float> BufferTuple;
3306 std::map<float, BufferTuple, std::greater<float>> sorted;
3307 for (const auto& statsPair : mBufferingStats) {
3308 const char* name = statsPair.first.c_str();
3309 const BufferingStats& stats = statsPair.second;
3310 if (stats.numSegments == 0) {
3311 continue;
3312 }
3313 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3314 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3315 stats.totalTime;
3316 float doubleBufferRatio = static_cast<float>(
3317 stats.doubleBufferedTime) / stats.totalTime;
3318 float tripleBufferRatio = static_cast<float>(
3319 stats.tripleBufferedTime) / stats.totalTime;
3320 sorted.insert({activeTime, {name, twoBufferRatio,
3321 doubleBufferRatio, tripleBufferRatio}});
3322 }
3323 for (const auto& sortedPair : sorted) {
3324 float activeTime = sortedPair.first;
3325 const BufferTuple& values = sortedPair.second;
3326 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3327 std::get<0>(values).c_str(), activeTime,
3328 std::get<1>(values), std::get<2>(values),
3329 std::get<3>(values));
3330 }
3331 result.append("\n");
3332}
3333
3334
Mathias Agopian74d211a2013-04-22 16:55:35 +02003335void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3336 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003337{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003338 bool colorize = false;
3339 if (index < args.size()
3340 && (args[index] == String16("--color"))) {
3341 colorize = true;
3342 index++;
3343 }
3344
3345 Colorizer colorizer(colorize);
3346
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003347 // figure out if we're stuck somewhere
3348 const nsecs_t now = systemTime();
3349 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3350 const nsecs_t inTransaction(mDebugInTransaction);
3351 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3352 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3353
3354 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003355 * Dump library configuration.
3356 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003357
3358 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003359 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003361 appendSfConfigString(result);
3362 appendUiConfigString(result);
3363 appendGuiConfigString(result);
3364 result.append("\n");
3365
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003366 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003367 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003368 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003369 result.append(SyncFeatures::getInstance().toString());
3370 result.append("\n");
3371
Dan Stoza9e56aa02015-11-02 13:00:03 -08003372 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3373
Andy McFadden41d67d72014-04-25 16:58:34 -07003374 colorizer.bold(result);
3375 result.append("DispSync configuration: ");
3376 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003377 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3378 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003379 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3380 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003381 result.append("\n");
3382
Dan Stozab90cf072015-03-05 11:05:59 -08003383 // Dump static screen stats
3384 result.append("\n");
3385 dumpStaticScreenStats(result);
3386 result.append("\n");
3387
Dan Stozae77c7662016-05-13 11:37:28 -07003388 dumpBufferingStats(result);
3389
Andy McFadden4803b742012-09-24 19:07:20 -07003390 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003391 * Dump the visible layer list
3392 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003393 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003394 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003395 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003396 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003397 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003398 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003399
3400 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003401 * Dump Display state
3402 */
3403
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003404 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003405 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003406 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003407 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3408 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003409 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003410 }
3411
3412 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003413 * Dump SurfaceFlinger global state
3414 */
3415
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003416 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003417 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003418 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419
Mathias Agopian888c8222012-08-04 21:10:38 -07003420 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003421 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003422
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003423 colorizer.bold(result);
3424 result.appendFormat("EGL implementation : %s\n",
3425 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3426 colorizer.reset(result);
3427 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003428 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003429
Mathias Agopian875d8e12013-06-07 15:35:48 -07003430 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431
Mathias Agopian42977342012-08-05 00:40:46 -07003432 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003433 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3434 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003435 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436 " last eglSwapBuffers() time: %f us\n"
3437 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003438 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003439 " refresh-rate : %f fps\n"
3440 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003441 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003442 " gpu_to_cpu_unsupported : %d\n"
3443 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003444 mLastSwapBufferTime/1000.0,
3445 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003446 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003447 1e9 / activeConfig->getVsyncPeriod(),
3448 activeConfig->getDpiX(),
3449 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003450 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003451
Mathias Agopian74d211a2013-04-22 16:55:35 +02003452 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003453 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003454
Mathias Agopian74d211a2013-04-22 16:55:35 +02003455 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457
3458 /*
3459 * VSYNC state
3460 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003461 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003462 result.append("\n");
3463
3464 /*
3465 * HWC layer minidump
3466 */
3467 for (size_t d = 0; d < mDisplays.size(); d++) {
3468 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3469 int32_t hwcId = displayDevice->getHwcDisplayId();
3470 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3471 continue;
3472 }
3473
3474 result.appendFormat("Display %d HWC layers:\n", hwcId);
3475 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003476 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003477 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 });
Dan Stozae22aec72016-08-01 13:20:59 -07003479 result.append("\n");
3480 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003481
3482 /*
3483 * Dump HWComposer state
3484 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003485 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003486 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003487 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003488 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003489 result.appendFormat(" h/w composer %s\n",
3490 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003491 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003492
3493 /*
3494 * Dump gralloc state
3495 */
3496 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3497 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003498}
3499
Mathias Agopian13127d82013-03-05 17:47:11 -08003500const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003501SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003502 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003503 wp<IBinder> dpy;
3504 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3505 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3506 dpy = mDisplays.keyAt(i);
3507 break;
3508 }
3509 }
3510 if (dpy == NULL) {
3511 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3512 // Just use the primary display so we have something to return
3513 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3514 }
3515 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003516}
3517
Keun young Park63f165f2012-08-31 10:53:36 -07003518bool SurfaceFlinger::startDdmConnection()
3519{
3520 void* libddmconnection_dso =
3521 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3522 if (!libddmconnection_dso) {
3523 return false;
3524 }
3525 void (*DdmConnection_start)(const char* name);
3526 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003527 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003528 if (!DdmConnection_start) {
3529 dlclose(libddmconnection_dso);
3530 return false;
3531 }
3532 (*DdmConnection_start)(getServiceName());
3533 return true;
3534}
3535
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003536status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 switch (code) {
3538 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003539 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003541 case CLEAR_ANIMATION_FRAME_STATS:
3542 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003543 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003544 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545 {
3546 // codes that require permission check
3547 IPCThreadState* ipc = IPCThreadState::self();
3548 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003549 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003550 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003551 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003552 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003553 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003555 break;
3556 }
Robert Carr1db73f62016-12-21 12:58:51 -08003557 /*
3558 * Calling setTransactionState is safe, because you need to have been
3559 * granted a reference to Client* and Handle* to do anything with it.
3560 *
3561 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3562 */
3563 case SET_TRANSACTION_STATE:
3564 case CREATE_SCOPED_CONNECTION:
3565 {
3566 return OK;
3567 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003568 case CAPTURE_SCREEN:
3569 {
3570 // codes that require permission check
3571 IPCThreadState* ipc = IPCThreadState::self();
3572 const int pid = ipc->getCallingPid();
3573 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003574 if ((uid != AID_GRAPHICS) &&
3575 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003576 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003577 return PERMISSION_DENIED;
3578 }
3579 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 }
3581 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003582 return OK;
3583}
3584
3585status_t SurfaceFlinger::onTransact(
3586 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3587{
3588 status_t credentialCheck = CheckTransactCodeCredentials(code);
3589 if (credentialCheck != OK) {
3590 return credentialCheck;
3591 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3594 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003595 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003596 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003597 IPCThreadState* ipc = IPCThreadState::self();
3598 const int pid = ipc->getCallingPid();
3599 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003600 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003601 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 return PERMISSION_DENIED;
3603 }
3604 int n;
3605 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003606 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003607 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 return NO_ERROR;
3609 case 1002: // SHOW_UPDATES
3610 n = data.readInt32();
3611 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003612 invalidateHwcGeometry();
3613 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003616 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003617 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003619 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003620 setTransactionFlags(
3621 eTransactionNeeded|
3622 eDisplayTransactionNeeded|
3623 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003624 return NO_ERROR;
3625 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003626 case 1006:{ // send empty update
3627 signalRefresh();
3628 return NO_ERROR;
3629 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003630 case 1008: // toggle use of hw composer
3631 n = data.readInt32();
3632 mDebugDisableHWC = n ? 1 : 0;
3633 invalidateHwcGeometry();
3634 repaintEverything();
3635 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003636 case 1009: // toggle use of transform hint
3637 n = data.readInt32();
3638 mDebugDisableTransformHint = n ? 1 : 0;
3639 invalidateHwcGeometry();
3640 repaintEverything();
3641 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003643 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 reply->writeInt32(0);
3645 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003646 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003647 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 return NO_ERROR;
3649 case 1013: {
3650 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003651 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3652 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003653 return NO_ERROR;
3654 }
3655 case 1014: {
3656 // daltonize
3657 n = data.readInt32();
3658 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003659 case 1:
3660 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3661 break;
3662 case 2:
3663 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3664 break;
3665 case 3:
3666 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3667 break;
3668 default:
3669 mDaltonizer.setType(ColorBlindnessType::None);
3670 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003671 }
3672 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003673 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003674 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003675 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003676 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003677 invalidateHwcGeometry();
3678 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003681 case 1015: {
3682 // apply a color matrix
3683 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003684 if (n) {
3685 // color matrix is sent as mat3 matrix followed by vec3
3686 // offset, then packed into a mat4 where the last row is
3687 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003688 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003689 for (size_t j = 0; j < 4; j++) {
3690 mColorMatrix[i][j] = data.readFloat();
3691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003692 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003693 } else {
3694 mColorMatrix = mat4();
3695 }
3696 invalidateHwcGeometry();
3697 repaintEverything();
3698 return NO_ERROR;
3699 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003700 // This is an experimental interface
3701 // Needs to be shifted to proper binder interface when we productize
3702 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003703 n = data.readInt32();
3704 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003705 return NO_ERROR;
3706 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003707 case 1017: {
3708 n = data.readInt32();
3709 mForceFullDamage = static_cast<bool>(n);
3710 return NO_ERROR;
3711 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003712 case 1018: { // Modify Choreographer's phase offset
3713 n = data.readInt32();
3714 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3715 return NO_ERROR;
3716 }
3717 case 1019: { // Modify SurfaceFlinger's phase offset
3718 n = data.readInt32();
3719 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3720 return NO_ERROR;
3721 }
Irvel468051e2016-06-13 16:44:44 -07003722 case 1020: { // Layer updates interceptor
3723 n = data.readInt32();
3724 if (n) {
3725 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003726 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003727 }
3728 else{
3729 ALOGV("Interceptor disabled");
3730 mInterceptor.disable();
3731 }
3732 return NO_ERROR;
3733 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003734 case 1021: { // Disable HWC virtual displays
3735 n = data.readInt32();
3736 mUseHwcVirtualDisplays = !n;
3737 return NO_ERROR;
3738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 }
3740 }
3741 return err;
3742}
3743
Mathias Agopian53331da2011-08-22 21:44:41 -07003744void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003745 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003746 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003747}
3748
Mathias Agopian59119e62010-10-11 12:37:43 -07003749// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003750// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003751// ---------------------------------------------------------------------------
3752
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753/* The code below is here to handle b/8734824
3754 *
3755 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003756 * from the surfaceflinger thread to the calling binder thread, where they
3757 * are executed. This allows the calling thread in the calling process to be
3758 * reused and not depend on having "enough" binder threads to handle the
3759 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003760 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003761class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003762 /* Parts of GraphicProducerWrapper are run on two different threads,
3763 * communicating by sending messages via Looper but also by shared member
3764 * data. Coherence maintenance is subtle and in places implicit (ugh).
3765 *
3766 * Don't rely on Looper's sendMessage/handleMessage providing
3767 * release/acquire semantics for any data not actually in the Message.
3768 * Data going from surfaceflinger to binder threads needs to be
3769 * synchronized explicitly.
3770 *
3771 * Barrier open/wait do provide release/acquire semantics. This provides
3772 * implicit synchronization for data coming back from binder to
3773 * surfaceflinger threads.
3774 */
3775
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003776 sp<IGraphicBufferProducer> impl;
3777 sp<Looper> looper;
3778 status_t result;
3779 bool exitPending;
3780 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003781 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003782 uint32_t code;
3783 Parcel const* data;
3784 Parcel* reply;
3785
3786 enum {
3787 MSG_API_CALL,
3788 MSG_EXIT
3789 };
3790
3791 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003792 * Called on surfaceflinger thread. This is called by our "fake"
3793 * BpGraphicBufferProducer. We package the data and reply Parcel and
3794 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 */
3796 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003797 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 this->code = code;
3799 this->data = &data;
3800 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003801 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003802 // if we've exited, we run the message synchronously right here.
3803 // note (JH): as far as I can tell from looking at the code, this
3804 // never actually happens. if it does, i'm not sure if it happens
3805 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003806 handleMessage(Message(MSG_API_CALL));
3807 } else {
3808 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003809 // Prevent stores to this->{code, data, reply} from being
3810 // reordered later than the construction of Message.
3811 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 looper->sendMessage(this, Message(MSG_API_CALL));
3813 barrier.wait();
3814 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003815 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003816 }
3817
3818 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003819 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 * call the real BpGraphicBufferProducer.
3821 */
3822 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003823 int what = message.what;
3824 // Prevent reads below from happening before the read from Message
3825 atomic_thread_fence(memory_order_acquire);
3826 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003827 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003829 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003830 exitRequested = true;
3831 }
3832 }
3833
3834public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003835 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003836 : impl(impl),
3837 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003838 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003839 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003840 exitRequested(false),
3841 code(0),
3842 data(NULL),
3843 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003844 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003845
Jesse Hallb154c422014-07-13 12:47:02 -07003846 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003847 status_t waitForResponse() {
3848 do {
3849 looper->pollOnce(-1);
3850 } while (!exitRequested);
3851 return result;
3852 }
3853
Jesse Hallb154c422014-07-13 12:47:02 -07003854 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003855 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003856 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003857 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003858 // Ensure this->result is visible to the binder thread before it
3859 // handles the message.
3860 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003861 looper->sendMessage(this, Message(MSG_EXIT));
3862 }
3863};
3864
3865
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003866status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3867 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003868 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003869 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003870 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871
3872 if (CC_UNLIKELY(display == 0))
3873 return BAD_VALUE;
3874
3875 if (CC_UNLIKELY(producer == 0))
3876 return BAD_VALUE;
3877
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003878 // if we have secure windows on this display, never allow the screen capture
3879 // unless the producer interface is local (i.e.: we can take a screenshot for
3880 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003881 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003882
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003883 // Convert to surfaceflinger's internal rotation type.
3884 Transform::orientation_flags rotationFlags;
3885 switch (rotation) {
3886 case ISurfaceComposer::eRotateNone:
3887 rotationFlags = Transform::ROT_0;
3888 break;
3889 case ISurfaceComposer::eRotate90:
3890 rotationFlags = Transform::ROT_90;
3891 break;
3892 case ISurfaceComposer::eRotate180:
3893 rotationFlags = Transform::ROT_180;
3894 break;
3895 case ISurfaceComposer::eRotate270:
3896 rotationFlags = Transform::ROT_270;
3897 break;
3898 default:
3899 rotationFlags = Transform::ROT_0;
3900 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3901 break;
3902 }
3903
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003904 class MessageCaptureScreen : public MessageBase {
3905 SurfaceFlinger* flinger;
3906 sp<IBinder> display;
3907 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003908 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 uint32_t reqWidth, reqHeight;
3910 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003911 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003912 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003913 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003914 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003915 public:
3916 MessageCaptureScreen(SurfaceFlinger* flinger,
3917 const sp<IBinder>& display,
3918 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003919 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003920 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003921 bool useIdentityTransform,
3922 Transform::orientation_flags rotation,
3923 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003924 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003925 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003927 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003928 rotation(rotation), result(PERMISSION_DENIED),
3929 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003930 {
3931 }
3932 status_t getResult() const {
3933 return result;
3934 }
3935 virtual bool handler() {
3936 Mutex::Autolock _l(flinger->mStateLock);
3937 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003938 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003939 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003940 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003941 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003942 return true;
3943 }
3944 };
3945
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946 // this creates a "fake" BBinder which will serve as a "fake" remote
3947 // binder to receive the marshaled calls and forward them to the
3948 // real remote (a BpGraphicBufferProducer)
3949 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3950
3951 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3952 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003953 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003955 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003956 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003957
3958 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003959 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003960 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003961 }
3962 return res;
3963}
3964
Mathias Agopian180f10d2013-04-10 22:55:41 -07003965
3966void SurfaceFlinger::renderScreenImplLocked(
3967 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003968 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003969 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003970 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003971{
3972 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003973 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003974
3975 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003976 const int32_t hw_w = hw->getWidth();
3977 const int32_t hw_h = hw->getHeight();
3978 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003979 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003980
Dan Stozac1879002014-05-22 15:59:05 -07003981 // if a default or invalid sourceCrop is passed in, set reasonable values
3982 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3983 !sourceCrop.isValid()) {
3984 sourceCrop.setLeftTop(Point(0, 0));
3985 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3986 }
3987
3988 // ensure that sourceCrop is inside screen
3989 if (sourceCrop.left < 0) {
3990 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3991 }
Dan Stozabe31f442014-06-11 11:20:54 -07003992 if (sourceCrop.right > hw_w) {
3993 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003994 }
3995 if (sourceCrop.top < 0) {
3996 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3997 }
Dan Stozabe31f442014-06-11 11:20:54 -07003998 if (sourceCrop.bottom > hw_h) {
3999 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004000 }
4001
Mathias Agopian180f10d2013-04-10 22:55:41 -07004002 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004003 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004004
4005 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004006 engine.setViewportAndProjection(
4007 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004008 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004009
4010 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004011 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004012
Robert Carr1f0a16a2016-10-24 16:27:39 -07004013 // We loop through the first level of layers without traversing,
4014 // as we need to interpret min/max layer Z in the top level Z space.
4015 for (const auto& layer : mDrawingState.layersSortedByZ) {
4016 if (layer->getLayerStack() != hw->getLayerStack()) {
4017 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004018 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004019 const Layer::State& state(layer->getDrawingState());
4020 if (state.z < minLayerZ || state.z > maxLayerZ) {
4021 continue;
4022 }
4023 layer->traverseInZOrder([&](Layer* layer) {
4024 if (!layer->isVisible()) {
4025 return;
4026 }
4027 if (filtering) layer->setFiltering(true);
4028 layer->draw(hw, useIdentityTransform);
4029 if (filtering) layer->setFiltering(false);
4030 });
4031 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004032
Mathias Agopian931bda12013-08-28 18:11:46 -07004033 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004034}
4035
4036
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004037status_t SurfaceFlinger::captureScreenImplLocked(
4038 const sp<const DisplayDevice>& hw,
4039 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004040 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004041 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004042 bool useIdentityTransform, Transform::orientation_flags rotation,
4043 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004044{
4045 ATRACE_CALL();
4046
Mathias Agopian180f10d2013-04-10 22:55:41 -07004047 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004048 uint32_t hw_w = hw->getWidth();
4049 uint32_t hw_h = hw->getHeight();
4050
4051 if (rotation & Transform::ROT_90) {
4052 std::swap(hw_w, hw_h);
4053 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004054
Mathias Agopian180f10d2013-04-10 22:55:41 -07004055 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4056 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4057 reqWidth, reqHeight, hw_w, hw_h);
4058 return BAD_VALUE;
4059 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004060
Mathias Agopian180f10d2013-04-10 22:55:41 -07004061 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4062 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4063
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004064 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004065 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004066 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004067 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4068 (state.z < minLayerZ || state.z > maxLayerZ)) {
4069 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004070 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004071 layer->traverseInZOrder([&](Layer *layer) {
4072 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4073 layer->isSecure());
4074 });
4075 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004076
4077 if (!isLocalScreenshot && secureLayerIsVisible) {
4078 ALOGW("FB is protected: PERMISSION_DENIED");
4079 return PERMISSION_DENIED;
4080 }
4081
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004082 // create a surface (because we're a producer, and we need to
4083 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004084 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004085
4086 // Put the screenshot Surface into async mode so that
4087 // Layer::headFenceHasSignaled will always return true and we'll latch the
4088 // first buffer regardless of whether or not its acquire fence has
4089 // signaled. This is needed to avoid a race condition in the rotation
4090 // animation. See b/30209608
4091 sur->setAsyncMode(true);
4092
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004093 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004094
Michael Lentine5a16a622015-05-21 13:48:24 -07004095 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4096 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004097 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4098 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004099
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004100 int err = 0;
4101 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004102 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004103 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4104 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004105
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004106 if (err == NO_ERROR) {
4107 ANativeWindowBuffer* buffer;
4108 /* TODO: Once we have the sync framework everywhere this can use
4109 * server-side waits on the fence that dequeueBuffer returns.
4110 */
4111 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4112 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004113 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004114 // create an EGLImage from the buffer so we can later
4115 // turn it into a texture
4116 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4117 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4118 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004119 // this binds the given EGLImage as a framebuffer for the
4120 // duration of this scope.
4121 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4122 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004123 // this will in fact render into our dequeued buffer
4124 // via an FBO, which means we didn't have to create
4125 // an EGLSurface and therefore we're not
4126 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004127 renderScreenImplLocked(
4128 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4129 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004130
Riley Andrews86639902014-08-15 12:27:24 -07004131 // Attempt to create a sync khr object that can produce a sync point. If that
4132 // isn't available, create a non-dupable sync object in the fallback path and
4133 // wait on it directly.
4134 EGLSyncKHR sync;
4135 if (!DEBUG_SCREENSHOTS) {
4136 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004137 // native fence fd will not be populated until flush() is done.
4138 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004139 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004140 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004141 }
Riley Andrews86639902014-08-15 12:27:24 -07004142 if (sync != EGL_NO_SYNC_KHR) {
4143 // get the sync fd
4144 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4145 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4146 ALOGW("captureScreen: failed to dup sync khr object");
4147 syncFd = -1;
4148 }
4149 eglDestroySyncKHR(mEGLDisplay, sync);
4150 } else {
4151 // fallback path
4152 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4153 if (sync != EGL_NO_SYNC_KHR) {
4154 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4155 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4156 EGLint eglErr = eglGetError();
4157 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4158 ALOGW("captureScreen: fence wait timed out");
4159 } else {
4160 ALOGW_IF(eglErr != EGL_SUCCESS,
4161 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4162 }
4163 eglDestroySyncKHR(mEGLDisplay, sync);
4164 } else {
4165 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4166 }
4167 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004168 if (DEBUG_SCREENSHOTS) {
4169 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4170 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4171 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4172 hw, minLayerZ, maxLayerZ);
4173 delete [] pixels;
4174 }
4175
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004176 } else {
4177 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4178 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004179 window->cancelBuffer(window, buffer, syncFd);
4180 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004181 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004182 // destroy our image
4183 eglDestroyImageKHR(mEGLDisplay, image);
4184 } else {
4185 result = BAD_VALUE;
4186 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004187 if (buffer) {
4188 // queueBuffer takes ownership of syncFd
4189 result = window->queueBuffer(window, buffer, syncFd);
4190 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004191 }
4192 } else {
4193 result = BAD_VALUE;
4194 }
4195 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4196 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004197
Mathias Agopian74c40c02010-09-29 13:02:36 -07004198 return result;
4199}
4200
Mathias Agopiand5556842013-09-19 17:08:37 -07004201void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004202 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004203 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004204 for (size_t y=0 ; y<h ; y++) {
4205 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4206 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004207 if (p[x] != 0xFF000000) return;
4208 }
4209 }
4210 ALOGE("*** we just took a black screenshot ***\n"
4211 "requested minz=%d, maxz=%d, layerStack=%d",
4212 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004213
Robert Carr2047fae2016-11-28 14:09:09 -08004214 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004215 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004216 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004217 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4218 state.z <= maxLayerZ) {
4219 layer->traverseInZOrder([&](Layer* layer) {
4220 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4221 layer->isVisible() ? '+' : '-',
4222 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004223 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004224 i++;
4225 });
4226 }
4227 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004228 }
4229}
4230
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004231// ---------------------------------------------------------------------------
4232
Robert Carr2047fae2016-11-28 14:09:09 -08004233void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4234 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004235}
4236
Robert Carr2047fae2016-11-28 14:09:09 -08004237void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4238 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004239}
4240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004242
4243
4244#if defined(__gl_h_)
4245#error "don't include gl/gl.h in this file"
4246#endif
4247
4248#if defined(__gl2_h_)
4249#error "don't include gl2/gl2.h in this file"
4250#endif