blob: 215628de0fd56b3aaf82fa6e81783fe9dde6329c [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 Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
40
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Mathias Agopian921e6ac2012-07-23 23:11:29 -070044#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080049#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080078#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Mathias Agopianca088332013-03-28 17:44:13 -0700100EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107// This is the phase offset in nanoseconds of the software vsync event
108// relative to the vsync event reported by HWComposer. The software vsync
109// event is when SurfaceFlinger and Choreographer-based applications run each
110// frame.
111//
112// This phase offset allows adjustment of the minimum latency from application
113// wake-up (by Choregographer) time to the time at which the resulting window
114// image is displayed. This value may be either positive (after the HW vsync)
115// or negative (before the HW vsync). Setting it to 0 will result in a
116// minimum latency of two vsync periods because the app and SurfaceFlinger
117// will run just after the HW vsync. Setting it to a positive number will
118// result in the minimum latency being:
119//
120// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
121//
122// Note that reducing this latency makes it more likely for the applications
123// to not have their window content image ready in time. When this happens
124// the latency will end up being an additional vsync period, and animations
125// will hiccup. Therefore, this latency should be tuned somewhat
126// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900127static int64_t vsyncPhaseOffsetNs = getInt64<
128 ISurfaceFlingerConfigs,
129 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800132static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700149 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700150 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800151 mHwc(nullptr),
152 mRealHwc(nullptr),
153 mVrHwc(nullptr),
154 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800158 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800159 mAnimCompositionPending(false),
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),
Irvel468051e2016-06-13 16:44:44 -0700170 mInterceptor(),
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),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800179 mNumLayers(0),
180 mEnterVrMode(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181{
Steve Blocka19954a2012-01-04 20:05:49 +0000182 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183
184 // debugging stuff...
185 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mathias Agopianb4b17302013-03-20 18:36:41 -0700187 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700188 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190 property_get("debug.sf.showupdates", value, "0");
191 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700192
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700193 property_get("debug.sf.ddms", value, "0");
194 mDebugDDMS = atoi(value);
195 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700196 if (!startDdmConnection()) {
197 // start failed, and DDMS debugging not enabled
198 mDebugDDMS = 0;
199 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700201 ALOGI_IF(mDebugRegion, "showupdates enabled");
202 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700203
204 property_get("debug.sf.disable_backpressure", value, "0");
205 mPropagateBackpressure = !atoi(value);
206 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700207
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800208 property_get("debug.sf.enable_hwc_vds", value, "0");
209 mUseHwcVirtualDisplays = atoi(value);
210 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800211
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800212 property_get("ro.sf.disable_triple_buffer", value, "1");
213 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800214 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215}
216
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800217void SurfaceFlinger::onFirstRef()
218{
219 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220}
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222SurfaceFlinger::~SurfaceFlinger()
223{
Mathias Agopiana4912602012-07-12 14:25:33 -0700224 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
225 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
226 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800227
228 if (mVrStateCallbacks.get()) {
229 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
230 defaultServiceManager()->checkService(String16("vrmanager")));
231 if (vrManagerService.get()) {
232 vrManagerService->unregisterListener(mVrStateCallbacks);
233 }
234 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235}
236
Dan Stozac7014012014-02-14 15:03:43 -0800237void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238{
239 // the window manager died on us. prepare its eulogy.
240
Andy McFadden13a082e2012-08-24 10:16:42 -0700241 // restore initial conditions (default device unblank, etc)
242 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243
244 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700245 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800246}
247
Robert Carr1db73f62016-12-21 12:58:51 -0800248static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700249 status_t err = client->initCheck();
250 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800251 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 }
Robert Carr1db73f62016-12-21 12:58:51 -0800253 return nullptr;
254}
255
256sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
257 return initClient(new Client(this));
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
261 const sp<IGraphicBufferProducer>& gbp) {
262 if (authenticateSurfaceTexture(gbp) == false) {
263 return nullptr;
264 }
265 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
266 if (layer == nullptr) {
267 return nullptr;
268 }
269
270 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800271}
272
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700273sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
274 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700275{
276 class DisplayToken : public BBinder {
277 sp<SurfaceFlinger> flinger;
278 virtual ~DisplayToken() {
279 // no more references, this display must be terminated
280 Mutex::Autolock _l(flinger->mStateLock);
281 flinger->mCurrentState.displays.removeItem(this);
282 flinger->setTransactionFlags(eDisplayTransactionNeeded);
283 }
284 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700285 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700286 : flinger(flinger) {
287 }
288 };
289
290 sp<BBinder> token = new DisplayToken(this);
291
292 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700293 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700294 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700296 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 return token;
298}
299
Jesse Hall6c913be2013-08-08 12:15:49 -0700300void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
301 Mutex::Autolock _l(mStateLock);
302
303 ssize_t idx = mCurrentState.displays.indexOfKey(display);
304 if (idx < 0) {
305 ALOGW("destroyDisplay: invalid display token");
306 return;
307 }
308
309 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
310 if (!info.isVirtualDisplay()) {
311 ALOGE("destroyDisplay called for non-virtual display");
312 return;
313 }
Irvelffc9efc2016-07-27 15:16:37 -0700314 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700315 mCurrentState.displays.removeItemsAt(idx);
316 setTransactionFlags(eDisplayTransactionNeeded);
317}
318
Jesse Hall692c7232012-11-08 15:41:56 -0800319void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800320 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800321 ALOGW_IF(mBuiltinDisplays[type],
322 "Overwriting display token for display type %d", type);
323 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800324 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700325 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700327 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800328}
329
Mathias Agopiane57f2922012-08-09 16:29:12 -0700330sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700331 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700332 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
333 return NULL;
334 }
Jesse Hall692c7232012-11-08 15:41:56 -0800335 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336}
337
Jamie Gennis9a78c902011-01-12 18:30:40 -0800338sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
339{
340 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
341 return gba;
342}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344void SurfaceFlinger::bootFinished()
345{
Wei Wangb254fa32017-01-31 17:43:23 -0800346 if (mStartBootAnimThread->join() != NO_ERROR) {
347 ALOGE("Join StartBootAnimThread failed!");
348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 const nsecs_t now = systemTime();
350 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000351 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700352 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700353
354 // wait patiently for the window manager death
355 const String16 name("window");
356 sp<IBinder> window(defaultServiceManager()->getService(name));
357 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700358 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359 }
360
361 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 // formerly we would just kill the process, but we now ask it to exit so it
363 // can choose where to stop the animation.
364 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700365
366 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
367 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
368 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800369
370 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
371 defaultServiceManager()->checkService(String16("vrmanager")));
372 if (vrManagerService.get()) {
373 mVrStateCallbacks = new VrStateCallbacks(*this);
374 vrManagerService->registerListener(mVrStateCallbacks);
375 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376}
377
Mathias Agopian3f844832013-08-07 21:24:32 -0700378void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700380 RenderEngine& engine;
381 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700382 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700383 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
384 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385 }
386 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700388 return true;
389 }
390 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700391 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392}
393
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394class DispSyncSource : public VSyncSource, private DispSync::Callback {
395public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 const char* name) :
398 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700399 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700400 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000401 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
402 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700403 mDispSync(dispSync),
404 mCallbackMutex(),
405 mCallback(),
406 mVsyncMutex(),
407 mPhaseOffset(phaseOffset),
408 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 virtual ~DispSyncSource() {}
411
412 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700413 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700421 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700422 } else {
423 status_t err = mDispSync->removeEventListener(
424 static_cast<DispSync::Callback*>(this));
425 if (err != NO_ERROR) {
426 ALOGE("error unregistering vsync callback: %s (%d)",
427 strerror(-err), err);
428 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
433
434 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 mCallback = callback;
437 }
438
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 virtual void setPhaseOffset(nsecs_t phaseOffset) {
440 Mutex::Autolock lock(mVsyncMutex);
441
442 // Normalize phaseOffset to [0, period)
443 auto period = mDispSync->getPeriod();
444 phaseOffset %= period;
445 if (phaseOffset < 0) {
446 // If we're here, then phaseOffset is in (-period, 0). After this
447 // operation, it will be in (0, period)
448 phaseOffset += period;
449 }
450 mPhaseOffset = phaseOffset;
451
452 // If we're not enabled, we don't need to mess with the listeners
453 if (!mEnabled) {
454 return;
455 }
456
457 // Remove the listener with the old offset
458 status_t err = mDispSync->removeEventListener(
459 static_cast<DispSync::Callback*>(this));
460 if (err != NO_ERROR) {
461 ALOGE("error unregistering vsync callback: %s (%d)",
462 strerror(-err), err);
463 }
464
465 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 static_cast<DispSync::Callback*>(this));
468 if (err != NO_ERROR) {
469 ALOGE("error registering vsync callback: %s (%d)",
470 strerror(-err), err);
471 }
472 }
473
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474private:
475 virtual void onDispSyncEvent(nsecs_t when) {
476 sp<VSyncSource::Callback> callback;
477 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 callback = mCallback;
480
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700481 if (mTraceVsync) {
482 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700483 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 }
486
487 if (callback != NULL) {
488 callback->onVSyncEvent(when);
489 }
490 }
491
Tim Murray4a4e4a22016-04-19 16:29:23 +0000492 const char* const mName;
493
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 int mValue;
495
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700496 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 const String8 mVsyncOnLabel;
498 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501
502 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504
505 Mutex mVsyncMutex; // Protects the following
506 nsecs_t mPhaseOffset;
507 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508};
509
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700510class InjectVSyncSource : public VSyncSource {
511public:
512 InjectVSyncSource() {}
513
514 virtual ~InjectVSyncSource() {}
515
516 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback = callback;
519 }
520
521 virtual void onInjectSyncEvent(nsecs_t when) {
522 std::lock_guard<std::mutex> lock(mCallbackMutex);
523 mCallback->onVSyncEvent(when);
524 }
525
526 virtual void setVSyncEnabled(bool) {}
527 virtual void setPhaseOffset(nsecs_t) {}
528
529private:
530 std::mutex mCallbackMutex; // Protects the following
531 sp<VSyncSource::Callback> mCallback;
532};
533
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700535 ALOGI( "SurfaceFlinger's main thread ready to run. "
536 "Initializing graphics H/W...");
537
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900538 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
539
Dan Stoza9e56aa02015-11-02 13:00:03 -0800540 { // Autolock scope
541 Mutex::Autolock _l(mStateLock);
542
543 // initialize EGL for the default display
544 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
545 eglInitialize(mEGLDisplay, NULL, NULL);
546
547 // start the EventThread
548 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
549 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700550 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
552 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700553 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800554 mEventQueue.setEventThread(mSFEventThread);
555
Tim Murrayacff43d2016-07-29 13:57:24 -0700556 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700557 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700558 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700559 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
560 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
561 }
562
Dan Stoza9e56aa02015-11-02 13:00:03 -0800563 // Get a RenderEngine for the given display / config (can't fail)
564 mRenderEngine = RenderEngine::create(mEGLDisplay,
565 HAL_PIXEL_FORMAT_RGBA_8888);
566 }
567
568 // Drop the state lock while we initialize the hardware composer. We drop
569 // the lock because on creation, it will call back into SurfaceFlinger to
570 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800571 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800572 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800573 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800574 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
575
Jesse Hall692c7232012-11-08 15:41:56 -0800576 Mutex::Autolock _l(mStateLock);
577
Mathias Agopian875d8e12013-06-07 15:35:48 -0700578 // retrieve the EGL context that was selected/created
579 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700580
Mathias Agopianda27af92012-09-13 18:17:13 -0700581 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
582 "couldn't create EGLContext");
583
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 // make the GLContext current so that we can create textures when creating
585 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700586 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
587
Jamie Gennisd1700752013-10-14 12:22:52 -0700588 mEventControlThread = new EventControlThread(this);
589 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
590
Mathias Agopian92a979a2012-08-02 18:32:23 -0700591 // initialize our drawing state
592 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700593
Andy McFadden13a082e2012-08-24 10:16:42 -0700594 // set initial conditions (e.g. unblank default device)
595 initializeDisplays();
596
Dan Stoza4e637772016-07-28 13:31:51 -0700597 mRenderEngine->primeCache();
598
Wei Wangb254fa32017-01-31 17:43:23 -0800599 mStartBootAnimThread = new StartBootAnimThread();
600 if (mStartBootAnimThread->Start() != NO_ERROR) {
601 ALOGE("Run StartBootAnimThread failed!");
602 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800603
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700605}
606
Mathias Agopiana67e4182012-06-19 17:26:12 -0700607void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800608 // Start boot animation service by setting a property mailbox
609 // if property setting thread is already running, Start() will be just a NOP
610 mStartBootAnimThread->Start();
611 // Wait until property was set
612 if (mStartBootAnimThread->join() != NO_ERROR) {
613 ALOGE("Join StartBootAnimThread failed!");
614 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700615}
616
Mathias Agopian875d8e12013-06-07 15:35:48 -0700617size_t SurfaceFlinger::getMaxTextureSize() const {
618 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700619}
620
Mathias Agopian875d8e12013-06-07 15:35:48 -0700621size_t SurfaceFlinger::getMaxViewportDims() const {
622 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700623}
624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800626
Jamie Gennis582270d2011-08-17 18:19:00 -0700627bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800628 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800629 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800630 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700631 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800632}
633
Brian Anderson069b3652016-07-22 10:32:47 -0700634status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700635 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700636 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700637 FrameEvent::REQUESTED_PRESENT,
638 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700639 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700640 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700641 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700642 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700643 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700644 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700645 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700647 };
648 return NO_ERROR;
649}
650
Dan Stoza7f7da322014-05-02 15:26:25 -0700651status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
652 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700653 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700654 return BAD_VALUE;
655 }
656
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500657 if (!display.get())
658 return NAME_NOT_FOUND;
659
Jesse Hall692c7232012-11-08 15:41:56 -0800660 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700661 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800662 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700663 type = i;
664 break;
665 }
666 }
667
668 if (type < 0) {
669 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700670 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700671
Mathias Agopian8b736f12012-08-13 17:54:26 -0700672 // TODO: Not sure if display density should handled by SF any longer
673 class Density {
674 static int getDensityFromProperty(char const* propName) {
675 char property[PROPERTY_VALUE_MAX];
676 int density = 0;
677 if (property_get(propName, property, NULL) > 0) {
678 density = atoi(property);
679 }
680 return density;
681 }
682 public:
683 static int getEmuDensity() {
684 return getDensityFromProperty("qemu.sf.lcd_density"); }
685 static int getBuildDensity() {
686 return getDensityFromProperty("ro.sf.lcd_density"); }
687 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700688
Dan Stoza7f7da322014-05-02 15:26:25 -0700689 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700690
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700692 DisplayInfo info = DisplayInfo();
693
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 float xdpi = hwConfig->getDpiX();
695 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700696
697 if (type == DisplayDevice::DISPLAY_PRIMARY) {
698 // The density of the device is provided by a build property
699 float density = Density::getBuildDensity() / 160.0f;
700 if (density == 0) {
701 // the build doesn't provide a density -- this is wrong!
702 // use xdpi instead
703 ALOGE("ro.sf.lcd_density must be defined as a build property");
704 density = xdpi / 160.0f;
705 }
706 if (Density::getEmuDensity()) {
707 // if "qemu.sf.lcd_density" is specified, it overrides everything
708 xdpi = ydpi = density = Density::getEmuDensity();
709 density /= 160.0f;
710 }
711 info.density = density;
712
713 // TODO: this needs to go away (currently needed only by webkit)
714 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
715 info.orientation = hw->getOrientation();
716 } else {
717 // TODO: where should this value come from?
718 static const int TV_DENSITY = 213;
719 info.density = TV_DENSITY / 160.0f;
720 info.orientation = 0;
721 }
722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 info.w = hwConfig->getWidth();
724 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700725 info.xdpi = xdpi;
726 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900728 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729
Andy McFadden91b2ca82014-06-13 14:04:23 -0700730 // This is how far in advance a buffer must be queued for
731 // presentation at a given time. If you want a buffer to appear
732 // on the screen at time N, you must submit the buffer before
733 // (N - presentationDeadline).
734 //
735 // Normally it's one full refresh period (to give SF a chance to
736 // latch the buffer), but this can be reduced by configuring a
737 // DispSync offset. Any additional delays introduced by the hardware
738 // composer or panel must be accounted for here.
739 //
740 // We add an additional 1ms to allow for processing time and
741 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 info.presentationDeadline = hwConfig->getVsyncPeriod() -
743 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700744
745 // All non-virtual displays are currently considered secure.
746 info.secure = true;
747
Michael Wright28f24d02016-07-12 13:30:53 -0700748 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749 }
750
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 return NO_ERROR;
752}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700753
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800754status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700755 DisplayStatInfo* stats) {
756 if (stats == NULL) {
757 return BAD_VALUE;
758 }
759
760 // FIXME for now we always return stats for the primary display
761 memset(stats, 0, sizeof(*stats));
762 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
763 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
764 return NO_ERROR;
765}
766
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700767int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800768 if (display == NULL) {
769 ALOGE("%s : display is NULL", __func__);
770 return BAD_VALUE;
771 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700772 sp<DisplayDevice> device(getDisplayDevice(display));
773 if (device != NULL) {
774 return device->getActiveConfig();
775 }
776 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700777}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700778
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700779void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
780 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
781 this);
782 int32_t type = hw->getDisplayType();
783 int currentMode = hw->getActiveConfig();
784
785 if (mode == currentMode) {
786 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
787 return;
788 }
789
790 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
791 ALOGW("Trying to set config for virtual display");
792 return;
793 }
794
795 hw->setActiveConfig(mode);
796 getHwComposer().setActiveConfig(type, mode);
797}
798
799status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
800 class MessageSetActiveConfig: public MessageBase {
801 SurfaceFlinger& mFlinger;
802 sp<IBinder> mDisplay;
803 int mMode;
804 public:
805 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
806 int mode) :
807 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
808 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700809 Vector<DisplayInfo> configs;
810 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700811 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700812 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700813 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700814 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700815 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700816 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
817 if (hw == NULL) {
818 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700819 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700820 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
821 ALOGW("Attempt to set active config = %d for virtual display",
822 mMode);
823 } else {
824 mFlinger.setActiveConfigInternal(hw, mMode);
825 }
826 return true;
827 }
828 };
829 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
830 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700831 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700832}
Michael Wright28f24d02016-07-12 13:30:53 -0700833status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
834 Vector<android_color_mode_t>* outColorModes) {
835 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
836 return BAD_VALUE;
837 }
838
839 if (!display.get()) {
840 return NAME_NOT_FOUND;
841 }
842
843 int32_t type = NAME_NOT_FOUND;
844 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
845 if (display == mBuiltinDisplays[i]) {
846 type = i;
847 break;
848 }
849 }
850
851 if (type < 0) {
852 return type;
853 }
854
855 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
856 outColorModes->clear();
857 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
858
859 return NO_ERROR;
860}
861
862android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
863 sp<DisplayDevice> device(getDisplayDevice(display));
864 if (device != nullptr) {
865 return device->getActiveColorMode();
866 }
867 return static_cast<android_color_mode_t>(BAD_VALUE);
868}
869
870void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
871 android_color_mode_t mode) {
872 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
873 this);
874 int32_t type = hw->getDisplayType();
875 android_color_mode_t currentMode = hw->getActiveColorMode();
876
877 if (mode == currentMode) {
878 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
879 return;
880 }
881
882 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
883 ALOGW("Trying to set config for virtual display");
884 return;
885 }
886
887 hw->setActiveColorMode(mode);
888 getHwComposer().setActiveColorMode(type, mode);
889}
890
891
892status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
893 android_color_mode_t colorMode) {
894 class MessageSetActiveColorMode: public MessageBase {
895 SurfaceFlinger& mFlinger;
896 sp<IBinder> mDisplay;
897 android_color_mode_t mMode;
898 public:
899 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
900 android_color_mode_t mode) :
901 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
902 virtual bool handler() {
903 Vector<android_color_mode_t> modes;
904 mFlinger.getDisplayColorModes(mDisplay, &modes);
905 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
906 if (mMode < 0 || !exists) {
907 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
908 mDisplay.get());
909 return true;
910 }
911 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
912 if (hw == nullptr) {
913 ALOGE("Attempt to set active color mode = %d for null display %p",
914 mMode, mDisplay.get());
915 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
916 ALOGW("Attempt to set active color mode= %d for virtual display",
917 mMode);
918 } else {
919 mFlinger.setActiveColorModeInternal(hw, mMode);
920 }
921 return true;
922 }
923 };
924 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
925 postMessageSync(msg);
926 return NO_ERROR;
927}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700928
Svetoslavd85084b2014-03-20 10:28:31 -0700929status_t SurfaceFlinger::clearAnimationFrameStats() {
930 Mutex::Autolock _l(mStateLock);
931 mAnimFrameTracker.clearStats();
932 return NO_ERROR;
933}
934
935status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
936 Mutex::Autolock _l(mStateLock);
937 mAnimFrameTracker.getStats(outStats);
938 return NO_ERROR;
939}
940
Dan Stozac4f471e2016-03-24 09:31:08 -0700941status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
942 HdrCapabilities* outCapabilities) const {
943 Mutex::Autolock _l(mStateLock);
944
945 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
946 if (displayDevice == nullptr) {
947 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
948 return BAD_VALUE;
949 }
950
951 std::unique_ptr<HdrCapabilities> capabilities =
952 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
953 if (capabilities) {
954 std::swap(*outCapabilities, *capabilities);
955 } else {
956 return BAD_VALUE;
957 }
958
959 return NO_ERROR;
960}
961
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700962status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
963 if (enable == mInjectVSyncs) {
964 return NO_ERROR;
965 }
966
967 if (enable) {
968 mInjectVSyncs = enable;
969 ALOGV("VSync Injections enabled");
970 if (mVSyncInjector.get() == nullptr) {
971 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700972 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700973 }
974 mEventQueue.setEventThread(mInjectorEventThread);
975 } else {
976 mInjectVSyncs = enable;
977 ALOGV("VSync Injections disabled");
978 mEventQueue.setEventThread(mSFEventThread);
979 mVSyncInjector.clear();
980 }
981 return NO_ERROR;
982}
983
984status_t SurfaceFlinger::injectVSync(nsecs_t when) {
985 if (!mInjectVSyncs) {
986 ALOGE("VSync Injections not enabled");
987 return BAD_VALUE;
988 }
989 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
990 ALOGV("Injecting VSync inside SurfaceFlinger");
991 mVSyncInjector->onInjectSyncEvent(when);
992 }
993 return NO_ERROR;
994}
995
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800996// ----------------------------------------------------------------------------
997
998sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800999 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001000}
1001
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001002// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001003
1004void SurfaceFlinger::waitForEvent() {
1005 mEventQueue.waitMessage();
1006}
1007
1008void SurfaceFlinger::signalTransaction() {
1009 mEventQueue.invalidate();
1010}
1011
1012void SurfaceFlinger::signalLayerUpdate() {
1013 mEventQueue.invalidate();
1014}
1015
1016void SurfaceFlinger::signalRefresh() {
1017 mEventQueue.refresh();
1018}
1019
1020status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001021 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001022 return mEventQueue.postMessage(msg, reltime);
1023}
1024
1025status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001026 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001027 status_t res = mEventQueue.postMessage(msg, reltime);
1028 if (res == NO_ERROR) {
1029 msg->wait();
1030 }
1031 return res;
1032}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001034void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001035 do {
1036 waitForEvent();
1037 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001038}
1039
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001040void SurfaceFlinger::enableHardwareVsync() {
1041 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001042 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001043 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001044 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1045 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001046 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001047 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001048}
1049
Jesse Hall948fe0c2013-10-14 12:56:09 -07001050void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001051 Mutex::Autolock _l(mHWVsyncLock);
1052
Jesse Hall948fe0c2013-10-14 12:56:09 -07001053 if (makeAvailable) {
1054 mHWVsyncAvailable = true;
1055 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001056 // Hardware vsync is not currently available, so abort the resync
1057 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001058 return;
1059 }
1060
Dan Stoza9e56aa02015-11-02 13:00:03 -08001061 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1062 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001063
1064 mPrimaryDispSync.reset();
1065 mPrimaryDispSync.setPeriod(period);
1066
1067 if (!mPrimaryHWVsyncEnabled) {
1068 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001069 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1070 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071 mPrimaryHWVsyncEnabled = true;
1072 }
1073}
1074
Jesse Hall948fe0c2013-10-14 12:56:09 -07001075void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 Mutex::Autolock _l(mHWVsyncLock);
1077 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001078 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1079 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 mPrimaryDispSync.endResync();
1081 mPrimaryHWVsyncEnabled = false;
1082 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001083 if (makeUnavailable) {
1084 mHWVsyncAvailable = false;
1085 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001086}
1087
Tim Murray4a4e4a22016-04-19 16:29:23 +00001088void SurfaceFlinger::resyncWithRateLimit() {
1089 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1090 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001091 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001092 }
1093}
1094
Steven Thomas3cfac282017-02-06 12:29:30 -08001095void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1096 nsecs_t timestamp) {
1097 Mutex::Autolock lock(mStateLock);
1098 // Ignore any vsyncs from the non-active hardware composer.
1099 if (composer != mHwc) {
1100 return;
1101 }
1102
Jamie Gennisd1700752013-10-14 12:22:52 -07001103 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001104
Jamie Gennisd1700752013-10-14 12:22:52 -07001105 { // Scope for the lock
1106 Mutex::Autolock _l(mHWVsyncLock);
1107 if (type == 0 && mPrimaryHWVsyncEnabled) {
1108 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001110 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001111
1112 if (needsHwVsync) {
1113 enableHardwareVsync();
1114 } else {
1115 disableHardwareVsync(false);
1116 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001117}
1118
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001119void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1120 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1121 *compositorTiming = mCompositorTiming;
1122}
1123
Dan Stoza9e56aa02015-11-02 13:00:03 -08001124void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1125 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1126 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1127 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001128
Dan Stoza9e56aa02015-11-02 13:00:03 -08001129 // All non-virtual displays are currently considered secure.
1130 bool isSecure = true;
1131
1132 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001133
1134 // When we're using the vr composer, the assumption is that we've
1135 // already created the IBinder object for the primary display.
1136 if (!mHwc->isUsingVrComposer()) {
1137 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1138 }
1139
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140 wp<IBinder> token = mBuiltinDisplays[type];
1141
1142 sp<IGraphicBufferProducer> producer;
1143 sp<IGraphicBufferConsumer> consumer;
1144 BufferQueue::createBufferQueue(&producer, &consumer,
1145 new GraphicBufferAlloc());
1146
1147 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1148 DisplayDevice::DISPLAY_PRIMARY, consumer);
1149 sp<DisplayDevice> hw = new DisplayDevice(this,
1150 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1151 producer, mRenderEngine->getEGLConfig());
1152 mDisplays.add(token, hw);
1153 } else {
1154 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001155 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001156 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001157 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001158 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001159 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1160 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001161 }
1162 setTransactionFlags(eDisplayTransactionNeeded);
1163
Andy McFadden9e9689c2012-10-10 18:17:51 -07001164 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001165 }
Mathias Agopian86303202012-07-24 22:46:10 -07001166}
1167
Steven Thomas3cfac282017-02-06 12:29:30 -08001168void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1169 Mutex::Autolock lock(mStateLock);
1170 if (composer == mHwc) {
1171 repaintEverything();
1172 } else {
1173 // This isn't from our current hardware composer. If it's a callback
1174 // from the real composer, forward the refresh request to vr
1175 // flinger. Otherwise ignore it.
1176 if (!composer->isUsingVrComposer()) {
1177 mVrFlinger->OnHardwareComposerRefresh();
1178 }
1179 }
1180}
1181
Dan Stoza9e56aa02015-11-02 13:00:03 -08001182void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184 getHwComposer().setVsyncEnabled(disp,
1185 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001186}
1187
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001188void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1189 for (size_t i = 0; i < layers.size(); ++i) {
1190 layers[i]->clearHwcLayers();
1191 }
1192}
1193
1194void SurfaceFlinger::resetHwc() {
1195 disableHardwareVsync(true);
1196 clearHwcLayers(mDrawingState.layersSortedByZ);
1197 clearHwcLayers(mCurrentState.layersSortedByZ);
1198 // Clear the drawing state so that the logic inside of
1199 // handleTransactionLocked will fire. It will determine the delta between
1200 // mCurrentState and mDrawingState and re-apply all changes when we make the
1201 // transition.
1202 mDrawingState.displays.clear();
1203 mDisplays.clear();
1204}
1205
1206void SurfaceFlinger::updateVrMode() {
1207 {
1208 Mutex::Autolock _l(mStateLock);
1209 bool enteringVrMode = mEnterVrMode;
1210 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1211 return;
1212 }
1213
1214 if (enteringVrMode) {
1215 // Start vrflinger thread, if it hasn't been started already.
1216 if (!mVrFlinger) {
1217 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1218 int err = mVrFlinger->Run(mHwc->getComposer());
1219 if (err != NO_ERROR) {
1220 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1221 mVrFlinger.reset();
1222 mEnterVrMode = false;
1223 return;
1224 }
1225 }
1226
1227 if (!mVrHwc) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001228 mVrHwc = new HWComposer(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001229 ALOGV("Vr HWC created");
1230 }
1231
1232 resetHwc();
1233
1234 mHwc = mVrHwc;
1235 mVrFlinger->EnterVrMode();
1236 } else {
1237 mVrFlinger->ExitVrMode();
1238
1239 resetHwc();
1240
1241 mHwc = mRealHwc;
1242 enableHardwareVsync();
1243 }
1244
1245 mVisibleRegionsDirty = true;
1246 invalidateHwcGeometry();
1247 android_atomic_or(1, &mRepaintEverything);
1248 setTransactionFlags(eDisplayTransactionNeeded);
1249 }
1250 if (mVrHwc) {
1251 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1252 }
1253}
1254
Mathias Agopian4fec8732012-06-29 14:12:52 -07001255void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001256 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001258 case MessageQueue::INVALIDATE: {
Corey Tabakace2c1982017-02-15 17:07:20 -08001259 // TODO(eieio): Disabled until SELinux issues are resolved.
1260 //updateVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001261
Dan Stoza50182882016-07-08 12:02:20 -07001262 bool frameMissed = !mHadClientComposition &&
1263 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001264 (mPreviousPresentFence->getSignalTime() ==
1265 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001266 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001267 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001268 signalLayerUpdate();
1269 break;
1270 }
1271
Dan Stoza6b9454d2014-11-07 16:00:59 -08001272 bool refreshNeeded = handleMessageTransaction();
1273 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001274 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001275 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001276 // Signal a refresh if a transaction modified the window state,
1277 // a new buffer was latched, or if HWC has requested a full
1278 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001279 signalRefresh();
1280 }
1281 break;
1282 }
1283 case MessageQueue::REFRESH: {
1284 handleMessageRefresh();
1285 break;
1286 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287 }
1288}
1289
Dan Stoza6b9454d2014-11-07 16:00:59 -08001290bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001291 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001292 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001293 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001294 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001295 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001296 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001297}
1298
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001300 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001301 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001302}
1303
1304void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001305 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001306
Pablo Ceballos40845df2016-01-25 17:41:15 -08001307 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001308
Brian Andersond6927fb2016-07-23 23:37:30 -07001309 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001310 rebuildLayerStacks();
1311 setUpHWComposer();
1312 doDebugFlashRegions();
1313 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001314 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001315
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001316 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001317
1318 mHadClientComposition = false;
1319 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1320 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1321 mHadClientComposition = mHadClientComposition ||
1322 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1323 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001324
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001326}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001327
Mathias Agopiancd60f992012-08-16 16:28:27 -07001328void SurfaceFlinger::doDebugFlashRegions()
1329{
1330 // is debugging enabled
1331 if (CC_LIKELY(!mDebugRegion))
1332 return;
1333
1334 const bool repaintEverything = mRepaintEverything;
1335 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1336 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001337 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338 // transform the dirty region into this screen's coordinate space
1339 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1340 if (!dirtyRegion.isEmpty()) {
1341 // redraw the whole screen
1342 doComposeSurfaces(hw, Region(hw->bounds()));
1343
1344 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001345 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001346 RenderEngine& engine(getRenderEngine());
1347 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1348
Mathias Agopianda27af92012-09-13 18:17:13 -07001349 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001350 }
1351 }
1352 }
1353
1354 postFramebuffer();
1355
1356 if (mDebugRegion > 1) {
1357 usleep(mDebugRegion * 1000);
1358 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001359
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001361 auto& displayDevice = mDisplays[displayId];
1362 if (!displayDevice->isDisplayOn()) {
1363 continue;
1364 }
1365
1366 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1368 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001369 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001370}
1371
Brian Andersond6927fb2016-07-23 23:37:30 -07001372void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 ATRACE_CALL();
1375 ALOGV("preComposition");
1376
Mathias Agopiancd60f992012-08-16 16:28:27 -07001377 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001378 mDrawingState.traverseInZOrder([&](Layer* layer) {
1379 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380 needExtraInvalidate = true;
1381 }
Robert Carr2047fae2016-11-28 14:09:09 -08001382 });
1383
Mathias Agopiancd60f992012-08-16 16:28:27 -07001384 if (needExtraInvalidate) {
1385 signalLayerUpdate();
1386 }
1387}
1388
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389void SurfaceFlinger::updateCompositorTiming(
1390 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1391 std::shared_ptr<FenceTime>& presentFenceTime) {
1392 // Update queue of past composite+present times and determine the
1393 // most recently known composite to present latency.
1394 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1395 nsecs_t compositeToPresentLatency = -1;
1396 while (!mCompositePresentTimes.empty()) {
1397 CompositePresentTime& cpt = mCompositePresentTimes.front();
1398 // Cached values should have been updated before calling this method,
1399 // which helps avoid duplicate syscalls.
1400 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1401 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1402 break;
1403 }
1404 compositeToPresentLatency = displayTime - cpt.composite;
1405 mCompositePresentTimes.pop();
1406 }
1407
1408 // Don't let mCompositePresentTimes grow unbounded, just in case.
1409 while (mCompositePresentTimes.size() > 16) {
1410 mCompositePresentTimes.pop();
1411 }
1412
1413 // Integer division and modulo round toward 0 not -inf, so we need to
1414 // treat negative and positive offsets differently.
1415 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1416 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1417 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1418
1419 // Snap the latency to a value that removes scheduling jitter from the
1420 // composition and present times, which often have >1ms of jitter.
1421 // Reducing jitter is important if an app attempts to extrapolate
1422 // something (such as user input) to an accurate diasplay time.
1423 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1424 // with (presentLatency % interval).
1425 nsecs_t snappedCompositeToPresentLatency = -1;
1426 if (compositeToPresentLatency >= 0) {
1427 nsecs_t bias = vsyncInterval / 2;
1428 int64_t extraVsyncs =
1429 (compositeToPresentLatency - idealLatency + bias) /
1430 vsyncInterval;
1431 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1432 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1433 }
1434
1435 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1436 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1437 mCompositorTiming.interval = vsyncInterval;
1438 if (snappedCompositeToPresentLatency >= 0) {
1439 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1440 }
1441}
1442
1443void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001445 ATRACE_CALL();
1446 ALOGV("postComposition");
1447
Brian Anderson3546a3f2016-07-14 11:51:14 -07001448 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001449 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001450 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001451 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001452 }
1453
Brian Andersond6927fb2016-07-23 23:37:30 -07001454 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001455
1456 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1457 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1458 glCompositionDoneFenceTime =
1459 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1460 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1461 } else {
1462 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1463 }
1464 mGlCompositionDoneTimeline.updateSignalTimes();
1465
1466 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1467 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1468 mDisplayTimeline.push(displayFenceTime);
1469 mDisplayTimeline.updateSignalTimes();
1470
1471 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1472 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1473 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1474 presentFenceTime = &displayFenceTime;
1475 } else {
1476 retireFenceTime = &displayFenceTime;
1477 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478
1479 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1480 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1481
1482 // We use the refreshStartTime which might be sampled a little later than
1483 // when we started doing work for this frame, but that should be okay
1484 // since updateCompositorTiming has snapping logic.
1485 updateCompositorTiming(
1486 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1487
Robert Carr2047fae2016-11-28 14:09:09 -08001488 mDrawingState.traverseInZOrder([&](Layer* layer) {
1489 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001490 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001491 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001492 recordBufferingStats(layer->getName().string(),
1493 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001494 }
Robert Carr2047fae2016-11-28 14:09:09 -08001495 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001496
Brian Anderson3d4039d2016-09-23 16:31:30 -07001497 if (displayFence->isValid()) {
1498 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001499 enableHardwareVsync();
1500 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001501 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001502 }
1503 }
1504
Andy McFadden5167ec62014-05-22 13:08:43 -07001505 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001506 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001507 enableHardwareVsync();
1508 }
1509 }
1510
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001511 if (mAnimCompositionPending) {
1512 mAnimCompositionPending = false;
1513
Brian Anderson3d4039d2016-09-23 16:31:30 -07001514 if (displayFenceTime->isValid()) {
1515 mAnimFrameTracker.setActualPresentFence(
1516 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001517 } else {
1518 // The HWC doesn't support present fences, so use the refresh
1519 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 nsecs_t presentTime =
1521 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001522 mAnimFrameTracker.setActualPresentTime(presentTime);
1523 }
1524 mAnimFrameTracker.advanceFrame();
1525 }
Dan Stozab90cf072015-03-05 11:05:59 -08001526
1527 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1528 return;
1529 }
1530
1531 nsecs_t currentTime = systemTime();
1532 if (mHasPoweredOff) {
1533 mHasPoweredOff = false;
1534 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001535 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001537 if (numPeriods < NUM_BUCKETS - 1) {
1538 mFrameBuckets[numPeriods] += elapsedTime;
1539 } else {
1540 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1541 }
1542 mTotalTime += elapsedTime;
1543 }
1544 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545}
1546
1547void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001548 ATRACE_CALL();
1549 ALOGV("rebuildLayerStacks");
1550
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001552 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001554 mVisibleRegionsDirty = false;
1555 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001556
Mathias Agopian92a979a2012-08-02 18:32:23 -07001557 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001558 Region opaqueRegion;
1559 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 Vector<sp<Layer>> layersSortedByZ;
1561 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1562 const Transform& tr(displayDevice->getTransform());
1563 const Rect bounds(displayDevice->getBounds());
1564 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001565 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 displayDevice->getLayerStack(), dirtyRegion,
1567 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001568
Robert Carr2047fae2016-11-28 14:09:09 -08001569 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001570 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001571 Region drawRegion(tr.transform(
1572 layer->visibleNonTransparentRegion));
1573 drawRegion.andSelf(bounds);
1574 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001575 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001576 } else {
1577 // Clear out the HWC layer if this layer was
1578 // previously visible, but no longer is
1579 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1580 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001581 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001582 }
Robert Carr2047fae2016-11-28 14:09:09 -08001583 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001584 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001585 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1586 displayDevice->undefinedRegion.set(bounds);
1587 displayDevice->undefinedRegion.subtractSelf(
1588 tr.transform(opaqueRegion));
1589 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001590 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001591 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001593
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 ATRACE_CALL();
1596 ALOGV("setUpHWComposer");
1597
Jesse Hall028dc8f2013-08-20 16:35:32 -07001598 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001599 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1600 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1601 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1602
1603 // If nothing has changed (!dirty), don't recompose.
1604 // If something changed, but we don't currently have any visible layers,
1605 // and didn't when we last did a composition, then skip it this time.
1606 // The second rule does two things:
1607 // - When all layers are removed from a display, we'll emit one black
1608 // frame, then nothing more until we get new layers.
1609 // - When a display is created with a private layer stack, we won't
1610 // emit any black frames until a layer is added to the layer stack.
1611 bool mustRecompose = dirty && !(empty && wasEmpty);
1612
1613 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1614 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1615 mustRecompose ? "doing" : "skipping",
1616 dirty ? "+" : "-",
1617 empty ? "+" : "-",
1618 wasEmpty ? "+" : "-");
1619
Dan Stoza71433162014-02-04 16:22:36 -08001620 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001621
1622 if (mustRecompose) {
1623 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1624 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001625 }
1626
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 // build the h/w work list
1628 if (CC_UNLIKELY(mGeometryInvalid)) {
1629 mGeometryInvalid = false;
1630 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1631 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1632 const auto hwcId = displayDevice->getHwcDisplayId();
1633 if (hwcId >= 0) {
1634 const Vector<sp<Layer>>& currentLayers(
1635 displayDevice->getVisibleLayersSortedByZ());
1636 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001637 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001638 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001639 if (!layer->hasHwcLayer(hwcId)) {
1640 auto hwcLayer = mHwc->createLayer(hwcId);
1641 if (hwcLayer) {
1642 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1643 } else {
1644 layer->forceClientComposition(hwcId);
1645 foundLayerWithoutHwc = true;
1646 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001647 }
1648 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001649
Robert Carrae060832016-11-28 10:51:00 -08001650 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001651 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001652 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001653 }
1654 }
1655 }
1656 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 }
Riley Andrews03414a12014-07-01 14:22:59 -07001658
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001659
1660 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1661
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 // Set the per-frame data
1663 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1664 auto& displayDevice = mDisplays[displayId];
1665 const auto hwcId = displayDevice->getHwcDisplayId();
1666 if (hwcId < 0) {
1667 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001668 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001669 if (colorMatrix != mPreviousColorMatrix) {
1670 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1671 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1672 "display %zd: %d", displayId, result);
1673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1675 layer->setPerFrameData(displayDevice);
1676 }
1677 }
1678
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001679 mPreviousColorMatrix = colorMatrix;
1680
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001682 auto& displayDevice = mDisplays[displayId];
1683 if (!displayDevice->isDisplayOn()) {
1684 continue;
1685 }
1686
1687 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001688 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1689 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001690 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001692
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693void SurfaceFlinger::doComposition() {
1694 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 ALOGV("doComposition");
1696
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001697 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001698 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001699 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001700 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701 // transform the dirty region into this screen's coordinate space
1702 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001703
1704 // repaint the framebuffer (if needed)
1705 doDisplayComposition(hw, dirtyRegion);
1706
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707 hw->dirtyRegion.clear();
1708 hw->flip(hw->swapRegion);
1709 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001710 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001712 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713}
1714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001715void SurfaceFlinger::postFramebuffer()
1716{
Mathias Agopian841cde52012-03-01 15:44:37 -08001717 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001719
Mathias Agopiana44b0412011-10-16 18:46:35 -07001720 const nsecs_t now = systemTime();
1721 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001722
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1724 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001725 if (!displayDevice->isDisplayOn()) {
1726 continue;
1727 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 const auto hwcId = displayDevice->getHwcDisplayId();
1729 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001730 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001731 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001732 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001733 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001734 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1735 sp<Fence> releaseFence = Fence::NO_FENCE;
1736 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1737 releaseFence = displayDevice->getClientTargetAcquireFence();
1738 } else {
1739 auto hwcLayer = layer->getHwcLayer(hwcId);
1740 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001741 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 layer->onLayerDisplayed(releaseFence);
1743 }
1744 if (hwcId >= 0) {
1745 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001746 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001747 }
1748
Mathias Agopiana44b0412011-10-16 18:46:35 -07001749 mLastSwapBufferTime = systemTime() - now;
1750 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001751
1752 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1753 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1754 logFrameStats();
1755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001756}
1757
Mathias Agopian87baae12012-07-31 12:38:26 -07001758void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001759{
Mathias Agopian841cde52012-03-01 15:44:37 -08001760 ATRACE_CALL();
1761
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001762 // here we keep a copy of the drawing state (that is the state that's
1763 // going to be overwritten by handleTransactionLocked()) outside of
1764 // mStateLock so that the side-effects of the State assignment
1765 // don't happen with mStateLock held (which can cause deadlocks).
1766 State drawingState(mDrawingState);
1767
Mathias Agopianca4d3602011-05-19 15:38:14 -07001768 Mutex::Autolock _l(mStateLock);
1769 const nsecs_t now = systemTime();
1770 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001771
Mathias Agopianca4d3602011-05-19 15:38:14 -07001772 // Here we're guaranteed that some transaction flags are set
1773 // so we can call handleTransactionLocked() unconditionally.
1774 // We call getTransactionFlags(), which will also clear the flags,
1775 // with mStateLock held to guarantee that mCurrentState won't change
1776 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001777
Mathias Agopiane57f2922012-08-09 16:29:12 -07001778 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001779 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001780
Mathias Agopianca4d3602011-05-19 15:38:14 -07001781 mLastTransactionTime = systemTime() - now;
1782 mDebugInTransaction = 0;
1783 invalidateHwcGeometry();
1784 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001785}
1786
Mathias Agopian87baae12012-07-31 12:38:26 -07001787void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001788{
Dan Stoza7dde5992015-05-22 09:51:44 -07001789 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001790 mCurrentState.traverseInZOrder([](Layer* layer) {
1791 layer->notifyAvailableFrames();
1792 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001794 /*
1795 * Traversal of the children
1796 * (perform the transaction for each of them if needed)
1797 */
1798
Mathias Agopian3559b072012-08-15 13:46:03 -07001799 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001800 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001802 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001803
1804 const uint32_t flags = layer->doTransaction(0);
1805 if (flags & Layer::eVisibleRegion)
1806 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001807 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001808 }
1809
1810 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001811 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812 */
1813
Mathias Agopiane57f2922012-08-09 16:29:12 -07001814 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001815 // here we take advantage of Vector's copy-on-write semantics to
1816 // improve performance by skipping the transaction entirely when
1817 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001818 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1819 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001820 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001822 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001823 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001824
1825 // find the displays that were removed
1826 // (ie: in drawing state but not in current state)
1827 // also handle displays that changed
1828 // (ie: displays that are in both lists)
1829 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001830 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1831 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001833 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001834 // Call makeCurrent() on the primary display so we can
1835 // be sure that nothing associated with this display
1836 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001837 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001838 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001839 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1840 if (hw != NULL)
1841 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001842 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001843 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001844 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001845 } else {
1846 ALOGW("trying to remove the main display");
1847 }
1848 } else {
1849 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001850 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001851 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001852 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1853 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001854 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001855 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001856 // recreating the DisplayDevice, so we just remove it
1857 // from the drawing state, so that it get re-added
1858 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001859 sp<DisplayDevice> hw(getDisplayDevice(display));
1860 if (hw != NULL)
1861 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001862 mDisplays.removeItem(display);
1863 mDrawingState.displays.removeItemsAt(i);
1864 dc--; i--;
1865 // at this point we must loop to the next item
1866 continue;
1867 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001868
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001869 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001870 if (disp != NULL) {
1871 if (state.layerStack != draw[i].layerStack) {
1872 disp->setLayerStack(state.layerStack);
1873 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001874 if ((state.orientation != draw[i].orientation)
1875 || (state.viewport != draw[i].viewport)
1876 || (state.frame != draw[i].frame))
1877 {
1878 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001879 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001880 }
Michael Lentine47e45402014-07-18 15:34:25 -07001881 if (state.width != draw[i].width || state.height != draw[i].height) {
1882 disp->setDisplaySize(state.width, state.height);
1883 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001884 }
1885 }
1886 }
1887
1888 // find displays that were added
1889 // (ie: in current state but not in drawing state)
1890 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001891 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001892 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001893
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001894 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001895 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001896 sp<IGraphicBufferProducer> bqProducer;
1897 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001898 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1899 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001902 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001903 // Virtual displays without a surface are dormant:
1904 // they have external state (layer stack, projection,
1905 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001906 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001907
Dan Stoza8cf150a2016-08-02 10:27:31 -07001908 if (mUseHwcVirtualDisplays) {
1909 int width = 0;
1910 int status = state.surface->query(
1911 NATIVE_WINDOW_WIDTH, &width);
1912 ALOGE_IF(status != NO_ERROR,
1913 "Unable to query width (%d)", status);
1914 int height = 0;
1915 status = state.surface->query(
1916 NATIVE_WINDOW_HEIGHT, &height);
1917 ALOGE_IF(status != NO_ERROR,
1918 "Unable to query height (%d)", status);
1919 int intFormat = 0;
1920 status = state.surface->query(
1921 NATIVE_WINDOW_FORMAT, &intFormat);
1922 ALOGE_IF(status != NO_ERROR,
1923 "Unable to query format (%d)", status);
1924 auto format = static_cast<android_pixel_format_t>(
1925 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001926
Dan Stoza8cf150a2016-08-02 10:27:31 -07001927 mHwc->allocateVirtualDisplay(width, height, &format,
1928 &hwcId);
1929 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930
Dan Stoza5cf424b2016-05-20 14:02:39 -07001931 // TODO: Plumb requested format back up to consumer
1932
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 sp<VirtualDisplaySurface> vds =
1934 new VirtualDisplaySurface(*mHwc,
1935 hwcId, state.surface, bqProducer,
1936 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001937
1938 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001939 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001940 }
1941 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001942 ALOGE_IF(state.surface!=NULL,
1943 "adding a supported display, but rendering "
1944 "surface is provided (%p), ignoring it",
1945 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001946
1947 hwcId = state.type;
1948 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1949 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001950 }
1951
1952 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001953 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001954 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 state.type, hwcId, state.isSecure, display,
1956 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001957 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001958 hw->setLayerStack(state.layerStack);
1959 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001960 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001961 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001962 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001964 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001965 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001966 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001967 }
1968 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001970 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971
Mathias Agopian84300952012-11-21 16:02:13 -08001972 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1973 // The transform hint might have changed for some layers
1974 // (either because a display has changed, or because a layer
1975 // as changed).
1976 //
1977 // Walk through all the layers in currentLayers,
1978 // and update their transform hint.
1979 //
1980 // If a layer is visible only on a single display, then that
1981 // display is used to calculate the hint, otherwise we use the
1982 // default display.
1983 //
1984 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1985 // the hint is set before we acquire a buffer from the surface texture.
1986 //
1987 // NOTE: layer transactions have taken place already, so we use their
1988 // drawing state. However, SurfaceFlinger's own transaction has not
1989 // happened yet, so we must use the current state layer list
1990 // (soon to become the drawing state list).
1991 //
1992 sp<const DisplayDevice> disp;
1993 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001994 bool first = true;
1995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001996 // NOTE: we rely on the fact that layers are sorted by
1997 // layerStack first (so we don't have to traverse the list
1998 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001999 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002000 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002001 currentlayerStack = layerStack;
2002 // figure out if this layerstack is mirrored
2003 // (more than one display) if so, pick the default display,
2004 // if not, pick the only display it's on.
2005 disp.clear();
2006 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2007 sp<const DisplayDevice> hw(mDisplays[dpy]);
2008 if (hw->getLayerStack() == currentlayerStack) {
2009 if (disp == NULL) {
2010 disp = hw;
2011 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002012 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002013 break;
2014 }
2015 }
2016 }
2017 }
Chet Haase91d25932013-04-11 15:24:55 -07002018 if (disp == NULL) {
2019 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2020 // redraw after transform hint changes. See bug 8508397.
2021
2022 // could be null when this layer is using a layerStack
2023 // that is not visible on any display. Also can occur at
2024 // screen off/on times.
2025 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002026 }
Chet Haase91d25932013-04-11 15:24:55 -07002027 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002028
2029 first = false;
2030 });
Mathias Agopian84300952012-11-21 16:02:13 -08002031 }
2032
2033
Mathias Agopian3559b072012-08-15 13:46:03 -07002034 /*
2035 * Perform our own transaction if needed
2036 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002037
2038 if (mLayersAdded) {
2039 mLayersAdded = false;
2040 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002041 mVisibleRegionsDirty = true;
2042 }
2043
2044 // some layers might have been removed, so
2045 // we need to update the regions they're exposing.
2046 if (mLayersRemoved) {
2047 mLayersRemoved = false;
2048 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002049 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002050 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002051 // this layer is not visible anymore
2052 // TODO: we could traverse the tree from front to back and
2053 // compute the actual visible region
2054 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002055 Region visibleReg;
2056 visibleReg.set(layer->computeScreenBounds());
2057 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002058 }
Robert Carr2047fae2016-11-28 14:09:09 -08002059 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060 }
2061
2062 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002063
2064 updateCursorAsync();
2065}
2066
2067void SurfaceFlinger::updateCursorAsync()
2068{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2070 auto& displayDevice = mDisplays[displayId];
2071 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002072 continue;
2073 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074
2075 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2076 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002077 }
2078 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002079}
2080
2081void SurfaceFlinger::commitTransaction()
2082{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002083 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002085 for (const auto& l : mLayersPendingRemoval) {
2086 recordBufferingStats(l->getName().string(),
2087 l->getOccupancyHistory(true));
2088 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002089 }
2090 mLayersPendingRemoval.clear();
2091 }
2092
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002093 // If this transaction is part of a window animation then the next frame
2094 // we composite should be considered an animation as well.
2095 mAnimCompositionPending = mAnimTransactionPending;
2096
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002098 mDrawingState.traverseInZOrder([](Layer* layer) {
2099 layer->commitChildList();
2100 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002101 mTransactionPending = false;
2102 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002103 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104}
2105
Robert Carr2047fae2016-11-28 14:09:09 -08002106void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002107 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002108{
Mathias Agopian841cde52012-03-01 15:44:37 -08002109 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112 Region aboveOpaqueLayers;
2113 Region aboveCoveredLayers;
2114 Region dirty;
2115
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117
Robert Carr2047fae2016-11-28 14:09:09 -08002118 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002120 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121
Jesse Hall01e29052013-02-19 16:13:35 -08002122 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002123 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002124 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002125
Mathias Agopianab028732010-03-16 16:41:46 -07002126 /*
2127 * opaqueRegion: area of a surface that is fully opaque.
2128 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002130
2131 /*
2132 * visibleRegion: area of a surface that is visible on screen
2133 * and not fully transparent. This is essentially the layer's
2134 * footprint minus the opaque regions above it.
2135 * Areas covered by a translucent surface are considered visible.
2136 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002138
2139 /*
2140 * coveredRegion: area of a surface that is covered by all
2141 * visible regions above it (which includes the translucent areas).
2142 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002144
Jesse Halla8026d22012-09-25 13:25:04 -07002145 /*
2146 * transparentRegion: area of a surface that is hinted to be completely
2147 * transparent. This is only used to tell when the layer has no visible
2148 * non-transparent regions and can be removed from the layer list. It
2149 * does not affect the visibleRegion of this layer or any layers
2150 * beneath it. The hint may not be correct if apps don't respect the
2151 * SurfaceView restrictions (which, sadly, some don't).
2152 */
2153 Region transparentRegion;
2154
Mathias Agopianab028732010-03-16 16:41:46 -07002155
2156 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002157 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002158 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002159 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002161 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002162 if (!visibleRegion.isEmpty()) {
2163 // Remove the transparent area from the visible region
2164 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002165 if (tr.preserveRects()) {
2166 // transform the transparent region
2167 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002168 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002169 // transformation too complex, can't do the
2170 // transparent region optimization.
2171 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002172 }
Mathias Agopianab028732010-03-16 16:41:46 -07002173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174
Mathias Agopianab028732010-03-16 16:41:46 -07002175 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002178 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2179 // the opaque region is the layer's footprint
2180 opaqueRegion = visibleRegion;
2181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002182 }
2183 }
2184
Mathias Agopianab028732010-03-16 16:41:46 -07002185 // Clip the covered region to the visible region
2186 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2187
2188 // Update aboveCoveredLayers for next (lower) layer
2189 aboveCoveredLayers.orSelf(visibleRegion);
2190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191 // subtract the opaque region covered by the layers above us
2192 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193
2194 // compute this layer's dirty region
2195 if (layer->contentDirty) {
2196 // we need to invalidate the whole region
2197 dirty = visibleRegion;
2198 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002199 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 layer->contentDirty = false;
2201 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002202 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002203 * the exposed region consists of two components:
2204 * 1) what's VISIBLE now and was COVERED before
2205 * 2) what's EXPOSED now less what was EXPOSED before
2206 *
2207 * note that (1) is conservative, we start with the whole
2208 * visible region but only keep what used to be covered by
2209 * something -- which mean it may have been exposed.
2210 *
2211 * (2) handles areas that were not covered by anything but got
2212 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002213 */
Mathias Agopianab028732010-03-16 16:41:46 -07002214 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002215 const Region oldVisibleRegion = layer->visibleRegion;
2216 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002217 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2218 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219 }
2220 dirty.subtractSelf(aboveOpaqueLayers);
2221
2222 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002223 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224
Mathias Agopianab028732010-03-16 16:41:46 -07002225 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002227
Jesse Halla8026d22012-09-25 13:25:04 -07002228 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229 layer->setVisibleRegion(visibleRegion);
2230 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002231 layer->setVisibleNonTransparentRegion(
2232 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002233 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopian87baae12012-07-31 12:38:26 -07002235 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236}
2237
Mathias Agopian87baae12012-07-31 12:38:26 -07002238void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2239 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002240 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002241 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2242 if (hw->getLayerStack() == layerStack) {
2243 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002244 }
2245 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002246}
2247
Dan Stoza6b9454d2014-11-07 16:00:59 -08002248bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002249{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002250 ALOGV("handlePageFlip");
2251
Brian Andersond6927fb2016-07-23 23:37:30 -07002252 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253
Mathias Agopian4fec8732012-06-29 14:12:52 -07002254 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002255 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002256
2257 // Store the set of layers that need updates. This set must not change as
2258 // buffers are being latched, as this could result in a deadlock.
2259 // Example: Two producers share the same command stream and:
2260 // 1.) Layer 0 is latched
2261 // 2.) Layer 0 gets a new frame
2262 // 2.) Layer 1 gets a new frame
2263 // 3.) Layer 1 is latched.
2264 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2265 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002266 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002267 if (layer->hasQueuedFrame()) {
2268 frameQueued = true;
2269 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002270 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002271 } else {
2272 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002273 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002274 } else {
2275 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002276 }
Robert Carr2047fae2016-11-28 14:09:09 -08002277 });
2278
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002280 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002281 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002283 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002284
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002285 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286
2287 // If we will need to wake up at some time in the future to deal with a
2288 // queued frame that shouldn't be displayed during this vsync period, wake
2289 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002291 signalLayerUpdate();
2292 }
2293
2294 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002295 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Mathias Agopianad456f92011-01-13 17:53:01 -08002298void SurfaceFlinger::invalidateHwcGeometry()
2299{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002300 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002301}
2302
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002303
Fabien Sanglard830b8472016-11-30 16:35:58 -08002304void SurfaceFlinger::doDisplayComposition(
2305 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002306 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307{
Dan Stoza71433162014-02-04 16:22:36 -08002308 // We only need to actually compose the display if:
2309 // 1) It is being handled by hardware composer, which may need this to
2310 // keep its virtual display state machine in sync, or
2311 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002312 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002313 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002315 return;
2316 }
2317
Dan Stoza9e56aa02015-11-02 13:00:03 -08002318 ALOGV("doDisplayComposition");
2319
Mathias Agopian87baae12012-07-31 12:38:26 -07002320 Region dirtyRegion(inDirtyRegion);
2321
Mathias Agopianb8a55602009-06-26 19:06:36 -07002322 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002323 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324
Fabien Sanglard830b8472016-11-30 16:35:58 -08002325 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002326 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002327 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2328 // takes a rectangle, we must make sure to update that whole
2329 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002330 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002331 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002332 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002333 // We need to redraw the rectangle that will be updated
2334 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002335 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002336 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002337 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002338 } else {
2339 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 dirtyRegion.set(displayDevice->bounds());
2341 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 }
2343 }
2344
Fabien Sanglard830b8472016-11-30 16:35:58 -08002345 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002347 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002348 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002349
2350 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002351 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352}
2353
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354bool SurfaceFlinger::doComposeSurfaces(
2355 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002356{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002358
Dan Stoza9e56aa02015-11-02 13:00:03 -08002359 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002360
2361 mat4 oldColorMatrix;
2362 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2363 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2364 if (applyColorMatrix) {
2365 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2366 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2367 }
2368
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2370 if (hasClientComposition) {
2371 ALOGV("hasClientComposition");
2372
2373 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002374 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002376 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2377 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2378 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2379 }
2380 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002381 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002382
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002383 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002384 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2385 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002386 // when using overlays, we assume a fully transparent framebuffer
2387 // NOTE: we could reduce how much we need to clear, for instance
2388 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002389 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002390 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002392 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002393 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002395
2396 // we remove the scissor part
2397 // we're left with the letterbox region
2398 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002399 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002400
2401 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002402 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002403
2404 // but limit it to the dirty region
2405 region.andSelf(dirty);
2406
Mathias Agopianb9494d52012-04-18 02:28:45 -07002407 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002408 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002409 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002411 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002412 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002413
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002415 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002416 // scissor on the main display. It should never be needed
2417 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 const Rect& bounds(displayDevice->getBounds());
2419 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002420 if (scissor != bounds) {
2421 // scissor doesn't match the screen's dimensions, so we
2422 // need to clear everything outside of it and enable
2423 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002424
Mathias Agopianf45c5102012-10-24 16:29:17 -07002425 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 const uint32_t height = displayDevice->getHeight();
2427 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002428 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002429 }
2430 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002431 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002432
Mathias Agopian85d751c2012-08-29 16:59:24 -07002433 /*
2434 * and then, render the layers targeted at the framebuffer
2435 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002436
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("Rendering client layers");
2438 const Transform& displayTransform = displayDevice->getTransform();
2439 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002440 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 bool firstLayer = true;
2442 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2443 const Region clip(dirty.intersect(
2444 displayTransform.transform(layer->visibleRegion)));
2445 ALOGV("Layer: %s", layer->getName().string());
2446 ALOGV(" Composition type: %s",
2447 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002448 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002449 switch (layer->getCompositionType(hwcId)) {
2450 case HWC2::Composition::Cursor:
2451 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002452 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002454 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2456 layer->isOpaque(state) && (state.alpha == 1.0f)
2457 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002458 // never clear the very first layer since we're
2459 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002460 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002461 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002462 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002463 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 case HWC2::Composition::Client: {
2465 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002466 break;
2467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002469 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 } else {
2472 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 }
2476 } else {
2477 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002479 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002481 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002483 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002484 }
2485 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002486
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002487 if (applyColorMatrix) {
2488 getRenderEngine().setupColorTransform(oldColorMatrix);
2489 }
2490
Mathias Agopianf45c5102012-10-24 16:29:17 -07002491 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002493 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494}
2495
Fabien Sanglard830b8472016-11-30 16:35:58 -08002496void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2497 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002498 RenderEngine& engine(getRenderEngine());
2499 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500}
2501
Dan Stoza7d89d062015-04-30 13:29:25 -07002502status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002503 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002504 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002505 const sp<Layer>& lbc,
2506 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002507{
Dan Stoza7d89d062015-04-30 13:29:25 -07002508 // add this layer to the current state list
2509 {
2510 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002512 return NO_MEMORY;
2513 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 if (parent == nullptr) {
2515 mCurrentState.layersSortedByZ.add(lbc);
2516 } else {
2517 parent->addChild(lbc);
2518 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002519 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 mLayersAdded = true;
2521 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002522 }
2523
Mathias Agopian96f08192010-06-02 23:28:45 -07002524 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002525 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002526
Dan Stoza7d89d062015-04-30 13:29:25 -07002527 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002528}
2529
Dan Stoza22851c32016-08-09 13:21:03 -07002530status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002532 sp<Layer> layer = weakLayer.promote();
2533 if (layer == nullptr) {
2534 // The layer has already been removed, carry on
2535 return NO_ERROR;
2536 }
2537
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 const auto& p = layer->getParent();
2539 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2540 mCurrentState.layersSortedByZ.remove(layer);
2541
2542 if (index < 0) {
2543 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2544 layer->getName().string(),
2545 (p != nullptr) ? p->getName().string() : "no-parent");
2546 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002547 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548
2549 mLayersPendingRemoval.add(layer);
2550 mLayersRemoved = true;
2551 mNumLayers--;
2552 setTransactionFlags(eTransactionNeeded);
2553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554}
2555
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002556uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002557 return android_atomic_release_load(&mTransactionFlags);
2558}
2559
Mathias Agopian3f844832013-08-07 21:24:32 -07002560uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2562}
2563
Mathias Agopian3f844832013-08-07 21:24:32 -07002564uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2566 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002567 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 }
2569 return old;
2570}
2571
Mathias Agopian8b33f032012-07-24 20:43:54 -07002572void SurfaceFlinger::setTransactionState(
2573 const Vector<ComposerState>& state,
2574 const Vector<DisplayState>& displays,
2575 uint32_t flags)
2576{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002577 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002578 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002579 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002580
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002581 if (flags & eAnimation) {
2582 // For window updates that are part of an animation we must wait for
2583 // previous animation "frames" to be handled.
2584 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002585 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002586 if (CC_UNLIKELY(err != NO_ERROR)) {
2587 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002588 // caller after a few seconds.
2589 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2590 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002591 mAnimTransactionPending = false;
2592 break;
2593 }
2594 }
2595 }
2596
Mathias Agopiane57f2922012-08-09 16:29:12 -07002597 size_t count = displays.size();
2598 for (size_t i=0 ; i<count ; i++) {
2599 const DisplayState& s(displays[i]);
2600 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002601 }
2602
Mathias Agopiane57f2922012-08-09 16:29:12 -07002603 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002604 for (size_t i=0 ; i<count ; i++) {
2605 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002606 // Here we need to check that the interface we're given is indeed
2607 // one of our own. A malicious client could give us a NULL
2608 // IInterface, or one of its own or even one of our own but a
2609 // different type. All these situations would cause us to crash.
2610 //
2611 // NOTE: it would be better to use RTTI as we could directly check
2612 // that we have a Client*. however, RTTI is disabled in Android.
2613 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002614 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002615 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002616 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002617 sp<Client> client( static_cast<Client *>(s.client.get()) );
2618 transactionFlags |= setClientStateLocked(client, s.state);
2619 }
2620 }
2621 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002622 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002623
Robert Carr2a7dbb42016-05-24 11:41:28 -07002624 // If a synchronous transaction is explicitly requested without any changes,
2625 // force a transaction anyway. This can be used as a flush mechanism for
2626 // previous async transactions.
2627 if (transactionFlags == 0 && (flags & eSynchronous)) {
2628 transactionFlags = eTransactionNeeded;
2629 }
2630
Mathias Agopian386aa982011-11-07 21:58:03 -08002631 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002632 if (mInterceptor.isEnabled()) {
2633 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2634 }
Irvel468051e2016-06-13 16:44:44 -07002635
Mathias Agopian386aa982011-11-07 21:58:03 -08002636 // this triggers the transaction
2637 setTransactionFlags(transactionFlags);
2638
2639 // if this is a synchronous transaction, wait for it to take effect
2640 // before returning.
2641 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002642 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002643 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002644 if (flags & eAnimation) {
2645 mAnimTransactionPending = true;
2646 }
2647 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002648 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2649 if (CC_UNLIKELY(err != NO_ERROR)) {
2650 // just in case something goes wrong in SF, return to the
2651 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002652 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2653 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002654 break;
2655 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
2658}
2659
Mathias Agopiane57f2922012-08-09 16:29:12 -07002660uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2661{
Jesse Hall9a143922012-10-04 16:29:19 -07002662 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2663 if (dpyIdx < 0)
2664 return 0;
2665
Mathias Agopiane57f2922012-08-09 16:29:12 -07002666 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002667 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002668 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669 const uint32_t what = s.what;
2670 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002671 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002672 disp.surface = s.surface;
2673 flags |= eDisplayTransactionNeeded;
2674 }
2675 }
2676 if (what & DisplayState::eLayerStackChanged) {
2677 if (disp.layerStack != s.layerStack) {
2678 disp.layerStack = s.layerStack;
2679 flags |= eDisplayTransactionNeeded;
2680 }
2681 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002682 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 if (disp.orientation != s.orientation) {
2684 disp.orientation = s.orientation;
2685 flags |= eDisplayTransactionNeeded;
2686 }
2687 if (disp.frame != s.frame) {
2688 disp.frame = s.frame;
2689 flags |= eDisplayTransactionNeeded;
2690 }
2691 if (disp.viewport != s.viewport) {
2692 disp.viewport = s.viewport;
2693 flags |= eDisplayTransactionNeeded;
2694 }
2695 }
Michael Lentine47e45402014-07-18 15:34:25 -07002696 if (what & DisplayState::eDisplaySizeChanged) {
2697 if (disp.width != s.width) {
2698 disp.width = s.width;
2699 flags |= eDisplayTransactionNeeded;
2700 }
2701 if (disp.height != s.height) {
2702 disp.height = s.height;
2703 flags |= eDisplayTransactionNeeded;
2704 }
2705 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002706 }
2707 return flags;
2708}
2709
2710uint32_t SurfaceFlinger::setClientStateLocked(
2711 const sp<Client>& client,
2712 const layer_state_t& s)
2713{
2714 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002715 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002716 if (layer != 0) {
2717 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002718 bool geometryAppliesWithResize =
2719 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002720 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002721 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002722 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002723 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002724 }
2725 if (what & layer_state_t::eLayerChanged) {
2726 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727 const auto& p = layer->getParent();
2728 if (p == nullptr) {
2729 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2730 if (layer->setLayer(s.z) && idx >= 0) {
2731 mCurrentState.layersSortedByZ.removeAt(idx);
2732 mCurrentState.layersSortedByZ.add(layer);
2733 // we need traversal (state changed)
2734 // AND transaction (list changed)
2735 flags |= eTransactionNeeded|eTraversalNeeded;
2736 }
2737 } else {
2738 if (p->setChildLayer(layer, s.z)) {
2739 flags |= eTransactionNeeded|eTraversalNeeded;
2740 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 }
2742 }
2743 if (what & layer_state_t::eSizeChanged) {
2744 if (layer->setSize(s.w, s.h)) {
2745 flags |= eTraversalNeeded;
2746 }
2747 }
2748 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002750 flags |= eTraversalNeeded;
2751 }
2752 if (what & layer_state_t::eMatrixChanged) {
2753 if (layer->setMatrix(s.matrix))
2754 flags |= eTraversalNeeded;
2755 }
2756 if (what & layer_state_t::eTransparentRegionChanged) {
2757 if (layer->setTransparentRegionHint(s.transparentRegion))
2758 flags |= eTraversalNeeded;
2759 }
Dan Stoza23116082015-06-18 14:58:39 -07002760 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002761 if (layer->setFlags(s.flags, s.mask))
2762 flags |= eTraversalNeeded;
2763 }
2764 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002765 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002766 flags |= eTraversalNeeded;
2767 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002768 if (what & layer_state_t::eFinalCropChanged) {
2769 if (layer->setFinalCrop(s.finalCrop))
2770 flags |= eTraversalNeeded;
2771 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002772 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 // We only allow setting layer stacks for top level layers,
2775 // everything else inherits layer stack from its parent.
2776 if (layer->hasParent()) {
2777 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2778 layer->getName().string());
2779 } else if (idx < 0) {
2780 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2781 "that also does not appear in the top level layer list. Something"
2782 " has gone wrong.", layer->getName().string());
2783 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002784 mCurrentState.layersSortedByZ.removeAt(idx);
2785 mCurrentState.layersSortedByZ.add(layer);
2786 // we need traversal (state changed)
2787 // AND transaction (list changed)
2788 flags |= eTransactionNeeded|eTraversalNeeded;
2789 }
2790 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002791 if (what & layer_state_t::eDeferTransaction) {
2792 layer->deferTransactionUntil(s.handle, s.frameNumber);
2793 // We don't trigger a traversal here because if no other state is
2794 // changed, we don't want this to cause any more work
2795 }
Robert Carr1db73f62016-12-21 12:58:51 -08002796 if (what & layer_state_t::eReparentChildren) {
2797 if (layer->reparentChildren(s.reparentHandle)) {
2798 flags |= eTransactionNeeded|eTraversalNeeded;
2799 }
2800 }
Robert Carrc3574f72016-03-24 12:19:32 -07002801 if (what & layer_state_t::eOverrideScalingModeChanged) {
2802 layer->setOverrideScalingMode(s.overrideScalingMode);
2803 // We don't trigger a traversal here because if no other state is
2804 // changed, we don't want this to cause any more work
2805 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002806 }
2807 return flags;
2808}
2809
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002810status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002811 const String8& name,
2812 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002813 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002814 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2815 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002817 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002818 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002819 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002820 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002821 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002822
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002823 status_t result = NO_ERROR;
2824
2825 sp<Layer> layer;
2826
Mathias Agopian3165cc22012-08-08 19:42:09 -07002827 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2828 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002829 result = createNormalLayer(client,
2830 name, w, h, flags, format,
2831 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002833 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002834 result = createDimLayer(client,
2835 name, w, h, flags,
2836 handle, gbp, &layer);
2837 break;
2838 default:
2839 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 break;
2841 }
2842
Dan Stoza7d89d062015-04-30 13:29:25 -07002843 if (result != NO_ERROR) {
2844 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002846
Albert Chaulk479c60c2017-01-27 14:21:34 -05002847 layer->setInfo(windowType, ownerUid);
2848
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002850 if (result != NO_ERROR) {
2851 return result;
2852 }
Irvelffc9efc2016-07-27 15:16:37 -07002853 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002854
2855 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002856 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857}
2858
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002859status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2860 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2861 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862{
2863 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002864 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 case PIXEL_FORMAT_TRANSPARENT:
2866 case PIXEL_FORMAT_TRANSLUCENT:
2867 format = PIXEL_FORMAT_RGBA_8888;
2868 break;
2869 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002870 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 break;
2872 }
2873
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002874 *outLayer = new Layer(this, client, name, w, h, flags);
2875 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2876 if (err == NO_ERROR) {
2877 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002878 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002880
2881 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2882 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883}
2884
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002885status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2886 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2887 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002889 *outLayer = new LayerDim(this, client, name, w, h, flags);
2890 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002891 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002892 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002893}
2894
Mathias Agopianac9fa422013-02-11 16:40:36 -08002895status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
Mathias Agopian67106042013-03-14 19:18:13 -07002897 // called by the window manager when it wants to remove a Layer
2898 status_t err = NO_ERROR;
2899 sp<Layer> l(client->getLayerUser(handle));
2900 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002901 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002902 err = removeLayer(l);
2903 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2904 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002905 }
2906 return err;
2907}
2908
Mathias Agopian13127d82013-03-05 17:47:11 -08002909status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002910{
Mathias Agopian67106042013-03-14 19:18:13 -07002911 // called by ~LayerCleaner() when all references to the IBinder (handle)
2912 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002913 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914}
2915
Mathias Agopianb60314a2012-04-10 22:09:54 -07002916// ---------------------------------------------------------------------------
2917
Andy McFadden13a082e2012-08-24 10:16:42 -07002918void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002919 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002920 Vector<ComposerState> state;
2921 Vector<DisplayState> displays;
2922 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002923 d.what = DisplayState::eDisplayProjectionChanged |
2924 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002925 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002926 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002927 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002928 d.frame.makeInvalid();
2929 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002930 d.width = 0;
2931 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002932 displays.add(d);
2933 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002934 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002935
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2937 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002938 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002939
2940 {
2941 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2942 mCompositorTiming.interval = period;
2943 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002944}
2945
2946void SurfaceFlinger::initializeDisplays() {
2947 class MessageScreenInitialized : public MessageBase {
2948 SurfaceFlinger* flinger;
2949 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002950 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002951 virtual bool handler() {
2952 flinger->onInitializeDisplays();
2953 return true;
2954 }
2955 };
2956 sp<MessageBase> msg = new MessageScreenInitialized(this);
2957 postMessageAsync(msg); // we may be called from main thread, use async message
2958}
2959
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002960void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2961 int mode) {
2962 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2963 this);
2964 int32_t type = hw->getDisplayType();
2965 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002966
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002967 if (mode == currentMode) {
2968 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002969 return;
2970 }
2971
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002972 hw->setPowerMode(mode);
2973 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2974 ALOGW("Trying to set power mode for virtual display");
2975 return;
2976 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002977
Irvelffc9efc2016-07-27 15:16:37 -07002978 if (mInterceptor.isEnabled()) {
2979 Mutex::Autolock _l(mStateLock);
2980 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2981 if (idx < 0) {
2982 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2983 return;
2984 }
2985 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2986 }
2987
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002988 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002989 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002990 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002991 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2992 // FIXME: eventthread only knows about the main display right now
2993 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002994 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002995 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002998 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002999 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003000
3001 struct sched_param param = {0};
3002 param.sched_priority = 1;
3003 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3004 ALOGW("Couldn't set SCHED_FIFO on display on");
3005 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003007 // Turn off the display
3008 struct sched_param param = {0};
3009 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3010 ALOGW("Couldn't set SCHED_OTHER on display off");
3011 }
3012
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003013 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003014 disableHardwareVsync(true); // also cancels any in-progress resync
3015
Mathias Agopiancde87a32012-09-13 14:09:01 -07003016 // FIXME: eventthread only knows about the main display right now
3017 mEventThread->onScreenReleased();
3018 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003019
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003020 getHwComposer().setPowerMode(type, mode);
3021 mVisibleRegionsDirty = true;
3022 // from this point on, SF will stop drawing on this display
3023 } else {
3024 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003025 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003026}
3027
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003028void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3029 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003030 SurfaceFlinger& mFlinger;
3031 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003032 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003034 MessageSetPowerMode(SurfaceFlinger& flinger,
3035 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3036 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003037 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003038 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003039 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003041 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003042 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 ALOGW("Attempt to set power mode = %d for virtual display",
3044 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003045 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003046 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003047 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003048 return true;
3049 }
3050 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003052 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003053}
3054
3055// ---------------------------------------------------------------------------
3056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3058{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003060
Mathias Agopianbd115332013-04-18 16:41:04 -07003061 IPCThreadState* ipc = IPCThreadState::self();
3062 const int pid = ipc->getCallingPid();
3063 const int uid = ipc->getCallingUid();
3064 if ((uid != AID_SHELL) &&
3065 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003066 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003067 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003069 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003070 // (this would indicate SF is stuck, but we want to be able to
3071 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003072 status_t err = mStateLock.timedLock(s2ns(1));
3073 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003074 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003075 result.appendFormat(
3076 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3077 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003078 }
3079
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003080 bool dumpAll = true;
3081 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003082 size_t numArgs = args.size();
3083 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003084 if ((index < numArgs) &&
3085 (args[index] == String16("--list"))) {
3086 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003087 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003088 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003089 }
3090
3091 if ((index < numArgs) &&
3092 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003093 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003094 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003095 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003096 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003097
3098 if ((index < numArgs) &&
3099 (args[index] == String16("--latency-clear"))) {
3100 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003101 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003102 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003103 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003104
3105 if ((index < numArgs) &&
3106 (args[index] == String16("--dispsync"))) {
3107 index++;
3108 mPrimaryDispSync.dump(result);
3109 dumpAll = false;
3110 }
Dan Stozab90cf072015-03-05 11:05:59 -08003111
3112 if ((index < numArgs) &&
3113 (args[index] == String16("--static-screen"))) {
3114 index++;
3115 dumpStaticScreenStats(result);
3116 dumpAll = false;
3117 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003118
3119 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003120 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003121 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003122 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003123 dumpAll = false;
3124 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003126
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003127 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003128 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003129 }
3130
Mathias Agopian9795c422009-08-26 16:36:26 -07003131 if (locked) {
3132 mStateLock.unlock();
3133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
3135 write(fd, result.string(), result.size());
3136 return NO_ERROR;
3137}
3138
Dan Stozac7014012014-02-14 15:03:43 -08003139void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3140 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003141{
Robert Carr2047fae2016-11-28 14:09:09 -08003142 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003143 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003144 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003145}
3146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003147void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003148 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003149{
3150 String8 name;
3151 if (index < args.size()) {
3152 name = String8(args[index]);
3153 index++;
3154 }
3155
Dan Stoza9e56aa02015-11-02 13:00:03 -08003156 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3157 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003158 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003159
3160 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003161 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003162 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003163 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003164 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003165 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003166 }
Robert Carr2047fae2016-11-28 14:09:09 -08003167 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003168 }
3169}
3170
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003171void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003172 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003173{
3174 String8 name;
3175 if (index < args.size()) {
3176 name = String8(args[index]);
3177 index++;
3178 }
3179
Robert Carr2047fae2016-11-28 14:09:09 -08003180 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003181 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003182 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003183 }
Robert Carr2047fae2016-11-28 14:09:09 -08003184 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003185
Svetoslavd85084b2014-03-20 10:28:31 -07003186 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003187}
3188
Jamie Gennis6547ff42013-07-16 20:12:42 -07003189// This should only be called from the main thread. Otherwise it would need
3190// the lock and should use mCurrentState rather than mDrawingState.
3191void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003192 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003193 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003194 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003195
3196 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3197}
3198
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003199void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003200{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003201 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003202#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003203 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003204#endif
3205#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003206 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003207#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003208 if (isLayerTripleBufferingDisabled())
3209 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003210 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003211}
3212
Dan Stozab90cf072015-03-05 11:05:59 -08003213void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3214{
3215 result.appendFormat("Static screen stats:\n");
3216 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3217 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3218 float percent = 100.0f *
3219 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3220 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3221 b + 1, bucketTimeSec, percent);
3222 }
3223 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3224 float percent = 100.0f *
3225 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3226 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3227 NUM_BUCKETS - 1, bucketTimeSec, percent);
3228}
3229
Dan Stozae77c7662016-05-13 11:37:28 -07003230void SurfaceFlinger::recordBufferingStats(const char* layerName,
3231 std::vector<OccupancyTracker::Segment>&& history) {
3232 Mutex::Autolock lock(mBufferingStatsMutex);
3233 auto& stats = mBufferingStats[layerName];
3234 for (const auto& segment : history) {
3235 if (!segment.usedThirdBuffer) {
3236 stats.twoBufferTime += segment.totalTime;
3237 }
3238 if (segment.occupancyAverage < 1.0f) {
3239 stats.doubleBufferedTime += segment.totalTime;
3240 } else if (segment.occupancyAverage < 2.0f) {
3241 stats.tripleBufferedTime += segment.totalTime;
3242 }
3243 ++stats.numSegments;
3244 stats.totalTime += segment.totalTime;
3245 }
3246}
3247
Brian Andersond6927fb2016-07-23 23:37:30 -07003248void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3249 result.appendFormat("Layer frame timestamps:\n");
3250
3251 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3252 const size_t count = currentLayers.size();
3253 for (size_t i=0 ; i<count ; i++) {
3254 currentLayers[i]->dumpFrameEvents(result);
3255 }
3256}
3257
Dan Stozae77c7662016-05-13 11:37:28 -07003258void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3259 result.append("Buffering stats:\n");
3260 result.append(" [Layer name] <Active time> <Two buffer> "
3261 "<Double buffered> <Triple buffered>\n");
3262 Mutex::Autolock lock(mBufferingStatsMutex);
3263 typedef std::tuple<std::string, float, float, float> BufferTuple;
3264 std::map<float, BufferTuple, std::greater<float>> sorted;
3265 for (const auto& statsPair : mBufferingStats) {
3266 const char* name = statsPair.first.c_str();
3267 const BufferingStats& stats = statsPair.second;
3268 if (stats.numSegments == 0) {
3269 continue;
3270 }
3271 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3272 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3273 stats.totalTime;
3274 float doubleBufferRatio = static_cast<float>(
3275 stats.doubleBufferedTime) / stats.totalTime;
3276 float tripleBufferRatio = static_cast<float>(
3277 stats.tripleBufferedTime) / stats.totalTime;
3278 sorted.insert({activeTime, {name, twoBufferRatio,
3279 doubleBufferRatio, tripleBufferRatio}});
3280 }
3281 for (const auto& sortedPair : sorted) {
3282 float activeTime = sortedPair.first;
3283 const BufferTuple& values = sortedPair.second;
3284 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3285 std::get<0>(values).c_str(), activeTime,
3286 std::get<1>(values), std::get<2>(values),
3287 std::get<3>(values));
3288 }
3289 result.append("\n");
3290}
3291
3292
Mathias Agopian74d211a2013-04-22 16:55:35 +02003293void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3294 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003295{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003296 bool colorize = false;
3297 if (index < args.size()
3298 && (args[index] == String16("--color"))) {
3299 colorize = true;
3300 index++;
3301 }
3302
3303 Colorizer colorizer(colorize);
3304
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003305 // figure out if we're stuck somewhere
3306 const nsecs_t now = systemTime();
3307 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3308 const nsecs_t inTransaction(mDebugInTransaction);
3309 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3310 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3311
3312 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003313 * Dump library configuration.
3314 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003315
3316 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003317 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003318 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003319 appendSfConfigString(result);
3320 appendUiConfigString(result);
3321 appendGuiConfigString(result);
3322 result.append("\n");
3323
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003324 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003325 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003326 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003327 result.append(SyncFeatures::getInstance().toString());
3328 result.append("\n");
3329
Dan Stoza9e56aa02015-11-02 13:00:03 -08003330 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3331
Andy McFadden41d67d72014-04-25 16:58:34 -07003332 colorizer.bold(result);
3333 result.append("DispSync configuration: ");
3334 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003335 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3336 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003337 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3338 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003339 result.append("\n");
3340
Dan Stozab90cf072015-03-05 11:05:59 -08003341 // Dump static screen stats
3342 result.append("\n");
3343 dumpStaticScreenStats(result);
3344 result.append("\n");
3345
Dan Stozae77c7662016-05-13 11:37:28 -07003346 dumpBufferingStats(result);
3347
Andy McFadden4803b742012-09-24 19:07:20 -07003348 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003349 * Dump the visible layer list
3350 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003351 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003352 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003353 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003354 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003355 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003356 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003357
3358 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003359 * Dump Display state
3360 */
3361
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003363 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003365 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3366 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003367 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003368 }
3369
3370 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003371 * Dump SurfaceFlinger global state
3372 */
3373
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003374 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003375 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003376 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003377
Mathias Agopian888c8222012-08-04 21:10:38 -07003378 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003379 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003380
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.bold(result);
3382 result.appendFormat("EGL implementation : %s\n",
3383 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3384 colorizer.reset(result);
3385 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003386 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003387
Mathias Agopian875d8e12013-06-07 15:35:48 -07003388 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003389
Mathias Agopian42977342012-08-05 00:40:46 -07003390 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003391 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3392 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003393 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003394 " last eglSwapBuffers() time: %f us\n"
3395 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003396 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003397 " refresh-rate : %f fps\n"
3398 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003399 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003400 " gpu_to_cpu_unsupported : %d\n"
3401 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402 mLastSwapBufferTime/1000.0,
3403 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003404 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003405 1e9 / activeConfig->getVsyncPeriod(),
3406 activeConfig->getDpiX(),
3407 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003408 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003409
Mathias Agopian74d211a2013-04-22 16:55:35 +02003410 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412
Mathias Agopian74d211a2013-04-22 16:55:35 +02003413 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003414 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003415
3416 /*
3417 * VSYNC state
3418 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003420 result.append("\n");
3421
3422 /*
3423 * HWC layer minidump
3424 */
3425 for (size_t d = 0; d < mDisplays.size(); d++) {
3426 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3427 int32_t hwcId = displayDevice->getHwcDisplayId();
3428 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3429 continue;
3430 }
3431
3432 result.appendFormat("Display %d HWC layers:\n", hwcId);
3433 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003434 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003435 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003436 });
Dan Stozae22aec72016-08-01 13:20:59 -07003437 result.append("\n");
3438 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003439
3440 /*
3441 * Dump HWComposer state
3442 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003443 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003444 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003445 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003446 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003447 result.appendFormat(" h/w composer %s\n",
3448 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003449 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003450
3451 /*
3452 * Dump gralloc state
3453 */
3454 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3455 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456}
3457
Mathias Agopian13127d82013-03-05 17:47:11 -08003458const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003459SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003460 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003461 wp<IBinder> dpy;
3462 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3463 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3464 dpy = mDisplays.keyAt(i);
3465 break;
3466 }
3467 }
3468 if (dpy == NULL) {
3469 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3470 // Just use the primary display so we have something to return
3471 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3472 }
3473 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003474}
3475
Keun young Park63f165f2012-08-31 10:53:36 -07003476bool SurfaceFlinger::startDdmConnection()
3477{
3478 void* libddmconnection_dso =
3479 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3480 if (!libddmconnection_dso) {
3481 return false;
3482 }
3483 void (*DdmConnection_start)(const char* name);
3484 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003485 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003486 if (!DdmConnection_start) {
3487 dlclose(libddmconnection_dso);
3488 return false;
3489 }
3490 (*DdmConnection_start)(getServiceName());
3491 return true;
3492}
3493
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003494status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495 switch (code) {
3496 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003497 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003498 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003499 case CLEAR_ANIMATION_FRAME_STATS:
3500 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003501 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003502 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503 {
3504 // codes that require permission check
3505 IPCThreadState* ipc = IPCThreadState::self();
3506 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003507 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003508 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003509 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003510 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003511 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003513 break;
3514 }
Robert Carr1db73f62016-12-21 12:58:51 -08003515 /*
3516 * Calling setTransactionState is safe, because you need to have been
3517 * granted a reference to Client* and Handle* to do anything with it.
3518 *
3519 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3520 */
3521 case SET_TRANSACTION_STATE:
3522 case CREATE_SCOPED_CONNECTION:
3523 {
3524 return OK;
3525 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003526 case CAPTURE_SCREEN:
3527 {
3528 // codes that require permission check
3529 IPCThreadState* ipc = IPCThreadState::self();
3530 const int pid = ipc->getCallingPid();
3531 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003532 if ((uid != AID_GRAPHICS) &&
3533 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003534 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003535 return PERMISSION_DENIED;
3536 }
3537 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 }
3539 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003540 return OK;
3541}
3542
3543status_t SurfaceFlinger::onTransact(
3544 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3545{
3546 status_t credentialCheck = CheckTransactCodeCredentials(code);
3547 if (credentialCheck != OK) {
3548 return credentialCheck;
3549 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3552 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003553 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003554 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003555 IPCThreadState* ipc = IPCThreadState::self();
3556 const int pid = ipc->getCallingPid();
3557 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003558 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003559 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 return PERMISSION_DENIED;
3561 }
3562 int n;
3563 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003564 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003565 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 return NO_ERROR;
3567 case 1002: // SHOW_UPDATES
3568 n = data.readInt32();
3569 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003570 invalidateHwcGeometry();
3571 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003574 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003575 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003577 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003578 setTransactionFlags(
3579 eTransactionNeeded|
3580 eDisplayTransactionNeeded|
3581 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003582 return NO_ERROR;
3583 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003584 case 1006:{ // send empty update
3585 signalRefresh();
3586 return NO_ERROR;
3587 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003588 case 1008: // toggle use of hw composer
3589 n = data.readInt32();
3590 mDebugDisableHWC = n ? 1 : 0;
3591 invalidateHwcGeometry();
3592 repaintEverything();
3593 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003594 case 1009: // toggle use of transform hint
3595 n = data.readInt32();
3596 mDebugDisableTransformHint = n ? 1 : 0;
3597 invalidateHwcGeometry();
3598 repaintEverything();
3599 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003601 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003602 reply->writeInt32(0);
3603 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003604 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003605 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 return NO_ERROR;
3607 case 1013: {
3608 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003609 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3610 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003611 return NO_ERROR;
3612 }
3613 case 1014: {
3614 // daltonize
3615 n = data.readInt32();
3616 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003617 case 1:
3618 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3619 break;
3620 case 2:
3621 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3622 break;
3623 case 3:
3624 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3625 break;
3626 default:
3627 mDaltonizer.setType(ColorBlindnessType::None);
3628 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003629 }
3630 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003631 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003632 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003633 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003634 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003635 invalidateHwcGeometry();
3636 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003637 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003639 case 1015: {
3640 // apply a color matrix
3641 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003642 if (n) {
3643 // color matrix is sent as mat3 matrix followed by vec3
3644 // offset, then packed into a mat4 where the last row is
3645 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003646 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003647 for (size_t j = 0; j < 4; j++) {
3648 mColorMatrix[i][j] = data.readFloat();
3649 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003650 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003651 } else {
3652 mColorMatrix = mat4();
3653 }
3654 invalidateHwcGeometry();
3655 repaintEverything();
3656 return NO_ERROR;
3657 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003658 // This is an experimental interface
3659 // Needs to be shifted to proper binder interface when we productize
3660 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003661 n = data.readInt32();
3662 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003663 return NO_ERROR;
3664 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003665 case 1017: {
3666 n = data.readInt32();
3667 mForceFullDamage = static_cast<bool>(n);
3668 return NO_ERROR;
3669 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003670 case 1018: { // Modify Choreographer's phase offset
3671 n = data.readInt32();
3672 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3673 return NO_ERROR;
3674 }
3675 case 1019: { // Modify SurfaceFlinger's phase offset
3676 n = data.readInt32();
3677 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3678 return NO_ERROR;
3679 }
Irvel468051e2016-06-13 16:44:44 -07003680 case 1020: { // Layer updates interceptor
3681 n = data.readInt32();
3682 if (n) {
3683 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003684 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003685 }
3686 else{
3687 ALOGV("Interceptor disabled");
3688 mInterceptor.disable();
3689 }
3690 return NO_ERROR;
3691 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003692 case 1021: { // Disable HWC virtual displays
3693 n = data.readInt32();
3694 mUseHwcVirtualDisplays = !n;
3695 return NO_ERROR;
3696 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697 }
3698 }
3699 return err;
3700}
3701
Mathias Agopian53331da2011-08-22 21:44:41 -07003702void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003703 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003704 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003705}
3706
Mathias Agopian59119e62010-10-11 12:37:43 -07003707// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003708// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003709// ---------------------------------------------------------------------------
3710
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003711/* The code below is here to handle b/8734824
3712 *
3713 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003714 * from the surfaceflinger thread to the calling binder thread, where they
3715 * are executed. This allows the calling thread in the calling process to be
3716 * reused and not depend on having "enough" binder threads to handle the
3717 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003718 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003719class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003720 /* Parts of GraphicProducerWrapper are run on two different threads,
3721 * communicating by sending messages via Looper but also by shared member
3722 * data. Coherence maintenance is subtle and in places implicit (ugh).
3723 *
3724 * Don't rely on Looper's sendMessage/handleMessage providing
3725 * release/acquire semantics for any data not actually in the Message.
3726 * Data going from surfaceflinger to binder threads needs to be
3727 * synchronized explicitly.
3728 *
3729 * Barrier open/wait do provide release/acquire semantics. This provides
3730 * implicit synchronization for data coming back from binder to
3731 * surfaceflinger threads.
3732 */
3733
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003734 sp<IGraphicBufferProducer> impl;
3735 sp<Looper> looper;
3736 status_t result;
3737 bool exitPending;
3738 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003739 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003740 uint32_t code;
3741 Parcel const* data;
3742 Parcel* reply;
3743
3744 enum {
3745 MSG_API_CALL,
3746 MSG_EXIT
3747 };
3748
3749 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003750 * Called on surfaceflinger thread. This is called by our "fake"
3751 * BpGraphicBufferProducer. We package the data and reply Parcel and
3752 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003753 */
3754 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003755 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003756 this->code = code;
3757 this->data = &data;
3758 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003759 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003760 // if we've exited, we run the message synchronously right here.
3761 // note (JH): as far as I can tell from looking at the code, this
3762 // never actually happens. if it does, i'm not sure if it happens
3763 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003764 handleMessage(Message(MSG_API_CALL));
3765 } else {
3766 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003767 // Prevent stores to this->{code, data, reply} from being
3768 // reordered later than the construction of Message.
3769 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003770 looper->sendMessage(this, Message(MSG_API_CALL));
3771 barrier.wait();
3772 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003773 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003774 }
3775
3776 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003777 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003778 * call the real BpGraphicBufferProducer.
3779 */
3780 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003781 int what = message.what;
3782 // Prevent reads below from happening before the read from Message
3783 atomic_thread_fence(memory_order_acquire);
3784 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003785 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003786 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003787 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003788 exitRequested = true;
3789 }
3790 }
3791
3792public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003793 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003794 : impl(impl),
3795 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003796 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003797 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003798 exitRequested(false),
3799 code(0),
3800 data(NULL),
3801 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003802 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003803
Jesse Hallb154c422014-07-13 12:47:02 -07003804 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003805 status_t waitForResponse() {
3806 do {
3807 looper->pollOnce(-1);
3808 } while (!exitRequested);
3809 return result;
3810 }
3811
Jesse Hallb154c422014-07-13 12:47:02 -07003812 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003813 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003814 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003815 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003816 // Ensure this->result is visible to the binder thread before it
3817 // handles the message.
3818 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003819 looper->sendMessage(this, Message(MSG_EXIT));
3820 }
3821};
3822
3823
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003824status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3825 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003826 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003827 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003828 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003829
3830 if (CC_UNLIKELY(display == 0))
3831 return BAD_VALUE;
3832
3833 if (CC_UNLIKELY(producer == 0))
3834 return BAD_VALUE;
3835
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003836 // if we have secure windows on this display, never allow the screen capture
3837 // unless the producer interface is local (i.e.: we can take a screenshot for
3838 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003839 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003840
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003841 // Convert to surfaceflinger's internal rotation type.
3842 Transform::orientation_flags rotationFlags;
3843 switch (rotation) {
3844 case ISurfaceComposer::eRotateNone:
3845 rotationFlags = Transform::ROT_0;
3846 break;
3847 case ISurfaceComposer::eRotate90:
3848 rotationFlags = Transform::ROT_90;
3849 break;
3850 case ISurfaceComposer::eRotate180:
3851 rotationFlags = Transform::ROT_180;
3852 break;
3853 case ISurfaceComposer::eRotate270:
3854 rotationFlags = Transform::ROT_270;
3855 break;
3856 default:
3857 rotationFlags = Transform::ROT_0;
3858 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3859 break;
3860 }
3861
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003862 class MessageCaptureScreen : public MessageBase {
3863 SurfaceFlinger* flinger;
3864 sp<IBinder> display;
3865 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003866 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003867 uint32_t reqWidth, reqHeight;
3868 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003869 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003870 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003872 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003873 public:
3874 MessageCaptureScreen(SurfaceFlinger* flinger,
3875 const sp<IBinder>& display,
3876 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003877 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003878 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003879 bool useIdentityTransform,
3880 Transform::orientation_flags rotation,
3881 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003882 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003883 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003884 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003885 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003886 rotation(rotation), result(PERMISSION_DENIED),
3887 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003888 {
3889 }
3890 status_t getResult() const {
3891 return result;
3892 }
3893 virtual bool handler() {
3894 Mutex::Autolock _l(flinger->mStateLock);
3895 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003896 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003897 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003898 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003899 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003900 return true;
3901 }
3902 };
3903
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003904 // this creates a "fake" BBinder which will serve as a "fake" remote
3905 // binder to receive the marshaled calls and forward them to the
3906 // real remote (a BpGraphicBufferProducer)
3907 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3908
3909 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3910 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003911 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003912 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003913 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003914 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003915
3916 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003917 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003918 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003919 }
3920 return res;
3921}
3922
Mathias Agopian180f10d2013-04-10 22:55:41 -07003923
3924void SurfaceFlinger::renderScreenImplLocked(
3925 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003926 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003927 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003928 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003929{
3930 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003931 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003932
3933 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003934 const int32_t hw_w = hw->getWidth();
3935 const int32_t hw_h = hw->getHeight();
3936 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003937 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003938
Dan Stozac1879002014-05-22 15:59:05 -07003939 // if a default or invalid sourceCrop is passed in, set reasonable values
3940 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3941 !sourceCrop.isValid()) {
3942 sourceCrop.setLeftTop(Point(0, 0));
3943 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3944 }
3945
3946 // ensure that sourceCrop is inside screen
3947 if (sourceCrop.left < 0) {
3948 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3949 }
Dan Stozabe31f442014-06-11 11:20:54 -07003950 if (sourceCrop.right > hw_w) {
3951 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003952 }
3953 if (sourceCrop.top < 0) {
3954 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3955 }
Dan Stozabe31f442014-06-11 11:20:54 -07003956 if (sourceCrop.bottom > hw_h) {
3957 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003958 }
3959
Mathias Agopian180f10d2013-04-10 22:55:41 -07003960 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003961 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003962
3963 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003964 engine.setViewportAndProjection(
3965 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003966 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003967
3968 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003969 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003970
Robert Carr1f0a16a2016-10-24 16:27:39 -07003971 // We loop through the first level of layers without traversing,
3972 // as we need to interpret min/max layer Z in the top level Z space.
3973 for (const auto& layer : mDrawingState.layersSortedByZ) {
3974 if (layer->getLayerStack() != hw->getLayerStack()) {
3975 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003977 const Layer::State& state(layer->getDrawingState());
3978 if (state.z < minLayerZ || state.z > maxLayerZ) {
3979 continue;
3980 }
3981 layer->traverseInZOrder([&](Layer* layer) {
3982 if (!layer->isVisible()) {
3983 return;
3984 }
3985 if (filtering) layer->setFiltering(true);
3986 layer->draw(hw, useIdentityTransform);
3987 if (filtering) layer->setFiltering(false);
3988 });
3989 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003990
Mathias Agopian931bda12013-08-28 18:11:46 -07003991 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003992}
3993
3994
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003995status_t SurfaceFlinger::captureScreenImplLocked(
3996 const sp<const DisplayDevice>& hw,
3997 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003998 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003999 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004000 bool useIdentityTransform, Transform::orientation_flags rotation,
4001 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004002{
4003 ATRACE_CALL();
4004
Mathias Agopian180f10d2013-04-10 22:55:41 -07004005 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004006 uint32_t hw_w = hw->getWidth();
4007 uint32_t hw_h = hw->getHeight();
4008
4009 if (rotation & Transform::ROT_90) {
4010 std::swap(hw_w, hw_h);
4011 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004012
Mathias Agopian180f10d2013-04-10 22:55:41 -07004013 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4014 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4015 reqWidth, reqHeight, hw_w, hw_h);
4016 return BAD_VALUE;
4017 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004018
Mathias Agopian180f10d2013-04-10 22:55:41 -07004019 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4020 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4021
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004022 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004023 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004024 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004025 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4026 (state.z < minLayerZ || state.z > maxLayerZ)) {
4027 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004028 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004029 layer->traverseInZOrder([&](Layer *layer) {
4030 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4031 layer->isSecure());
4032 });
4033 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004034
4035 if (!isLocalScreenshot && secureLayerIsVisible) {
4036 ALOGW("FB is protected: PERMISSION_DENIED");
4037 return PERMISSION_DENIED;
4038 }
4039
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004040 // create a surface (because we're a producer, and we need to
4041 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004042 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004043
4044 // Put the screenshot Surface into async mode so that
4045 // Layer::headFenceHasSignaled will always return true and we'll latch the
4046 // first buffer regardless of whether or not its acquire fence has
4047 // signaled. This is needed to avoid a race condition in the rotation
4048 // animation. See b/30209608
4049 sur->setAsyncMode(true);
4050
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004051 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004052
Michael Lentine5a16a622015-05-21 13:48:24 -07004053 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4054 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004055 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4056 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004057
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004058 int err = 0;
4059 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004060 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004061 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4062 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004063
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004064 if (err == NO_ERROR) {
4065 ANativeWindowBuffer* buffer;
4066 /* TODO: Once we have the sync framework everywhere this can use
4067 * server-side waits on the fence that dequeueBuffer returns.
4068 */
4069 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4070 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004071 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004072 // create an EGLImage from the buffer so we can later
4073 // turn it into a texture
4074 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4075 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4076 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004077 // this binds the given EGLImage as a framebuffer for the
4078 // duration of this scope.
4079 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4080 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 // this will in fact render into our dequeued buffer
4082 // via an FBO, which means we didn't have to create
4083 // an EGLSurface and therefore we're not
4084 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004085 renderScreenImplLocked(
4086 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4087 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004088
Riley Andrews86639902014-08-15 12:27:24 -07004089 // Attempt to create a sync khr object that can produce a sync point. If that
4090 // isn't available, create a non-dupable sync object in the fallback path and
4091 // wait on it directly.
4092 EGLSyncKHR sync;
4093 if (!DEBUG_SCREENSHOTS) {
4094 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004095 // native fence fd will not be populated until flush() is done.
4096 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004097 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004098 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004099 }
Riley Andrews86639902014-08-15 12:27:24 -07004100 if (sync != EGL_NO_SYNC_KHR) {
4101 // get the sync fd
4102 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4103 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4104 ALOGW("captureScreen: failed to dup sync khr object");
4105 syncFd = -1;
4106 }
4107 eglDestroySyncKHR(mEGLDisplay, sync);
4108 } else {
4109 // fallback path
4110 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4111 if (sync != EGL_NO_SYNC_KHR) {
4112 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4113 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4114 EGLint eglErr = eglGetError();
4115 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4116 ALOGW("captureScreen: fence wait timed out");
4117 } else {
4118 ALOGW_IF(eglErr != EGL_SUCCESS,
4119 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4120 }
4121 eglDestroySyncKHR(mEGLDisplay, sync);
4122 } else {
4123 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4124 }
4125 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004126 if (DEBUG_SCREENSHOTS) {
4127 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4128 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4129 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4130 hw, minLayerZ, maxLayerZ);
4131 delete [] pixels;
4132 }
4133
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004134 } else {
4135 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4136 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004137 window->cancelBuffer(window, buffer, syncFd);
4138 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004139 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004140 // destroy our image
4141 eglDestroyImageKHR(mEGLDisplay, image);
4142 } else {
4143 result = BAD_VALUE;
4144 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004145 if (buffer) {
4146 // queueBuffer takes ownership of syncFd
4147 result = window->queueBuffer(window, buffer, syncFd);
4148 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004149 }
4150 } else {
4151 result = BAD_VALUE;
4152 }
4153 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4154 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004155
Mathias Agopian74c40c02010-09-29 13:02:36 -07004156 return result;
4157}
4158
Mathias Agopiand5556842013-09-19 17:08:37 -07004159void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004160 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004161 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004162 for (size_t y=0 ; y<h ; y++) {
4163 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4164 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004165 if (p[x] != 0xFF000000) return;
4166 }
4167 }
4168 ALOGE("*** we just took a black screenshot ***\n"
4169 "requested minz=%d, maxz=%d, layerStack=%d",
4170 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004171
Robert Carr2047fae2016-11-28 14:09:09 -08004172 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004173 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004174 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004175 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4176 state.z <= maxLayerZ) {
4177 layer->traverseInZOrder([&](Layer* layer) {
4178 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4179 layer->isVisible() ? '+' : '-',
4180 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004181 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004182 i++;
4183 });
4184 }
4185 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004186 }
4187}
4188
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004189// ---------------------------------------------------------------------------
4190
Robert Carr2047fae2016-11-28 14:09:09 -08004191void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4192 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004193}
4194
Robert Carr2047fae2016-11-28 14:09:09 -08004195void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4196 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004197}
4198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004199}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004200
4201
4202#if defined(__gl_h_)
4203#error "don't include gl/gl.h in this file"
4204#endif
4205
4206#if defined(__gl2_h_)
4207#error "don't include gl2/gl2.h in this file"
4208#endif