blob: 2781e8c4f9cd684352ad8f9d924711ac8bf6a298 [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
Robert Carr136e2f62017-02-08 17:54:29 -08002542 // As a matter of normal operation, the LayerCleaner will produce a second
2543 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2544 // so we will succeed in promoting it, but it's already been removed
2545 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2546 // otherwise something has gone wrong and we are leaking the layer.
2547 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2549 layer->getName().string(),
2550 (p != nullptr) ? p->getName().string() : "no-parent");
2551 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002552 } else if (index < 0) {
2553 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002554 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555
2556 mLayersPendingRemoval.add(layer);
2557 mLayersRemoved = true;
2558 mNumLayers--;
2559 setTransactionFlags(eTransactionNeeded);
2560 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561}
2562
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002563uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002564 return android_atomic_release_load(&mTransactionFlags);
2565}
2566
Mathias Agopian3f844832013-08-07 21:24:32 -07002567uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2569}
2570
Mathias Agopian3f844832013-08-07 21:24:32 -07002571uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2573 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002574 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 }
2576 return old;
2577}
2578
Mathias Agopian8b33f032012-07-24 20:43:54 -07002579void SurfaceFlinger::setTransactionState(
2580 const Vector<ComposerState>& state,
2581 const Vector<DisplayState>& displays,
2582 uint32_t flags)
2583{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002584 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002585 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002586 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002587
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002588 if (flags & eAnimation) {
2589 // For window updates that are part of an animation we must wait for
2590 // previous animation "frames" to be handled.
2591 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002592 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002593 if (CC_UNLIKELY(err != NO_ERROR)) {
2594 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002595 // caller after a few seconds.
2596 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2597 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002598 mAnimTransactionPending = false;
2599 break;
2600 }
2601 }
2602 }
2603
Mathias Agopiane57f2922012-08-09 16:29:12 -07002604 size_t count = displays.size();
2605 for (size_t i=0 ; i<count ; i++) {
2606 const DisplayState& s(displays[i]);
2607 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002608 }
2609
Mathias Agopiane57f2922012-08-09 16:29:12 -07002610 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002611 for (size_t i=0 ; i<count ; i++) {
2612 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002613 // Here we need to check that the interface we're given is indeed
2614 // one of our own. A malicious client could give us a NULL
2615 // IInterface, or one of its own or even one of our own but a
2616 // different type. All these situations would cause us to crash.
2617 //
2618 // NOTE: it would be better to use RTTI as we could directly check
2619 // that we have a Client*. however, RTTI is disabled in Android.
2620 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002621 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002622 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002623 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002624 sp<Client> client( static_cast<Client *>(s.client.get()) );
2625 transactionFlags |= setClientStateLocked(client, s.state);
2626 }
2627 }
2628 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002629 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002630
Robert Carr2a7dbb42016-05-24 11:41:28 -07002631 // If a synchronous transaction is explicitly requested without any changes,
2632 // force a transaction anyway. This can be used as a flush mechanism for
2633 // previous async transactions.
2634 if (transactionFlags == 0 && (flags & eSynchronous)) {
2635 transactionFlags = eTransactionNeeded;
2636 }
2637
Mathias Agopian386aa982011-11-07 21:58:03 -08002638 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002639 if (mInterceptor.isEnabled()) {
2640 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2641 }
Irvel468051e2016-06-13 16:44:44 -07002642
Mathias Agopian386aa982011-11-07 21:58:03 -08002643 // this triggers the transaction
2644 setTransactionFlags(transactionFlags);
2645
2646 // if this is a synchronous transaction, wait for it to take effect
2647 // before returning.
2648 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002649 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002650 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002651 if (flags & eAnimation) {
2652 mAnimTransactionPending = true;
2653 }
2654 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002655 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2656 if (CC_UNLIKELY(err != NO_ERROR)) {
2657 // just in case something goes wrong in SF, return to the
2658 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002659 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2660 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002661 break;
2662 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 }
2665}
2666
Mathias Agopiane57f2922012-08-09 16:29:12 -07002667uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2668{
Jesse Hall9a143922012-10-04 16:29:19 -07002669 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2670 if (dpyIdx < 0)
2671 return 0;
2672
Mathias Agopiane57f2922012-08-09 16:29:12 -07002673 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002674 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002675 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676 const uint32_t what = s.what;
2677 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002678 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679 disp.surface = s.surface;
2680 flags |= eDisplayTransactionNeeded;
2681 }
2682 }
2683 if (what & DisplayState::eLayerStackChanged) {
2684 if (disp.layerStack != s.layerStack) {
2685 disp.layerStack = s.layerStack;
2686 flags |= eDisplayTransactionNeeded;
2687 }
2688 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002689 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002690 if (disp.orientation != s.orientation) {
2691 disp.orientation = s.orientation;
2692 flags |= eDisplayTransactionNeeded;
2693 }
2694 if (disp.frame != s.frame) {
2695 disp.frame = s.frame;
2696 flags |= eDisplayTransactionNeeded;
2697 }
2698 if (disp.viewport != s.viewport) {
2699 disp.viewport = s.viewport;
2700 flags |= eDisplayTransactionNeeded;
2701 }
2702 }
Michael Lentine47e45402014-07-18 15:34:25 -07002703 if (what & DisplayState::eDisplaySizeChanged) {
2704 if (disp.width != s.width) {
2705 disp.width = s.width;
2706 flags |= eDisplayTransactionNeeded;
2707 }
2708 if (disp.height != s.height) {
2709 disp.height = s.height;
2710 flags |= eDisplayTransactionNeeded;
2711 }
2712 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713 }
2714 return flags;
2715}
2716
2717uint32_t SurfaceFlinger::setClientStateLocked(
2718 const sp<Client>& client,
2719 const layer_state_t& s)
2720{
2721 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002722 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002723 if (layer != 0) {
2724 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002725 bool geometryAppliesWithResize =
2726 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002727 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002728 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002730 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 }
2732 if (what & layer_state_t::eLayerChanged) {
2733 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 const auto& p = layer->getParent();
2735 if (p == nullptr) {
2736 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2737 if (layer->setLayer(s.z) && idx >= 0) {
2738 mCurrentState.layersSortedByZ.removeAt(idx);
2739 mCurrentState.layersSortedByZ.add(layer);
2740 // we need traversal (state changed)
2741 // AND transaction (list changed)
2742 flags |= eTransactionNeeded|eTraversalNeeded;
2743 }
2744 } else {
2745 if (p->setChildLayer(layer, s.z)) {
2746 flags |= eTransactionNeeded|eTraversalNeeded;
2747 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002748 }
2749 }
2750 if (what & layer_state_t::eSizeChanged) {
2751 if (layer->setSize(s.w, s.h)) {
2752 flags |= eTraversalNeeded;
2753 }
2754 }
2755 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 flags |= eTraversalNeeded;
2758 }
2759 if (what & layer_state_t::eMatrixChanged) {
2760 if (layer->setMatrix(s.matrix))
2761 flags |= eTraversalNeeded;
2762 }
2763 if (what & layer_state_t::eTransparentRegionChanged) {
2764 if (layer->setTransparentRegionHint(s.transparentRegion))
2765 flags |= eTraversalNeeded;
2766 }
Dan Stoza23116082015-06-18 14:58:39 -07002767 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002768 if (layer->setFlags(s.flags, s.mask))
2769 flags |= eTraversalNeeded;
2770 }
2771 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002772 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 flags |= eTraversalNeeded;
2774 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002775 if (what & layer_state_t::eFinalCropChanged) {
2776 if (layer->setFinalCrop(s.finalCrop))
2777 flags |= eTraversalNeeded;
2778 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002779 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 // We only allow setting layer stacks for top level layers,
2782 // everything else inherits layer stack from its parent.
2783 if (layer->hasParent()) {
2784 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2785 layer->getName().string());
2786 } else if (idx < 0) {
2787 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2788 "that also does not appear in the top level layer list. Something"
2789 " has gone wrong.", layer->getName().string());
2790 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791 mCurrentState.layersSortedByZ.removeAt(idx);
2792 mCurrentState.layersSortedByZ.add(layer);
2793 // we need traversal (state changed)
2794 // AND transaction (list changed)
2795 flags |= eTransactionNeeded|eTraversalNeeded;
2796 }
2797 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002798 if (what & layer_state_t::eDeferTransaction) {
2799 layer->deferTransactionUntil(s.handle, s.frameNumber);
2800 // We don't trigger a traversal here because if no other state is
2801 // changed, we don't want this to cause any more work
2802 }
Robert Carr1db73f62016-12-21 12:58:51 -08002803 if (what & layer_state_t::eReparentChildren) {
2804 if (layer->reparentChildren(s.reparentHandle)) {
2805 flags |= eTransactionNeeded|eTraversalNeeded;
2806 }
2807 }
Robert Carrc3574f72016-03-24 12:19:32 -07002808 if (what & layer_state_t::eOverrideScalingModeChanged) {
2809 layer->setOverrideScalingMode(s.overrideScalingMode);
2810 // We don't trigger a traversal here because if no other state is
2811 // changed, we don't want this to cause any more work
2812 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813 }
2814 return flags;
2815}
2816
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002817status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002818 const String8& name,
2819 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002820 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002821 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2822 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002824 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002825 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002826 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002827 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002828 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002829
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002830 status_t result = NO_ERROR;
2831
2832 sp<Layer> layer;
2833
Mathias Agopian3165cc22012-08-08 19:42:09 -07002834 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2835 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002836 result = createNormalLayer(client,
2837 name, w, h, flags, format,
2838 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002840 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002841 result = createDimLayer(client,
2842 name, w, h, flags,
2843 handle, gbp, &layer);
2844 break;
2845 default:
2846 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 break;
2848 }
2849
Dan Stoza7d89d062015-04-30 13:29:25 -07002850 if (result != NO_ERROR) {
2851 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002853
Albert Chaulk479c60c2017-01-27 14:21:34 -05002854 layer->setInfo(windowType, ownerUid);
2855
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002857 if (result != NO_ERROR) {
2858 return result;
2859 }
Irvelffc9efc2016-07-27 15:16:37 -07002860 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002861
2862 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002863 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864}
2865
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002866status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2867 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2868 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869{
2870 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002871 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 case PIXEL_FORMAT_TRANSPARENT:
2873 case PIXEL_FORMAT_TRANSLUCENT:
2874 format = PIXEL_FORMAT_RGBA_8888;
2875 break;
2876 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002877 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 break;
2879 }
2880
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002881 *outLayer = new Layer(this, client, name, w, h, flags);
2882 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2883 if (err == NO_ERROR) {
2884 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002885 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002887
2888 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2889 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890}
2891
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002892status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2893 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2894 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002896 *outLayer = new LayerDim(this, client, name, w, h, flags);
2897 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002898 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002899 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002900}
2901
Mathias Agopianac9fa422013-02-11 16:40:36 -08002902status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903{
Mathias Agopian67106042013-03-14 19:18:13 -07002904 // called by the window manager when it wants to remove a Layer
2905 status_t err = NO_ERROR;
2906 sp<Layer> l(client->getLayerUser(handle));
2907 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002908 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002909 err = removeLayer(l);
2910 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2911 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002912 }
2913 return err;
2914}
2915
Mathias Agopian13127d82013-03-05 17:47:11 -08002916status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002917{
Mathias Agopian67106042013-03-14 19:18:13 -07002918 // called by ~LayerCleaner() when all references to the IBinder (handle)
2919 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002920 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921}
2922
Mathias Agopianb60314a2012-04-10 22:09:54 -07002923// ---------------------------------------------------------------------------
2924
Andy McFadden13a082e2012-08-24 10:16:42 -07002925void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002926 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002927 Vector<ComposerState> state;
2928 Vector<DisplayState> displays;
2929 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002930 d.what = DisplayState::eDisplayProjectionChanged |
2931 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002932 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002933 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002934 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002935 d.frame.makeInvalid();
2936 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002937 d.width = 0;
2938 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002939 displays.add(d);
2940 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002941 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002942
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2944 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002945 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002946
2947 {
2948 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2949 mCompositorTiming.interval = period;
2950 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002951}
2952
2953void SurfaceFlinger::initializeDisplays() {
2954 class MessageScreenInitialized : public MessageBase {
2955 SurfaceFlinger* flinger;
2956 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002957 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002958 virtual bool handler() {
2959 flinger->onInitializeDisplays();
2960 return true;
2961 }
2962 };
2963 sp<MessageBase> msg = new MessageScreenInitialized(this);
2964 postMessageAsync(msg); // we may be called from main thread, use async message
2965}
2966
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002967void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2968 int mode) {
2969 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2970 this);
2971 int32_t type = hw->getDisplayType();
2972 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002973
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002974 if (mode == currentMode) {
2975 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002976 return;
2977 }
2978
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002979 hw->setPowerMode(mode);
2980 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2981 ALOGW("Trying to set power mode for virtual display");
2982 return;
2983 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002984
Irvelffc9efc2016-07-27 15:16:37 -07002985 if (mInterceptor.isEnabled()) {
2986 Mutex::Autolock _l(mStateLock);
2987 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2988 if (idx < 0) {
2989 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2990 return;
2991 }
2992 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2993 }
2994
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002995 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002996 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002998 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2999 // FIXME: eventthread only knows about the main display right now
3000 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003001 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003002 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003004 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003005 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003007
3008 struct sched_param param = {0};
3009 param.sched_priority = 1;
3010 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3011 ALOGW("Couldn't set SCHED_FIFO on display on");
3012 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003013 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003014 // Turn off the display
3015 struct sched_param param = {0};
3016 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3017 ALOGW("Couldn't set SCHED_OTHER on display off");
3018 }
3019
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003020 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003021 disableHardwareVsync(true); // also cancels any in-progress resync
3022
Mathias Agopiancde87a32012-09-13 14:09:01 -07003023 // FIXME: eventthread only knows about the main display right now
3024 mEventThread->onScreenReleased();
3025 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003026
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003027 getHwComposer().setPowerMode(type, mode);
3028 mVisibleRegionsDirty = true;
3029 // from this point on, SF will stop drawing on this display
3030 } else {
3031 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003032 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033}
3034
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003035void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3036 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003037 SurfaceFlinger& mFlinger;
3038 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003039 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003040 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041 MessageSetPowerMode(SurfaceFlinger& flinger,
3042 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3043 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003044 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003045 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003046 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003047 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003048 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003049 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003050 ALOGW("Attempt to set power mode = %d for virtual display",
3051 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003052 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003053 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003054 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003055 return true;
3056 }
3057 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003058 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003059 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003060}
3061
3062// ---------------------------------------------------------------------------
3063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3065{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003067
Mathias Agopianbd115332013-04-18 16:41:04 -07003068 IPCThreadState* ipc = IPCThreadState::self();
3069 const int pid = ipc->getCallingPid();
3070 const int uid = ipc->getCallingUid();
3071 if ((uid != AID_SHELL) &&
3072 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003073 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003074 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003076 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003077 // (this would indicate SF is stuck, but we want to be able to
3078 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003079 status_t err = mStateLock.timedLock(s2ns(1));
3080 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003081 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003082 result.appendFormat(
3083 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3084 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003085 }
3086
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003087 bool dumpAll = true;
3088 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003089 size_t numArgs = args.size();
3090 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003091 if ((index < numArgs) &&
3092 (args[index] == String16("--list"))) {
3093 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003094 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003095 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003096 }
3097
3098 if ((index < numArgs) &&
3099 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003100 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003101 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003102 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003103 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003104
3105 if ((index < numArgs) &&
3106 (args[index] == String16("--latency-clear"))) {
3107 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003108 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003109 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003110 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003111
3112 if ((index < numArgs) &&
3113 (args[index] == String16("--dispsync"))) {
3114 index++;
3115 mPrimaryDispSync.dump(result);
3116 dumpAll = false;
3117 }
Dan Stozab90cf072015-03-05 11:05:59 -08003118
3119 if ((index < numArgs) &&
3120 (args[index] == String16("--static-screen"))) {
3121 index++;
3122 dumpStaticScreenStats(result);
3123 dumpAll = false;
3124 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003125
3126 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003127 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003128 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003129 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003130 dumpAll = false;
3131 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003133
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003134 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003135 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003136 }
3137
Mathias Agopian9795c422009-08-26 16:36:26 -07003138 if (locked) {
3139 mStateLock.unlock();
3140 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 }
3142 write(fd, result.string(), result.size());
3143 return NO_ERROR;
3144}
3145
Dan Stozac7014012014-02-14 15:03:43 -08003146void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3147 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003148{
Robert Carr2047fae2016-11-28 14:09:09 -08003149 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003150 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003151 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003152}
3153
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003154void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003155 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003156{
3157 String8 name;
3158 if (index < args.size()) {
3159 name = String8(args[index]);
3160 index++;
3161 }
3162
Dan Stoza9e56aa02015-11-02 13:00:03 -08003163 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3164 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003165 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003166
3167 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003168 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003169 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003170 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003171 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003172 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003173 }
Robert Carr2047fae2016-11-28 14:09:09 -08003174 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003175 }
3176}
3177
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003178void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003179 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003180{
3181 String8 name;
3182 if (index < args.size()) {
3183 name = String8(args[index]);
3184 index++;
3185 }
3186
Robert Carr2047fae2016-11-28 14:09:09 -08003187 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003188 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003189 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003190 }
Robert Carr2047fae2016-11-28 14:09:09 -08003191 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003192
Svetoslavd85084b2014-03-20 10:28:31 -07003193 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003194}
3195
Jamie Gennis6547ff42013-07-16 20:12:42 -07003196// This should only be called from the main thread. Otherwise it would need
3197// the lock and should use mCurrentState rather than mDrawingState.
3198void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003199 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003200 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003201 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003202
3203 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3204}
3205
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003206void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003207{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003208 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003209#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003210 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003211#endif
3212#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003213 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003214#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003215 if (isLayerTripleBufferingDisabled())
3216 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003218}
3219
Dan Stozab90cf072015-03-05 11:05:59 -08003220void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3221{
3222 result.appendFormat("Static screen stats:\n");
3223 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3224 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3225 float percent = 100.0f *
3226 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3227 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3228 b + 1, bucketTimeSec, percent);
3229 }
3230 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3231 float percent = 100.0f *
3232 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3233 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3234 NUM_BUCKETS - 1, bucketTimeSec, percent);
3235}
3236
Dan Stozae77c7662016-05-13 11:37:28 -07003237void SurfaceFlinger::recordBufferingStats(const char* layerName,
3238 std::vector<OccupancyTracker::Segment>&& history) {
3239 Mutex::Autolock lock(mBufferingStatsMutex);
3240 auto& stats = mBufferingStats[layerName];
3241 for (const auto& segment : history) {
3242 if (!segment.usedThirdBuffer) {
3243 stats.twoBufferTime += segment.totalTime;
3244 }
3245 if (segment.occupancyAverage < 1.0f) {
3246 stats.doubleBufferedTime += segment.totalTime;
3247 } else if (segment.occupancyAverage < 2.0f) {
3248 stats.tripleBufferedTime += segment.totalTime;
3249 }
3250 ++stats.numSegments;
3251 stats.totalTime += segment.totalTime;
3252 }
3253}
3254
Brian Andersond6927fb2016-07-23 23:37:30 -07003255void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3256 result.appendFormat("Layer frame timestamps:\n");
3257
3258 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3259 const size_t count = currentLayers.size();
3260 for (size_t i=0 ; i<count ; i++) {
3261 currentLayers[i]->dumpFrameEvents(result);
3262 }
3263}
3264
Dan Stozae77c7662016-05-13 11:37:28 -07003265void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3266 result.append("Buffering stats:\n");
3267 result.append(" [Layer name] <Active time> <Two buffer> "
3268 "<Double buffered> <Triple buffered>\n");
3269 Mutex::Autolock lock(mBufferingStatsMutex);
3270 typedef std::tuple<std::string, float, float, float> BufferTuple;
3271 std::map<float, BufferTuple, std::greater<float>> sorted;
3272 for (const auto& statsPair : mBufferingStats) {
3273 const char* name = statsPair.first.c_str();
3274 const BufferingStats& stats = statsPair.second;
3275 if (stats.numSegments == 0) {
3276 continue;
3277 }
3278 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3279 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3280 stats.totalTime;
3281 float doubleBufferRatio = static_cast<float>(
3282 stats.doubleBufferedTime) / stats.totalTime;
3283 float tripleBufferRatio = static_cast<float>(
3284 stats.tripleBufferedTime) / stats.totalTime;
3285 sorted.insert({activeTime, {name, twoBufferRatio,
3286 doubleBufferRatio, tripleBufferRatio}});
3287 }
3288 for (const auto& sortedPair : sorted) {
3289 float activeTime = sortedPair.first;
3290 const BufferTuple& values = sortedPair.second;
3291 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3292 std::get<0>(values).c_str(), activeTime,
3293 std::get<1>(values), std::get<2>(values),
3294 std::get<3>(values));
3295 }
3296 result.append("\n");
3297}
3298
3299
Mathias Agopian74d211a2013-04-22 16:55:35 +02003300void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3301 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003302{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003303 bool colorize = false;
3304 if (index < args.size()
3305 && (args[index] == String16("--color"))) {
3306 colorize = true;
3307 index++;
3308 }
3309
3310 Colorizer colorizer(colorize);
3311
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003312 // figure out if we're stuck somewhere
3313 const nsecs_t now = systemTime();
3314 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3315 const nsecs_t inTransaction(mDebugInTransaction);
3316 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3317 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3318
3319 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003320 * Dump library configuration.
3321 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003322
3323 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003324 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003325 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003326 appendSfConfigString(result);
3327 appendUiConfigString(result);
3328 appendGuiConfigString(result);
3329 result.append("\n");
3330
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003331 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003332 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003333 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003334 result.append(SyncFeatures::getInstance().toString());
3335 result.append("\n");
3336
Dan Stoza9e56aa02015-11-02 13:00:03 -08003337 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3338
Andy McFadden41d67d72014-04-25 16:58:34 -07003339 colorizer.bold(result);
3340 result.append("DispSync configuration: ");
3341 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003342 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3343 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003344 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3345 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003346 result.append("\n");
3347
Dan Stozab90cf072015-03-05 11:05:59 -08003348 // Dump static screen stats
3349 result.append("\n");
3350 dumpStaticScreenStats(result);
3351 result.append("\n");
3352
Dan Stozae77c7662016-05-13 11:37:28 -07003353 dumpBufferingStats(result);
3354
Andy McFadden4803b742012-09-24 19:07:20 -07003355 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003356 * Dump the visible layer list
3357 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003358 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003359 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003361 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003363 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003364
3365 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003366 * Dump Display state
3367 */
3368
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003369 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003370 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003371 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003372 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3373 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003374 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003375 }
3376
3377 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003378 * Dump SurfaceFlinger global state
3379 */
3380
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003381 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003382 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003384
Mathias Agopian888c8222012-08-04 21:10:38 -07003385 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003386 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003387
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003388 colorizer.bold(result);
3389 result.appendFormat("EGL implementation : %s\n",
3390 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3391 colorizer.reset(result);
3392 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003393 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003394
Mathias Agopian875d8e12013-06-07 15:35:48 -07003395 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003396
Mathias Agopian42977342012-08-05 00:40:46 -07003397 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003398 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3399 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003400 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003401 " last eglSwapBuffers() time: %f us\n"
3402 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003403 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003404 " refresh-rate : %f fps\n"
3405 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003406 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003407 " gpu_to_cpu_unsupported : %d\n"
3408 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003409 mLastSwapBufferTime/1000.0,
3410 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003411 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003412 1e9 / activeConfig->getVsyncPeriod(),
3413 activeConfig->getDpiX(),
3414 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003415 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003416
Mathias Agopian74d211a2013-04-22 16:55:35 +02003417 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419
Mathias Agopian74d211a2013-04-22 16:55:35 +02003420 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003422
3423 /*
3424 * VSYNC state
3425 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003426 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003427 result.append("\n");
3428
3429 /*
3430 * HWC layer minidump
3431 */
3432 for (size_t d = 0; d < mDisplays.size(); d++) {
3433 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3434 int32_t hwcId = displayDevice->getHwcDisplayId();
3435 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3436 continue;
3437 }
3438
3439 result.appendFormat("Display %d HWC layers:\n", hwcId);
3440 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003441 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003442 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 });
Dan Stozae22aec72016-08-01 13:20:59 -07003444 result.append("\n");
3445 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003446
3447 /*
3448 * Dump HWComposer state
3449 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003450 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003451 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003452 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003453 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003454 result.appendFormat(" h/w composer %s\n",
3455 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003456 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457
3458 /*
3459 * Dump gralloc state
3460 */
3461 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3462 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003463}
3464
Mathias Agopian13127d82013-03-05 17:47:11 -08003465const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003466SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003467 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003468 wp<IBinder> dpy;
3469 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3470 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3471 dpy = mDisplays.keyAt(i);
3472 break;
3473 }
3474 }
3475 if (dpy == NULL) {
3476 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3477 // Just use the primary display so we have something to return
3478 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3479 }
3480 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003481}
3482
Keun young Park63f165f2012-08-31 10:53:36 -07003483bool SurfaceFlinger::startDdmConnection()
3484{
3485 void* libddmconnection_dso =
3486 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3487 if (!libddmconnection_dso) {
3488 return false;
3489 }
3490 void (*DdmConnection_start)(const char* name);
3491 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003492 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003493 if (!DdmConnection_start) {
3494 dlclose(libddmconnection_dso);
3495 return false;
3496 }
3497 (*DdmConnection_start)(getServiceName());
3498 return true;
3499}
3500
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003501status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502 switch (code) {
3503 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003504 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003506 case CLEAR_ANIMATION_FRAME_STATS:
3507 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003508 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003509 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510 {
3511 // codes that require permission check
3512 IPCThreadState* ipc = IPCThreadState::self();
3513 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003514 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003515 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003516 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003517 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003518 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003520 break;
3521 }
Robert Carr1db73f62016-12-21 12:58:51 -08003522 /*
3523 * Calling setTransactionState is safe, because you need to have been
3524 * granted a reference to Client* and Handle* to do anything with it.
3525 *
3526 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3527 */
3528 case SET_TRANSACTION_STATE:
3529 case CREATE_SCOPED_CONNECTION:
3530 {
3531 return OK;
3532 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003533 case CAPTURE_SCREEN:
3534 {
3535 // codes that require permission check
3536 IPCThreadState* ipc = IPCThreadState::self();
3537 const int pid = ipc->getCallingPid();
3538 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003539 if ((uid != AID_GRAPHICS) &&
3540 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003541 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003542 return PERMISSION_DENIED;
3543 }
3544 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545 }
3546 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003547 return OK;
3548}
3549
3550status_t SurfaceFlinger::onTransact(
3551 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3552{
3553 status_t credentialCheck = CheckTransactCodeCredentials(code);
3554 if (credentialCheck != OK) {
3555 return credentialCheck;
3556 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003557
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003558 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3559 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003560 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003561 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003562 IPCThreadState* ipc = IPCThreadState::self();
3563 const int pid = ipc->getCallingPid();
3564 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003565 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003566 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 return PERMISSION_DENIED;
3568 }
3569 int n;
3570 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003571 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003572 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 return NO_ERROR;
3574 case 1002: // SHOW_UPDATES
3575 n = data.readInt32();
3576 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003577 invalidateHwcGeometry();
3578 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003581 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003582 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003584 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585 setTransactionFlags(
3586 eTransactionNeeded|
3587 eDisplayTransactionNeeded|
3588 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003589 return NO_ERROR;
3590 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003591 case 1006:{ // send empty update
3592 signalRefresh();
3593 return NO_ERROR;
3594 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003595 case 1008: // toggle use of hw composer
3596 n = data.readInt32();
3597 mDebugDisableHWC = n ? 1 : 0;
3598 invalidateHwcGeometry();
3599 repaintEverything();
3600 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003601 case 1009: // toggle use of transform hint
3602 n = data.readInt32();
3603 mDebugDisableTransformHint = n ? 1 : 0;
3604 invalidateHwcGeometry();
3605 repaintEverything();
3606 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003608 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 reply->writeInt32(0);
3610 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003611 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003612 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 return NO_ERROR;
3614 case 1013: {
3615 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003616 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3617 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003618 return NO_ERROR;
3619 }
3620 case 1014: {
3621 // daltonize
3622 n = data.readInt32();
3623 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003624 case 1:
3625 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3626 break;
3627 case 2:
3628 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3629 break;
3630 case 3:
3631 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3632 break;
3633 default:
3634 mDaltonizer.setType(ColorBlindnessType::None);
3635 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003636 }
3637 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003638 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003639 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003640 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003641 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003642 invalidateHwcGeometry();
3643 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003644 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003646 case 1015: {
3647 // apply a color matrix
3648 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003649 if (n) {
3650 // color matrix is sent as mat3 matrix followed by vec3
3651 // offset, then packed into a mat4 where the last row is
3652 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003653 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003654 for (size_t j = 0; j < 4; j++) {
3655 mColorMatrix[i][j] = data.readFloat();
3656 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003657 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003658 } else {
3659 mColorMatrix = mat4();
3660 }
3661 invalidateHwcGeometry();
3662 repaintEverything();
3663 return NO_ERROR;
3664 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003665 // This is an experimental interface
3666 // Needs to be shifted to proper binder interface when we productize
3667 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003668 n = data.readInt32();
3669 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003670 return NO_ERROR;
3671 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003672 case 1017: {
3673 n = data.readInt32();
3674 mForceFullDamage = static_cast<bool>(n);
3675 return NO_ERROR;
3676 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003677 case 1018: { // Modify Choreographer's phase offset
3678 n = data.readInt32();
3679 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3680 return NO_ERROR;
3681 }
3682 case 1019: { // Modify SurfaceFlinger's phase offset
3683 n = data.readInt32();
3684 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3685 return NO_ERROR;
3686 }
Irvel468051e2016-06-13 16:44:44 -07003687 case 1020: { // Layer updates interceptor
3688 n = data.readInt32();
3689 if (n) {
3690 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003691 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003692 }
3693 else{
3694 ALOGV("Interceptor disabled");
3695 mInterceptor.disable();
3696 }
3697 return NO_ERROR;
3698 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003699 case 1021: { // Disable HWC virtual displays
3700 n = data.readInt32();
3701 mUseHwcVirtualDisplays = !n;
3702 return NO_ERROR;
3703 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 }
3705 }
3706 return err;
3707}
3708
Mathias Agopian53331da2011-08-22 21:44:41 -07003709void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003710 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003711 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003712}
3713
Mathias Agopian59119e62010-10-11 12:37:43 -07003714// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003715// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003716// ---------------------------------------------------------------------------
3717
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003718/* The code below is here to handle b/8734824
3719 *
3720 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003721 * from the surfaceflinger thread to the calling binder thread, where they
3722 * are executed. This allows the calling thread in the calling process to be
3723 * reused and not depend on having "enough" binder threads to handle the
3724 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003725 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003726class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003727 /* Parts of GraphicProducerWrapper are run on two different threads,
3728 * communicating by sending messages via Looper but also by shared member
3729 * data. Coherence maintenance is subtle and in places implicit (ugh).
3730 *
3731 * Don't rely on Looper's sendMessage/handleMessage providing
3732 * release/acquire semantics for any data not actually in the Message.
3733 * Data going from surfaceflinger to binder threads needs to be
3734 * synchronized explicitly.
3735 *
3736 * Barrier open/wait do provide release/acquire semantics. This provides
3737 * implicit synchronization for data coming back from binder to
3738 * surfaceflinger threads.
3739 */
3740
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003741 sp<IGraphicBufferProducer> impl;
3742 sp<Looper> looper;
3743 status_t result;
3744 bool exitPending;
3745 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003746 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003747 uint32_t code;
3748 Parcel const* data;
3749 Parcel* reply;
3750
3751 enum {
3752 MSG_API_CALL,
3753 MSG_EXIT
3754 };
3755
3756 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003757 * Called on surfaceflinger thread. This is called by our "fake"
3758 * BpGraphicBufferProducer. We package the data and reply Parcel and
3759 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003760 */
3761 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003762 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003763 this->code = code;
3764 this->data = &data;
3765 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003766 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003767 // if we've exited, we run the message synchronously right here.
3768 // note (JH): as far as I can tell from looking at the code, this
3769 // never actually happens. if it does, i'm not sure if it happens
3770 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003771 handleMessage(Message(MSG_API_CALL));
3772 } else {
3773 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003774 // Prevent stores to this->{code, data, reply} from being
3775 // reordered later than the construction of Message.
3776 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003777 looper->sendMessage(this, Message(MSG_API_CALL));
3778 barrier.wait();
3779 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003780 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003781 }
3782
3783 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003784 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003785 * call the real BpGraphicBufferProducer.
3786 */
3787 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003788 int what = message.what;
3789 // Prevent reads below from happening before the read from Message
3790 atomic_thread_fence(memory_order_acquire);
3791 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003792 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003793 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003794 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 exitRequested = true;
3796 }
3797 }
3798
3799public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003800 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003801 : impl(impl),
3802 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003803 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003804 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003805 exitRequested(false),
3806 code(0),
3807 data(NULL),
3808 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003809 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003810
Jesse Hallb154c422014-07-13 12:47:02 -07003811 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812 status_t waitForResponse() {
3813 do {
3814 looper->pollOnce(-1);
3815 } while (!exitRequested);
3816 return result;
3817 }
3818
Jesse Hallb154c422014-07-13 12:47:02 -07003819 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003820 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003821 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003823 // Ensure this->result is visible to the binder thread before it
3824 // handles the message.
3825 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003826 looper->sendMessage(this, Message(MSG_EXIT));
3827 }
3828};
3829
3830
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003831status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3832 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003833 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003834 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003835 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003836
3837 if (CC_UNLIKELY(display == 0))
3838 return BAD_VALUE;
3839
3840 if (CC_UNLIKELY(producer == 0))
3841 return BAD_VALUE;
3842
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003843 // if we have secure windows on this display, never allow the screen capture
3844 // unless the producer interface is local (i.e.: we can take a screenshot for
3845 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003846 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003847
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003848 // Convert to surfaceflinger's internal rotation type.
3849 Transform::orientation_flags rotationFlags;
3850 switch (rotation) {
3851 case ISurfaceComposer::eRotateNone:
3852 rotationFlags = Transform::ROT_0;
3853 break;
3854 case ISurfaceComposer::eRotate90:
3855 rotationFlags = Transform::ROT_90;
3856 break;
3857 case ISurfaceComposer::eRotate180:
3858 rotationFlags = Transform::ROT_180;
3859 break;
3860 case ISurfaceComposer::eRotate270:
3861 rotationFlags = Transform::ROT_270;
3862 break;
3863 default:
3864 rotationFlags = Transform::ROT_0;
3865 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3866 break;
3867 }
3868
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003869 class MessageCaptureScreen : public MessageBase {
3870 SurfaceFlinger* flinger;
3871 sp<IBinder> display;
3872 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003873 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003874 uint32_t reqWidth, reqHeight;
3875 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003876 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003877 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003878 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003879 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003880 public:
3881 MessageCaptureScreen(SurfaceFlinger* flinger,
3882 const sp<IBinder>& display,
3883 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003884 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003885 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003886 bool useIdentityTransform,
3887 Transform::orientation_flags rotation,
3888 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003889 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003890 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003891 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003892 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003893 rotation(rotation), result(PERMISSION_DENIED),
3894 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003895 {
3896 }
3897 status_t getResult() const {
3898 return result;
3899 }
3900 virtual bool handler() {
3901 Mutex::Autolock _l(flinger->mStateLock);
3902 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003903 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003904 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003905 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003906 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003907 return true;
3908 }
3909 };
3910
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003911 // this creates a "fake" BBinder which will serve as a "fake" remote
3912 // binder to receive the marshaled calls and forward them to the
3913 // real remote (a BpGraphicBufferProducer)
3914 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3915
3916 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3917 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003918 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003919 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003920 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003921 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003922
3923 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003924 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003925 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 }
3927 return res;
3928}
3929
Mathias Agopian180f10d2013-04-10 22:55:41 -07003930
3931void SurfaceFlinger::renderScreenImplLocked(
3932 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003933 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003934 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003935 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003936{
3937 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003938 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003939
3940 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003941 const int32_t hw_w = hw->getWidth();
3942 const int32_t hw_h = hw->getHeight();
3943 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003944 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003945
Dan Stozac1879002014-05-22 15:59:05 -07003946 // if a default or invalid sourceCrop is passed in, set reasonable values
3947 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3948 !sourceCrop.isValid()) {
3949 sourceCrop.setLeftTop(Point(0, 0));
3950 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3951 }
3952
3953 // ensure that sourceCrop is inside screen
3954 if (sourceCrop.left < 0) {
3955 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3956 }
Dan Stozabe31f442014-06-11 11:20:54 -07003957 if (sourceCrop.right > hw_w) {
3958 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003959 }
3960 if (sourceCrop.top < 0) {
3961 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3962 }
Dan Stozabe31f442014-06-11 11:20:54 -07003963 if (sourceCrop.bottom > hw_h) {
3964 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003965 }
3966
Mathias Agopian180f10d2013-04-10 22:55:41 -07003967 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003968 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003969
3970 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003971 engine.setViewportAndProjection(
3972 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003973 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003974
3975 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003976 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003977
Robert Carr1f0a16a2016-10-24 16:27:39 -07003978 // We loop through the first level of layers without traversing,
3979 // as we need to interpret min/max layer Z in the top level Z space.
3980 for (const auto& layer : mDrawingState.layersSortedByZ) {
3981 if (layer->getLayerStack() != hw->getLayerStack()) {
3982 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003983 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003984 const Layer::State& state(layer->getDrawingState());
3985 if (state.z < minLayerZ || state.z > maxLayerZ) {
3986 continue;
3987 }
3988 layer->traverseInZOrder([&](Layer* layer) {
3989 if (!layer->isVisible()) {
3990 return;
3991 }
3992 if (filtering) layer->setFiltering(true);
3993 layer->draw(hw, useIdentityTransform);
3994 if (filtering) layer->setFiltering(false);
3995 });
3996 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003997
Mathias Agopian931bda12013-08-28 18:11:46 -07003998 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003999}
4000
4001
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004002status_t SurfaceFlinger::captureScreenImplLocked(
4003 const sp<const DisplayDevice>& hw,
4004 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004005 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004006 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004007 bool useIdentityTransform, Transform::orientation_flags rotation,
4008 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004009{
4010 ATRACE_CALL();
4011
Mathias Agopian180f10d2013-04-10 22:55:41 -07004012 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004013 uint32_t hw_w = hw->getWidth();
4014 uint32_t hw_h = hw->getHeight();
4015
4016 if (rotation & Transform::ROT_90) {
4017 std::swap(hw_w, hw_h);
4018 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004019
Mathias Agopian180f10d2013-04-10 22:55:41 -07004020 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4021 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4022 reqWidth, reqHeight, hw_w, hw_h);
4023 return BAD_VALUE;
4024 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004025
Mathias Agopian180f10d2013-04-10 22:55:41 -07004026 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4027 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4028
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004029 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004030 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004031 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004032 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4033 (state.z < minLayerZ || state.z > maxLayerZ)) {
4034 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004035 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004036 layer->traverseInZOrder([&](Layer *layer) {
4037 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4038 layer->isSecure());
4039 });
4040 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004041
4042 if (!isLocalScreenshot && secureLayerIsVisible) {
4043 ALOGW("FB is protected: PERMISSION_DENIED");
4044 return PERMISSION_DENIED;
4045 }
4046
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004047 // create a surface (because we're a producer, and we need to
4048 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004049 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004050
4051 // Put the screenshot Surface into async mode so that
4052 // Layer::headFenceHasSignaled will always return true and we'll latch the
4053 // first buffer regardless of whether or not its acquire fence has
4054 // signaled. This is needed to avoid a race condition in the rotation
4055 // animation. See b/30209608
4056 sur->setAsyncMode(true);
4057
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004058 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004059
Michael Lentine5a16a622015-05-21 13:48:24 -07004060 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4061 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004062 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4063 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004064
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004065 int err = 0;
4066 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004067 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004068 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4069 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004070
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004071 if (err == NO_ERROR) {
4072 ANativeWindowBuffer* buffer;
4073 /* TODO: Once we have the sync framework everywhere this can use
4074 * server-side waits on the fence that dequeueBuffer returns.
4075 */
4076 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4077 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004078 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004079 // create an EGLImage from the buffer so we can later
4080 // turn it into a texture
4081 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4082 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4083 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004084 // this binds the given EGLImage as a framebuffer for the
4085 // duration of this scope.
4086 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4087 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004088 // this will in fact render into our dequeued buffer
4089 // via an FBO, which means we didn't have to create
4090 // an EGLSurface and therefore we're not
4091 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004092 renderScreenImplLocked(
4093 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4094 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004095
Riley Andrews86639902014-08-15 12:27:24 -07004096 // Attempt to create a sync khr object that can produce a sync point. If that
4097 // isn't available, create a non-dupable sync object in the fallback path and
4098 // wait on it directly.
4099 EGLSyncKHR sync;
4100 if (!DEBUG_SCREENSHOTS) {
4101 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004102 // native fence fd will not be populated until flush() is done.
4103 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004104 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004105 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004106 }
Riley Andrews86639902014-08-15 12:27:24 -07004107 if (sync != EGL_NO_SYNC_KHR) {
4108 // get the sync fd
4109 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4110 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4111 ALOGW("captureScreen: failed to dup sync khr object");
4112 syncFd = -1;
4113 }
4114 eglDestroySyncKHR(mEGLDisplay, sync);
4115 } else {
4116 // fallback path
4117 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4118 if (sync != EGL_NO_SYNC_KHR) {
4119 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4120 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4121 EGLint eglErr = eglGetError();
4122 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4123 ALOGW("captureScreen: fence wait timed out");
4124 } else {
4125 ALOGW_IF(eglErr != EGL_SUCCESS,
4126 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4127 }
4128 eglDestroySyncKHR(mEGLDisplay, sync);
4129 } else {
4130 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4131 }
4132 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004133 if (DEBUG_SCREENSHOTS) {
4134 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4135 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4136 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4137 hw, minLayerZ, maxLayerZ);
4138 delete [] pixels;
4139 }
4140
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004141 } else {
4142 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4143 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004144 window->cancelBuffer(window, buffer, syncFd);
4145 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004146 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004147 // destroy our image
4148 eglDestroyImageKHR(mEGLDisplay, image);
4149 } else {
4150 result = BAD_VALUE;
4151 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004152 if (buffer) {
4153 // queueBuffer takes ownership of syncFd
4154 result = window->queueBuffer(window, buffer, syncFd);
4155 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004156 }
4157 } else {
4158 result = BAD_VALUE;
4159 }
4160 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4161 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004162
Mathias Agopian74c40c02010-09-29 13:02:36 -07004163 return result;
4164}
4165
Mathias Agopiand5556842013-09-19 17:08:37 -07004166void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004167 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004168 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004169 for (size_t y=0 ; y<h ; y++) {
4170 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4171 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004172 if (p[x] != 0xFF000000) return;
4173 }
4174 }
4175 ALOGE("*** we just took a black screenshot ***\n"
4176 "requested minz=%d, maxz=%d, layerStack=%d",
4177 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004178
Robert Carr2047fae2016-11-28 14:09:09 -08004179 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004180 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004181 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004182 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4183 state.z <= maxLayerZ) {
4184 layer->traverseInZOrder([&](Layer* layer) {
4185 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4186 layer->isVisible() ? '+' : '-',
4187 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004188 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004189 i++;
4190 });
4191 }
4192 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004193 }
4194}
4195
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004196// ---------------------------------------------------------------------------
4197
Robert Carr2047fae2016-11-28 14:09:09 -08004198void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4199 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004200}
4201
Robert Carr2047fae2016-11-28 14:09:09 -08004202void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4203 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004204}
4205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004207
4208
4209#if defined(__gl_h_)
4210#error "don't include gl/gl.h in this file"
4211#endif
4212
4213#if defined(__gl2_h_)
4214#error "don't include gl2/gl2.h in this file"
4215#endif