blob: e1dff3cffdc717c94ea1816e89afb166a0cd1059 [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) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001268 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001269 signalLayerUpdate();
1270 break;
1271 }
1272
Dan Stoza6b9454d2014-11-07 16:00:59 -08001273 bool refreshNeeded = handleMessageTransaction();
1274 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001275 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001276 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001277 // Signal a refresh if a transaction modified the window state,
1278 // a new buffer was latched, or if HWC has requested a full
1279 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001280 signalRefresh();
1281 }
1282 break;
1283 }
1284 case MessageQueue::REFRESH: {
1285 handleMessageRefresh();
1286 break;
1287 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 }
1289}
1290
Dan Stoza6b9454d2014-11-07 16:00:59 -08001291bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001292 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001293 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001294 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001295 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001296 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001297 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001298}
1299
Dan Stoza6b9454d2014-11-07 16:00:59 -08001300bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001301 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001302 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001303}
1304
1305void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001306 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001307
Pablo Ceballos40845df2016-01-25 17:41:15 -08001308 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001309
Brian Andersond6927fb2016-07-23 23:37:30 -07001310 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001311 rebuildLayerStacks();
1312 setUpHWComposer();
1313 doDebugFlashRegions();
1314 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001315 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001316
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001317 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001318
1319 mHadClientComposition = false;
1320 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1321 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1322 mHadClientComposition = mHadClientComposition ||
1323 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1324 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001325
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001327}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001328
Mathias Agopiancd60f992012-08-16 16:28:27 -07001329void SurfaceFlinger::doDebugFlashRegions()
1330{
1331 // is debugging enabled
1332 if (CC_LIKELY(!mDebugRegion))
1333 return;
1334
1335 const bool repaintEverything = mRepaintEverything;
1336 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1337 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001338 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001339 // transform the dirty region into this screen's coordinate space
1340 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1341 if (!dirtyRegion.isEmpty()) {
1342 // redraw the whole screen
1343 doComposeSurfaces(hw, Region(hw->bounds()));
1344
1345 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001346 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001347 RenderEngine& engine(getRenderEngine());
1348 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1349
Mathias Agopianda27af92012-09-13 18:17:13 -07001350 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001351 }
1352 }
1353 }
1354
1355 postFramebuffer();
1356
1357 if (mDebugRegion > 1) {
1358 usleep(mDebugRegion * 1000);
1359 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001360
Dan Stoza9e56aa02015-11-02 13:00:03 -08001361 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001362 auto& displayDevice = mDisplays[displayId];
1363 if (!displayDevice->isDisplayOn()) {
1364 continue;
1365 }
1366
1367 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1369 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001370 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001371}
1372
Brian Andersond6927fb2016-07-23 23:37:30 -07001373void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001374{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 ATRACE_CALL();
1376 ALOGV("preComposition");
1377
Mathias Agopiancd60f992012-08-16 16:28:27 -07001378 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001379 mDrawingState.traverseInZOrder([&](Layer* layer) {
1380 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001381 needExtraInvalidate = true;
1382 }
Robert Carr2047fae2016-11-28 14:09:09 -08001383 });
1384
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385 if (needExtraInvalidate) {
1386 signalLayerUpdate();
1387 }
1388}
1389
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001390void SurfaceFlinger::updateCompositorTiming(
1391 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1392 std::shared_ptr<FenceTime>& presentFenceTime) {
1393 // Update queue of past composite+present times and determine the
1394 // most recently known composite to present latency.
1395 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1396 nsecs_t compositeToPresentLatency = -1;
1397 while (!mCompositePresentTimes.empty()) {
1398 CompositePresentTime& cpt = mCompositePresentTimes.front();
1399 // Cached values should have been updated before calling this method,
1400 // which helps avoid duplicate syscalls.
1401 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1402 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1403 break;
1404 }
1405 compositeToPresentLatency = displayTime - cpt.composite;
1406 mCompositePresentTimes.pop();
1407 }
1408
1409 // Don't let mCompositePresentTimes grow unbounded, just in case.
1410 while (mCompositePresentTimes.size() > 16) {
1411 mCompositePresentTimes.pop();
1412 }
1413
1414 // Integer division and modulo round toward 0 not -inf, so we need to
1415 // treat negative and positive offsets differently.
1416 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1417 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1418 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1419
1420 // Snap the latency to a value that removes scheduling jitter from the
1421 // composition and present times, which often have >1ms of jitter.
1422 // Reducing jitter is important if an app attempts to extrapolate
1423 // something (such as user input) to an accurate diasplay time.
1424 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1425 // with (presentLatency % interval).
1426 nsecs_t snappedCompositeToPresentLatency = -1;
1427 if (compositeToPresentLatency >= 0) {
1428 nsecs_t bias = vsyncInterval / 2;
1429 int64_t extraVsyncs =
1430 (compositeToPresentLatency - idealLatency + bias) /
1431 vsyncInterval;
1432 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1433 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1434 }
1435
1436 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1437 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1438 mCompositorTiming.interval = vsyncInterval;
1439 if (snappedCompositeToPresentLatency >= 0) {
1440 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1441 }
1442}
1443
1444void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001446 ATRACE_CALL();
1447 ALOGV("postComposition");
1448
Brian Anderson3546a3f2016-07-14 11:51:14 -07001449 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001450 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001451 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001452 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001453 }
1454
Brian Andersond6927fb2016-07-23 23:37:30 -07001455 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001456
1457 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1458 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1459 glCompositionDoneFenceTime =
1460 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1461 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1462 } else {
1463 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1464 }
1465 mGlCompositionDoneTimeline.updateSignalTimes();
1466
1467 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1468 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1469 mDisplayTimeline.push(displayFenceTime);
1470 mDisplayTimeline.updateSignalTimes();
1471
1472 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1473 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1474 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1475 presentFenceTime = &displayFenceTime;
1476 } else {
1477 retireFenceTime = &displayFenceTime;
1478 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479
1480 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1481 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1482
1483 // We use the refreshStartTime which might be sampled a little later than
1484 // when we started doing work for this frame, but that should be okay
1485 // since updateCompositorTiming has snapping logic.
1486 updateCompositorTiming(
1487 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1488
Robert Carr2047fae2016-11-28 14:09:09 -08001489 mDrawingState.traverseInZOrder([&](Layer* layer) {
1490 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001491 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001492 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001493 recordBufferingStats(layer->getName().string(),
1494 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001495 }
Robert Carr2047fae2016-11-28 14:09:09 -08001496 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001497
Brian Anderson3d4039d2016-09-23 16:31:30 -07001498 if (displayFence->isValid()) {
1499 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001500 enableHardwareVsync();
1501 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001502 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001503 }
1504 }
1505
Andy McFadden5167ec62014-05-22 13:08:43 -07001506 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001507 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001508 enableHardwareVsync();
1509 }
1510 }
1511
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001512 if (mAnimCompositionPending) {
1513 mAnimCompositionPending = false;
1514
Brian Anderson3d4039d2016-09-23 16:31:30 -07001515 if (displayFenceTime->isValid()) {
1516 mAnimFrameTracker.setActualPresentFence(
1517 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001518 } else {
1519 // The HWC doesn't support present fences, so use the refresh
1520 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001521 nsecs_t presentTime =
1522 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001523 mAnimFrameTracker.setActualPresentTime(presentTime);
1524 }
1525 mAnimFrameTracker.advanceFrame();
1526 }
Dan Stozab90cf072015-03-05 11:05:59 -08001527
1528 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1529 return;
1530 }
1531
1532 nsecs_t currentTime = systemTime();
1533 if (mHasPoweredOff) {
1534 mHasPoweredOff = false;
1535 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001536 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001538 if (numPeriods < NUM_BUCKETS - 1) {
1539 mFrameBuckets[numPeriods] += elapsedTime;
1540 } else {
1541 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1542 }
1543 mTotalTime += elapsedTime;
1544 }
1545 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546}
1547
1548void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001549 ATRACE_CALL();
1550 ALOGV("rebuildLayerStacks");
1551
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001553 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001555 mVisibleRegionsDirty = false;
1556 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001557
Mathias Agopian92a979a2012-08-02 18:32:23 -07001558 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001559 Region opaqueRegion;
1560 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001561 Vector<sp<Layer>> layersSortedByZ;
1562 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1563 const Transform& tr(displayDevice->getTransform());
1564 const Rect bounds(displayDevice->getBounds());
1565 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001566 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 displayDevice->getLayerStack(), dirtyRegion,
1568 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001569
Robert Carr2047fae2016-11-28 14:09:09 -08001570 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001571 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001572 Region drawRegion(tr.transform(
1573 layer->visibleNonTransparentRegion));
1574 drawRegion.andSelf(bounds);
1575 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001576 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 } else {
1578 // Clear out the HWC layer if this layer was
1579 // previously visible, but no longer is
1580 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1581 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001582 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001583 }
Robert Carr2047fae2016-11-28 14:09:09 -08001584 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001585 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1587 displayDevice->undefinedRegion.set(bounds);
1588 displayDevice->undefinedRegion.subtractSelf(
1589 tr.transform(opaqueRegion));
1590 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001591 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001592 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001594
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001596 ATRACE_CALL();
1597 ALOGV("setUpHWComposer");
1598
Jesse Hall028dc8f2013-08-20 16:35:32 -07001599 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001600 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1601 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1602 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1603
1604 // If nothing has changed (!dirty), don't recompose.
1605 // If something changed, but we don't currently have any visible layers,
1606 // and didn't when we last did a composition, then skip it this time.
1607 // The second rule does two things:
1608 // - When all layers are removed from a display, we'll emit one black
1609 // frame, then nothing more until we get new layers.
1610 // - When a display is created with a private layer stack, we won't
1611 // emit any black frames until a layer is added to the layer stack.
1612 bool mustRecompose = dirty && !(empty && wasEmpty);
1613
1614 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1615 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1616 mustRecompose ? "doing" : "skipping",
1617 dirty ? "+" : "-",
1618 empty ? "+" : "-",
1619 wasEmpty ? "+" : "-");
1620
Dan Stoza71433162014-02-04 16:22:36 -08001621 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001622
1623 if (mustRecompose) {
1624 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1625 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001626 }
1627
Dan Stoza9e56aa02015-11-02 13:00:03 -08001628 // build the h/w work list
1629 if (CC_UNLIKELY(mGeometryInvalid)) {
1630 mGeometryInvalid = false;
1631 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1632 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1633 const auto hwcId = displayDevice->getHwcDisplayId();
1634 if (hwcId >= 0) {
1635 const Vector<sp<Layer>>& currentLayers(
1636 displayDevice->getVisibleLayersSortedByZ());
1637 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001638 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001639 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 if (!layer->hasHwcLayer(hwcId)) {
1641 auto hwcLayer = mHwc->createLayer(hwcId);
1642 if (hwcLayer) {
1643 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1644 } else {
1645 layer->forceClientComposition(hwcId);
1646 foundLayerWithoutHwc = true;
1647 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001648 }
1649 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001650
Robert Carrae060832016-11-28 10:51:00 -08001651 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001652 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001654 }
1655 }
1656 }
1657 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 }
Riley Andrews03414a12014-07-01 14:22:59 -07001659
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001660
1661 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1662
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 // Set the per-frame data
1664 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1665 auto& displayDevice = mDisplays[displayId];
1666 const auto hwcId = displayDevice->getHwcDisplayId();
1667 if (hwcId < 0) {
1668 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001669 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001670 if (colorMatrix != mPreviousColorMatrix) {
1671 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1672 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1673 "display %zd: %d", displayId, result);
1674 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001675 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1676 layer->setPerFrameData(displayDevice);
1677 }
1678 }
1679
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001680 mPreviousColorMatrix = colorMatrix;
1681
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001683 auto& displayDevice = mDisplays[displayId];
1684 if (!displayDevice->isDisplayOn()) {
1685 continue;
1686 }
1687
1688 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001689 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1690 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001691 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001693
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694void SurfaceFlinger::doComposition() {
1695 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 ALOGV("doComposition");
1697
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001698 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001699 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001700 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001701 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702 // transform the dirty region into this screen's coordinate space
1703 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001704
1705 // repaint the framebuffer (if needed)
1706 doDisplayComposition(hw, dirtyRegion);
1707
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708 hw->dirtyRegion.clear();
1709 hw->flip(hw->swapRegion);
1710 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001711 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001713 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714}
1715
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001716void SurfaceFlinger::postFramebuffer()
1717{
Mathias Agopian841cde52012-03-01 15:44:37 -08001718 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001719 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001720
Mathias Agopiana44b0412011-10-16 18:46:35 -07001721 const nsecs_t now = systemTime();
1722 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001723
Dan Stoza9e56aa02015-11-02 13:00:03 -08001724 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1725 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001726 if (!displayDevice->isDisplayOn()) {
1727 continue;
1728 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 const auto hwcId = displayDevice->getHwcDisplayId();
1730 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001731 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001732 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001733 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001734 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1736 sp<Fence> releaseFence = Fence::NO_FENCE;
1737 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1738 releaseFence = displayDevice->getClientTargetAcquireFence();
1739 } else {
1740 auto hwcLayer = layer->getHwcLayer(hwcId);
1741 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 layer->onLayerDisplayed(releaseFence);
1744 }
1745 if (hwcId >= 0) {
1746 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001747 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001748 }
1749
Mathias Agopiana44b0412011-10-16 18:46:35 -07001750 mLastSwapBufferTime = systemTime() - now;
1751 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001752
1753 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1754 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1755 logFrameStats();
1756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001757}
1758
Mathias Agopian87baae12012-07-31 12:38:26 -07001759void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001760{
Mathias Agopian841cde52012-03-01 15:44:37 -08001761 ATRACE_CALL();
1762
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001763 // here we keep a copy of the drawing state (that is the state that's
1764 // going to be overwritten by handleTransactionLocked()) outside of
1765 // mStateLock so that the side-effects of the State assignment
1766 // don't happen with mStateLock held (which can cause deadlocks).
1767 State drawingState(mDrawingState);
1768
Mathias Agopianca4d3602011-05-19 15:38:14 -07001769 Mutex::Autolock _l(mStateLock);
1770 const nsecs_t now = systemTime();
1771 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001772
Mathias Agopianca4d3602011-05-19 15:38:14 -07001773 // Here we're guaranteed that some transaction flags are set
1774 // so we can call handleTransactionLocked() unconditionally.
1775 // We call getTransactionFlags(), which will also clear the flags,
1776 // with mStateLock held to guarantee that mCurrentState won't change
1777 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001778
Mathias Agopiane57f2922012-08-09 16:29:12 -07001779 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001780 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001781
Mathias Agopianca4d3602011-05-19 15:38:14 -07001782 mLastTransactionTime = systemTime() - now;
1783 mDebugInTransaction = 0;
1784 invalidateHwcGeometry();
1785 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001786}
1787
Mathias Agopian87baae12012-07-31 12:38:26 -07001788void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001789{
Dan Stoza7dde5992015-05-22 09:51:44 -07001790 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001791 mCurrentState.traverseInZOrder([](Layer* layer) {
1792 layer->notifyAvailableFrames();
1793 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 /*
1796 * Traversal of the children
1797 * (perform the transaction for each of them if needed)
1798 */
1799
Mathias Agopian3559b072012-08-15 13:46:03 -07001800 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001801 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001803 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804
1805 const uint32_t flags = layer->doTransaction(0);
1806 if (flags & Layer::eVisibleRegion)
1807 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001808 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001809 }
1810
1811 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001812 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813 */
1814
Mathias Agopiane57f2922012-08-09 16:29:12 -07001815 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001816 // here we take advantage of Vector's copy-on-write semantics to
1817 // improve performance by skipping the transaction entirely when
1818 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001819 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1820 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001821 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001823 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001824 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001825
1826 // find the displays that were removed
1827 // (ie: in drawing state but not in current state)
1828 // also handle displays that changed
1829 // (ie: displays that are in both lists)
1830 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001831 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1832 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001833 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001834 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001835 // Call makeCurrent() on the primary display so we can
1836 // be sure that nothing associated with this display
1837 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001838 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001839 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001840 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1841 if (hw != NULL)
1842 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001843 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001844 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001845 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001846 } else {
1847 ALOGW("trying to remove the main display");
1848 }
1849 } else {
1850 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001851 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001852 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001853 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1854 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001855 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001856 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001857 // recreating the DisplayDevice, so we just remove it
1858 // from the drawing state, so that it get re-added
1859 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001860 sp<DisplayDevice> hw(getDisplayDevice(display));
1861 if (hw != NULL)
1862 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001863 mDisplays.removeItem(display);
1864 mDrawingState.displays.removeItemsAt(i);
1865 dc--; i--;
1866 // at this point we must loop to the next item
1867 continue;
1868 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001869
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001870 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001871 if (disp != NULL) {
1872 if (state.layerStack != draw[i].layerStack) {
1873 disp->setLayerStack(state.layerStack);
1874 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001875 if ((state.orientation != draw[i].orientation)
1876 || (state.viewport != draw[i].viewport)
1877 || (state.frame != draw[i].frame))
1878 {
1879 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001880 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001881 }
Michael Lentine47e45402014-07-18 15:34:25 -07001882 if (state.width != draw[i].width || state.height != draw[i].height) {
1883 disp->setDisplaySize(state.width, state.height);
1884 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001885 }
1886 }
1887 }
1888
1889 // find displays that were added
1890 // (ie: in current state but not in drawing state)
1891 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001892 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001893 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001894
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001895 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001896 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001897 sp<IGraphicBufferProducer> bqProducer;
1898 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001899 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1900 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001901
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001903 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001904 // Virtual displays without a surface are dormant:
1905 // they have external state (layer stack, projection,
1906 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001907 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001908
Dan Stoza8cf150a2016-08-02 10:27:31 -07001909 if (mUseHwcVirtualDisplays) {
1910 int width = 0;
1911 int status = state.surface->query(
1912 NATIVE_WINDOW_WIDTH, &width);
1913 ALOGE_IF(status != NO_ERROR,
1914 "Unable to query width (%d)", status);
1915 int height = 0;
1916 status = state.surface->query(
1917 NATIVE_WINDOW_HEIGHT, &height);
1918 ALOGE_IF(status != NO_ERROR,
1919 "Unable to query height (%d)", status);
1920 int intFormat = 0;
1921 status = state.surface->query(
1922 NATIVE_WINDOW_FORMAT, &intFormat);
1923 ALOGE_IF(status != NO_ERROR,
1924 "Unable to query format (%d)", status);
1925 auto format = static_cast<android_pixel_format_t>(
1926 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001927
Dan Stoza8cf150a2016-08-02 10:27:31 -07001928 mHwc->allocateVirtualDisplay(width, height, &format,
1929 &hwcId);
1930 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931
Dan Stoza5cf424b2016-05-20 14:02:39 -07001932 // TODO: Plumb requested format back up to consumer
1933
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 sp<VirtualDisplaySurface> vds =
1935 new VirtualDisplaySurface(*mHwc,
1936 hwcId, state.surface, bqProducer,
1937 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001938
1939 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001940 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001941 }
1942 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001943 ALOGE_IF(state.surface!=NULL,
1944 "adding a supported display, but rendering "
1945 "surface is provided (%p), ignoring it",
1946 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001947
1948 hwcId = state.type;
1949 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1950 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001951 }
1952
1953 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001954 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001955 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 state.type, hwcId, state.isSecure, display,
1957 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001958 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001959 hw->setLayerStack(state.layerStack);
1960 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001961 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001962 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001963 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001965 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001966 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001967 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001968 }
1969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001971 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001972
Mathias Agopian84300952012-11-21 16:02:13 -08001973 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1974 // The transform hint might have changed for some layers
1975 // (either because a display has changed, or because a layer
1976 // as changed).
1977 //
1978 // Walk through all the layers in currentLayers,
1979 // and update their transform hint.
1980 //
1981 // If a layer is visible only on a single display, then that
1982 // display is used to calculate the hint, otherwise we use the
1983 // default display.
1984 //
1985 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1986 // the hint is set before we acquire a buffer from the surface texture.
1987 //
1988 // NOTE: layer transactions have taken place already, so we use their
1989 // drawing state. However, SurfaceFlinger's own transaction has not
1990 // happened yet, so we must use the current state layer list
1991 // (soon to become the drawing state list).
1992 //
1993 sp<const DisplayDevice> disp;
1994 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001995 bool first = true;
1996 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001997 // NOTE: we rely on the fact that layers are sorted by
1998 // layerStack first (so we don't have to traverse the list
1999 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002000 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002001 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002002 currentlayerStack = layerStack;
2003 // figure out if this layerstack is mirrored
2004 // (more than one display) if so, pick the default display,
2005 // if not, pick the only display it's on.
2006 disp.clear();
2007 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2008 sp<const DisplayDevice> hw(mDisplays[dpy]);
2009 if (hw->getLayerStack() == currentlayerStack) {
2010 if (disp == NULL) {
2011 disp = hw;
2012 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002013 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002014 break;
2015 }
2016 }
2017 }
2018 }
Chet Haase91d25932013-04-11 15:24:55 -07002019 if (disp == NULL) {
2020 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2021 // redraw after transform hint changes. See bug 8508397.
2022
2023 // could be null when this layer is using a layerStack
2024 // that is not visible on any display. Also can occur at
2025 // screen off/on times.
2026 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002027 }
Chet Haase91d25932013-04-11 15:24:55 -07002028 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002029
2030 first = false;
2031 });
Mathias Agopian84300952012-11-21 16:02:13 -08002032 }
2033
2034
Mathias Agopian3559b072012-08-15 13:46:03 -07002035 /*
2036 * Perform our own transaction if needed
2037 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002038
2039 if (mLayersAdded) {
2040 mLayersAdded = false;
2041 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002042 mVisibleRegionsDirty = true;
2043 }
2044
2045 // some layers might have been removed, so
2046 // we need to update the regions they're exposing.
2047 if (mLayersRemoved) {
2048 mLayersRemoved = false;
2049 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002050 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002051 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002052 // this layer is not visible anymore
2053 // TODO: we could traverse the tree from front to back and
2054 // compute the actual visible region
2055 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002056 Region visibleReg;
2057 visibleReg.set(layer->computeScreenBounds());
2058 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002059 }
Robert Carr2047fae2016-11-28 14:09:09 -08002060 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061 }
2062
2063 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002064
2065 updateCursorAsync();
2066}
2067
2068void SurfaceFlinger::updateCursorAsync()
2069{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2071 auto& displayDevice = mDisplays[displayId];
2072 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002073 continue;
2074 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075
2076 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2077 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002078 }
2079 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002080}
2081
2082void SurfaceFlinger::commitTransaction()
2083{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002084 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002085 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002086 for (const auto& l : mLayersPendingRemoval) {
2087 recordBufferingStats(l->getName().string(),
2088 l->getOccupancyHistory(true));
2089 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002090 }
2091 mLayersPendingRemoval.clear();
2092 }
2093
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002094 // If this transaction is part of a window animation then the next frame
2095 // we composite should be considered an animation as well.
2096 mAnimCompositionPending = mAnimTransactionPending;
2097
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002099 mDrawingState.traverseInZOrder([](Layer* layer) {
2100 layer->commitChildList();
2101 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002102 mTransactionPending = false;
2103 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002104 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105}
2106
Robert Carr2047fae2016-11-28 14:09:09 -08002107void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002108 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109{
Mathias Agopian841cde52012-03-01 15:44:37 -08002110 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002112
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 Region aboveOpaqueLayers;
2114 Region aboveCoveredLayers;
2115 Region dirty;
2116
Mathias Agopian87baae12012-07-31 12:38:26 -07002117 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118
Robert Carr2047fae2016-11-28 14:09:09 -08002119 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002121 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122
Jesse Hall01e29052013-02-19 16:13:35 -08002123 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002124 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002125 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002126
Mathias Agopianab028732010-03-16 16:41:46 -07002127 /*
2128 * opaqueRegion: area of a surface that is fully opaque.
2129 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002131
2132 /*
2133 * visibleRegion: area of a surface that is visible on screen
2134 * and not fully transparent. This is essentially the layer's
2135 * footprint minus the opaque regions above it.
2136 * Areas covered by a translucent surface are considered visible.
2137 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002139
2140 /*
2141 * coveredRegion: area of a surface that is covered by all
2142 * visible regions above it (which includes the translucent areas).
2143 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002145
Jesse Halla8026d22012-09-25 13:25:04 -07002146 /*
2147 * transparentRegion: area of a surface that is hinted to be completely
2148 * transparent. This is only used to tell when the layer has no visible
2149 * non-transparent regions and can be removed from the layer list. It
2150 * does not affect the visibleRegion of this layer or any layers
2151 * beneath it. The hint may not be correct if apps don't respect the
2152 * SurfaceView restrictions (which, sadly, some don't).
2153 */
2154 Region transparentRegion;
2155
Mathias Agopianab028732010-03-16 16:41:46 -07002156
2157 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002158 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002159 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002160 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002161 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002162 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002163 if (!visibleRegion.isEmpty()) {
2164 // Remove the transparent area from the visible region
2165 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002166 if (tr.preserveRects()) {
2167 // transform the transparent region
2168 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002169 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002170 // transformation too complex, can't do the
2171 // transparent region optimization.
2172 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002173 }
Mathias Agopianab028732010-03-16 16:41:46 -07002174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002175
Mathias Agopianab028732010-03-16 16:41:46 -07002176 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002178 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002179 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2180 // the opaque region is the layer's footprint
2181 opaqueRegion = visibleRegion;
2182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183 }
2184 }
2185
Mathias Agopianab028732010-03-16 16:41:46 -07002186 // Clip the covered region to the visible region
2187 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2188
2189 // Update aboveCoveredLayers for next (lower) layer
2190 aboveCoveredLayers.orSelf(visibleRegion);
2191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192 // subtract the opaque region covered by the layers above us
2193 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194
2195 // compute this layer's dirty region
2196 if (layer->contentDirty) {
2197 // we need to invalidate the whole region
2198 dirty = visibleRegion;
2199 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002200 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201 layer->contentDirty = false;
2202 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002203 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002204 * the exposed region consists of two components:
2205 * 1) what's VISIBLE now and was COVERED before
2206 * 2) what's EXPOSED now less what was EXPOSED before
2207 *
2208 * note that (1) is conservative, we start with the whole
2209 * visible region but only keep what used to be covered by
2210 * something -- which mean it may have been exposed.
2211 *
2212 * (2) handles areas that were not covered by anything but got
2213 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002214 */
Mathias Agopianab028732010-03-16 16:41:46 -07002215 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002216 const Region oldVisibleRegion = layer->visibleRegion;
2217 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002218 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2219 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220 }
2221 dirty.subtractSelf(aboveOpaqueLayers);
2222
2223 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002224 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225
Mathias Agopianab028732010-03-16 16:41:46 -07002226 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002227 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002228
Jesse Halla8026d22012-09-25 13:25:04 -07002229 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 layer->setVisibleRegion(visibleRegion);
2231 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002232 layer->setVisibleNonTransparentRegion(
2233 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002234 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Mathias Agopian87baae12012-07-31 12:38:26 -07002236 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237}
2238
Mathias Agopian87baae12012-07-31 12:38:26 -07002239void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2240 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002241 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002242 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2243 if (hw->getLayerStack() == layerStack) {
2244 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002245 }
2246 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002247}
2248
Dan Stoza6b9454d2014-11-07 16:00:59 -08002249bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002251 ALOGV("handlePageFlip");
2252
Brian Andersond6927fb2016-07-23 23:37:30 -07002253 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Mathias Agopian4fec8732012-06-29 14:12:52 -07002255 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002256 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002257
2258 // Store the set of layers that need updates. This set must not change as
2259 // buffers are being latched, as this could result in a deadlock.
2260 // Example: Two producers share the same command stream and:
2261 // 1.) Layer 0 is latched
2262 // 2.) Layer 0 gets a new frame
2263 // 2.) Layer 1 gets a new frame
2264 // 3.) Layer 1 is latched.
2265 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2266 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002267 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002268 if (layer->hasQueuedFrame()) {
2269 frameQueued = true;
2270 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002271 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002272 } else {
2273 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002274 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002275 } else {
2276 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002277 }
Robert Carr2047fae2016-11-28 14:09:09 -08002278 });
2279
Dan Stoza9e56aa02015-11-02 13:00:03 -08002280 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002281 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002282 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002283 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002284 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002285
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002286 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002287
2288 // If we will need to wake up at some time in the future to deal with a
2289 // queued frame that shouldn't be displayed during this vsync period, wake
2290 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002291 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002292 signalLayerUpdate();
2293 }
2294
2295 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297}
2298
Mathias Agopianad456f92011-01-13 17:53:01 -08002299void SurfaceFlinger::invalidateHwcGeometry()
2300{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002302}
2303
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002304
Fabien Sanglard830b8472016-11-30 16:35:58 -08002305void SurfaceFlinger::doDisplayComposition(
2306 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002307 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308{
Dan Stoza71433162014-02-04 16:22:36 -08002309 // We only need to actually compose the display if:
2310 // 1) It is being handled by hardware composer, which may need this to
2311 // keep its virtual display state machine in sync, or
2312 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002313 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002314 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002315 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002316 return;
2317 }
2318
Dan Stoza9e56aa02015-11-02 13:00:03 -08002319 ALOGV("doDisplayComposition");
2320
Mathias Agopian87baae12012-07-31 12:38:26 -07002321 Region dirtyRegion(inDirtyRegion);
2322
Mathias Agopianb8a55602009-06-26 19:06:36 -07002323 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002324 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325
Fabien Sanglard830b8472016-11-30 16:35:58 -08002326 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002327 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002328 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2329 // takes a rectangle, we must make sure to update that whole
2330 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002331 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002332 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002333 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002334 // We need to redraw the rectangle that will be updated
2335 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002336 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002337 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002338 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002339 } else {
2340 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002341 dirtyRegion.set(displayDevice->bounds());
2342 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343 }
2344 }
2345
Fabien Sanglard830b8472016-11-30 16:35:58 -08002346 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002348 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002350
2351 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002352 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353}
2354
Dan Stoza9e56aa02015-11-02 13:00:03 -08002355bool SurfaceFlinger::doComposeSurfaces(
2356 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002357{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002359
Dan Stoza9e56aa02015-11-02 13:00:03 -08002360 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002361
2362 mat4 oldColorMatrix;
2363 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2364 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2365 if (applyColorMatrix) {
2366 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2367 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2368 }
2369
Dan Stoza9e56aa02015-11-02 13:00:03 -08002370 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2371 if (hasClientComposition) {
2372 ALOGV("hasClientComposition");
2373
2374 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002375 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002377 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2378 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2379 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2380 }
2381 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002382 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002383
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002384 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002385 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2386 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002387 // when using overlays, we assume a fully transparent framebuffer
2388 // NOTE: we could reduce how much we need to clear, for instance
2389 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002390 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002391 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002392 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002393 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002394 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002395 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002396
2397 // we remove the scissor part
2398 // we're left with the letterbox region
2399 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002400 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002401
2402 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002404
2405 // but limit it to the dirty region
2406 region.andSelf(dirty);
2407
Mathias Agopianb9494d52012-04-18 02:28:45 -07002408 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002409 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002410 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002412 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002413 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002414
Dan Stoza9e56aa02015-11-02 13:00:03 -08002415 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002416 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002417 // scissor on the main display. It should never be needed
2418 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 const Rect& bounds(displayDevice->getBounds());
2420 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002421 if (scissor != bounds) {
2422 // scissor doesn't match the screen's dimensions, so we
2423 // need to clear everything outside of it and enable
2424 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002425
Mathias Agopianf45c5102012-10-24 16:29:17 -07002426 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 const uint32_t height = displayDevice->getHeight();
2428 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002429 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002430 }
2431 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002432 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002433
Mathias Agopian85d751c2012-08-29 16:59:24 -07002434 /*
2435 * and then, render the layers targeted at the framebuffer
2436 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002437
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 ALOGV("Rendering client layers");
2439 const Transform& displayTransform = displayDevice->getTransform();
2440 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002441 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002442 bool firstLayer = true;
2443 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2444 const Region clip(dirty.intersect(
2445 displayTransform.transform(layer->visibleRegion)));
2446 ALOGV("Layer: %s", layer->getName().string());
2447 ALOGV(" Composition type: %s",
2448 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002449 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 switch (layer->getCompositionType(hwcId)) {
2451 case HWC2::Composition::Cursor:
2452 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002453 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002455 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2457 layer->isOpaque(state) && (state.alpha == 1.0f)
2458 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002459 // never clear the very first layer since we're
2460 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002461 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002462 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002463 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002464 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 case HWC2::Composition::Client: {
2466 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002467 break;
2468 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002470 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002471 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 } else {
2473 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002474 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002476 }
2477 } else {
2478 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002480 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002482 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002484 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002485 }
2486 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002487
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002488 if (applyColorMatrix) {
2489 getRenderEngine().setupColorTransform(oldColorMatrix);
2490 }
2491
Mathias Agopianf45c5102012-10-24 16:29:17 -07002492 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002494 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495}
2496
Fabien Sanglard830b8472016-11-30 16:35:58 -08002497void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2498 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002499 RenderEngine& engine(getRenderEngine());
2500 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Dan Stoza7d89d062015-04-30 13:29:25 -07002503status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002504 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002505 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002506 const sp<Layer>& lbc,
2507 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002508{
Dan Stoza7d89d062015-04-30 13:29:25 -07002509 // add this layer to the current state list
2510 {
2511 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002512 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002513 return NO_MEMORY;
2514 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515 if (parent == nullptr) {
2516 mCurrentState.layersSortedByZ.add(lbc);
2517 } else {
2518 parent->addChild(lbc);
2519 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002520 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002521 mLayersAdded = true;
2522 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002523 }
2524
Mathias Agopian96f08192010-06-02 23:28:45 -07002525 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002526 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002527
Dan Stoza7d89d062015-04-30 13:29:25 -07002528 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002529}
2530
Dan Stoza22851c32016-08-09 13:21:03 -07002531status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002533 sp<Layer> layer = weakLayer.promote();
2534 if (layer == nullptr) {
2535 // The layer has already been removed, carry on
2536 return NO_ERROR;
2537 }
2538
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 const auto& p = layer->getParent();
2540 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2541 mCurrentState.layersSortedByZ.remove(layer);
2542
Robert Carr136e2f62017-02-08 17:54:29 -08002543 // As a matter of normal operation, the LayerCleaner will produce a second
2544 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2545 // so we will succeed in promoting it, but it's already been removed
2546 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2547 // otherwise something has gone wrong and we are leaking the layer.
2548 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002549 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2550 layer->getName().string(),
2551 (p != nullptr) ? p->getName().string() : "no-parent");
2552 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002553 } else if (index < 0) {
2554 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002555 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002556
2557 mLayersPendingRemoval.add(layer);
2558 mLayersRemoved = true;
2559 mNumLayers--;
2560 setTransactionFlags(eTransactionNeeded);
2561 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562}
2563
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002564uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002565 return android_atomic_release_load(&mTransactionFlags);
2566}
2567
Mathias Agopian3f844832013-08-07 21:24:32 -07002568uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2570}
2571
Mathias Agopian3f844832013-08-07 21:24:32 -07002572uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2574 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002575 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 }
2577 return old;
2578}
2579
Mathias Agopian8b33f032012-07-24 20:43:54 -07002580void SurfaceFlinger::setTransactionState(
2581 const Vector<ComposerState>& state,
2582 const Vector<DisplayState>& displays,
2583 uint32_t flags)
2584{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002585 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002586 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002587 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002588
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002589 if (flags & eAnimation) {
2590 // For window updates that are part of an animation we must wait for
2591 // previous animation "frames" to be handled.
2592 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002593 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002594 if (CC_UNLIKELY(err != NO_ERROR)) {
2595 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002596 // caller after a few seconds.
2597 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2598 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002599 mAnimTransactionPending = false;
2600 break;
2601 }
2602 }
2603 }
2604
Mathias Agopiane57f2922012-08-09 16:29:12 -07002605 size_t count = displays.size();
2606 for (size_t i=0 ; i<count ; i++) {
2607 const DisplayState& s(displays[i]);
2608 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002609 }
2610
Mathias Agopiane57f2922012-08-09 16:29:12 -07002611 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002612 for (size_t i=0 ; i<count ; i++) {
2613 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002614 // Here we need to check that the interface we're given is indeed
2615 // one of our own. A malicious client could give us a NULL
2616 // IInterface, or one of its own or even one of our own but a
2617 // different type. All these situations would cause us to crash.
2618 //
2619 // NOTE: it would be better to use RTTI as we could directly check
2620 // that we have a Client*. however, RTTI is disabled in Android.
2621 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002622 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002623 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002624 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002625 sp<Client> client( static_cast<Client *>(s.client.get()) );
2626 transactionFlags |= setClientStateLocked(client, s.state);
2627 }
2628 }
2629 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002630 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002631
Robert Carr2a7dbb42016-05-24 11:41:28 -07002632 // If a synchronous transaction is explicitly requested without any changes,
2633 // force a transaction anyway. This can be used as a flush mechanism for
2634 // previous async transactions.
2635 if (transactionFlags == 0 && (flags & eSynchronous)) {
2636 transactionFlags = eTransactionNeeded;
2637 }
2638
Mathias Agopian386aa982011-11-07 21:58:03 -08002639 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002640 if (mInterceptor.isEnabled()) {
2641 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2642 }
Irvel468051e2016-06-13 16:44:44 -07002643
Mathias Agopian386aa982011-11-07 21:58:03 -08002644 // this triggers the transaction
2645 setTransactionFlags(transactionFlags);
2646
2647 // if this is a synchronous transaction, wait for it to take effect
2648 // before returning.
2649 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002650 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002651 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002652 if (flags & eAnimation) {
2653 mAnimTransactionPending = true;
2654 }
2655 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002656 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2657 if (CC_UNLIKELY(err != NO_ERROR)) {
2658 // just in case something goes wrong in SF, return to the
2659 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002660 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2661 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002662 break;
2663 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002664 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 }
2666}
2667
Mathias Agopiane57f2922012-08-09 16:29:12 -07002668uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2669{
Jesse Hall9a143922012-10-04 16:29:19 -07002670 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2671 if (dpyIdx < 0)
2672 return 0;
2673
Mathias Agopiane57f2922012-08-09 16:29:12 -07002674 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002675 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002676 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002677 const uint32_t what = s.what;
2678 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002679 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002680 disp.surface = s.surface;
2681 flags |= eDisplayTransactionNeeded;
2682 }
2683 }
2684 if (what & DisplayState::eLayerStackChanged) {
2685 if (disp.layerStack != s.layerStack) {
2686 disp.layerStack = s.layerStack;
2687 flags |= eDisplayTransactionNeeded;
2688 }
2689 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002690 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002691 if (disp.orientation != s.orientation) {
2692 disp.orientation = s.orientation;
2693 flags |= eDisplayTransactionNeeded;
2694 }
2695 if (disp.frame != s.frame) {
2696 disp.frame = s.frame;
2697 flags |= eDisplayTransactionNeeded;
2698 }
2699 if (disp.viewport != s.viewport) {
2700 disp.viewport = s.viewport;
2701 flags |= eDisplayTransactionNeeded;
2702 }
2703 }
Michael Lentine47e45402014-07-18 15:34:25 -07002704 if (what & DisplayState::eDisplaySizeChanged) {
2705 if (disp.width != s.width) {
2706 disp.width = s.width;
2707 flags |= eDisplayTransactionNeeded;
2708 }
2709 if (disp.height != s.height) {
2710 disp.height = s.height;
2711 flags |= eDisplayTransactionNeeded;
2712 }
2713 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002714 }
2715 return flags;
2716}
2717
2718uint32_t SurfaceFlinger::setClientStateLocked(
2719 const sp<Client>& client,
2720 const layer_state_t& s)
2721{
2722 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002723 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002724 if (layer != 0) {
2725 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002726 bool geometryAppliesWithResize =
2727 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002728 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002729 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002730 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002731 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002732 }
2733 if (what & layer_state_t::eLayerChanged) {
2734 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735 const auto& p = layer->getParent();
2736 if (p == nullptr) {
2737 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2738 if (layer->setLayer(s.z) && idx >= 0) {
2739 mCurrentState.layersSortedByZ.removeAt(idx);
2740 mCurrentState.layersSortedByZ.add(layer);
2741 // we need traversal (state changed)
2742 // AND transaction (list changed)
2743 flags |= eTransactionNeeded|eTraversalNeeded;
2744 }
2745 } else {
2746 if (p->setChildLayer(layer, s.z)) {
2747 flags |= eTransactionNeeded|eTraversalNeeded;
2748 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002749 }
2750 }
2751 if (what & layer_state_t::eSizeChanged) {
2752 if (layer->setSize(s.w, s.h)) {
2753 flags |= eTraversalNeeded;
2754 }
2755 }
2756 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002758 flags |= eTraversalNeeded;
2759 }
2760 if (what & layer_state_t::eMatrixChanged) {
2761 if (layer->setMatrix(s.matrix))
2762 flags |= eTraversalNeeded;
2763 }
2764 if (what & layer_state_t::eTransparentRegionChanged) {
2765 if (layer->setTransparentRegionHint(s.transparentRegion))
2766 flags |= eTraversalNeeded;
2767 }
Dan Stoza23116082015-06-18 14:58:39 -07002768 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002769 if (layer->setFlags(s.flags, s.mask))
2770 flags |= eTraversalNeeded;
2771 }
2772 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002773 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002774 flags |= eTraversalNeeded;
2775 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002776 if (what & layer_state_t::eFinalCropChanged) {
2777 if (layer->setFinalCrop(s.finalCrop))
2778 flags |= eTraversalNeeded;
2779 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002780 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002781 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782 // We only allow setting layer stacks for top level layers,
2783 // everything else inherits layer stack from its parent.
2784 if (layer->hasParent()) {
2785 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2786 layer->getName().string());
2787 } else if (idx < 0) {
2788 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2789 "that also does not appear in the top level layer list. Something"
2790 " has gone wrong.", layer->getName().string());
2791 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792 mCurrentState.layersSortedByZ.removeAt(idx);
2793 mCurrentState.layersSortedByZ.add(layer);
2794 // we need traversal (state changed)
2795 // AND transaction (list changed)
2796 flags |= eTransactionNeeded|eTraversalNeeded;
2797 }
2798 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002799 if (what & layer_state_t::eDeferTransaction) {
2800 layer->deferTransactionUntil(s.handle, s.frameNumber);
2801 // We don't trigger a traversal here because if no other state is
2802 // changed, we don't want this to cause any more work
2803 }
Robert Carr1db73f62016-12-21 12:58:51 -08002804 if (what & layer_state_t::eReparentChildren) {
2805 if (layer->reparentChildren(s.reparentHandle)) {
2806 flags |= eTransactionNeeded|eTraversalNeeded;
2807 }
2808 }
Robert Carrc3574f72016-03-24 12:19:32 -07002809 if (what & layer_state_t::eOverrideScalingModeChanged) {
2810 layer->setOverrideScalingMode(s.overrideScalingMode);
2811 // We don't trigger a traversal here because if no other state is
2812 // changed, we don't want this to cause any more work
2813 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002814 }
2815 return flags;
2816}
2817
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002818status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002819 const String8& name,
2820 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002821 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002822 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2823 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002825 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002826 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002827 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002828 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002829 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002830
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002831 status_t result = NO_ERROR;
2832
2833 sp<Layer> layer;
2834
Mathias Agopian3165cc22012-08-08 19:42:09 -07002835 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2836 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002837 result = createNormalLayer(client,
2838 name, w, h, flags, format,
2839 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002841 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002842 result = createDimLayer(client,
2843 name, w, h, flags,
2844 handle, gbp, &layer);
2845 break;
2846 default:
2847 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 break;
2849 }
2850
Dan Stoza7d89d062015-04-30 13:29:25 -07002851 if (result != NO_ERROR) {
2852 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002854
Albert Chaulk479c60c2017-01-27 14:21:34 -05002855 layer->setInfo(windowType, ownerUid);
2856
Robert Carr1f0a16a2016-10-24 16:27:39 -07002857 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002858 if (result != NO_ERROR) {
2859 return result;
2860 }
Irvelffc9efc2016-07-27 15:16:37 -07002861 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002862
2863 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002864 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002867status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2868 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2869 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870{
2871 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002872 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 case PIXEL_FORMAT_TRANSPARENT:
2874 case PIXEL_FORMAT_TRANSLUCENT:
2875 format = PIXEL_FORMAT_RGBA_8888;
2876 break;
2877 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002878 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 break;
2880 }
2881
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002882 *outLayer = new Layer(this, client, name, w, h, flags);
2883 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2884 if (err == NO_ERROR) {
2885 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002886 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002888
2889 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2890 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002893status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2894 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2895 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002897 *outLayer = new LayerDim(this, client, name, w, h, flags);
2898 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002899 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002900 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002901}
2902
Mathias Agopianac9fa422013-02-11 16:40:36 -08002903status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904{
Mathias Agopian67106042013-03-14 19:18:13 -07002905 // called by the window manager when it wants to remove a Layer
2906 status_t err = NO_ERROR;
2907 sp<Layer> l(client->getLayerUser(handle));
2908 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002909 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002910 err = removeLayer(l);
2911 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2912 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002913 }
2914 return err;
2915}
2916
Mathias Agopian13127d82013-03-05 17:47:11 -08002917status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002918{
Mathias Agopian67106042013-03-14 19:18:13 -07002919 // called by ~LayerCleaner() when all references to the IBinder (handle)
2920 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002921 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922}
2923
Mathias Agopianb60314a2012-04-10 22:09:54 -07002924// ---------------------------------------------------------------------------
2925
Andy McFadden13a082e2012-08-24 10:16:42 -07002926void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002927 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002928 Vector<ComposerState> state;
2929 Vector<DisplayState> displays;
2930 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002931 d.what = DisplayState::eDisplayProjectionChanged |
2932 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002933 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002934 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002935 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002936 d.frame.makeInvalid();
2937 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002938 d.width = 0;
2939 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002940 displays.add(d);
2941 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002942 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002943
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2945 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002946 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002947
2948 {
2949 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2950 mCompositorTiming.interval = period;
2951 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002952}
2953
2954void SurfaceFlinger::initializeDisplays() {
2955 class MessageScreenInitialized : public MessageBase {
2956 SurfaceFlinger* flinger;
2957 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002958 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002959 virtual bool handler() {
2960 flinger->onInitializeDisplays();
2961 return true;
2962 }
2963 };
2964 sp<MessageBase> msg = new MessageScreenInitialized(this);
2965 postMessageAsync(msg); // we may be called from main thread, use async message
2966}
2967
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002968void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2969 int mode) {
2970 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2971 this);
2972 int32_t type = hw->getDisplayType();
2973 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002974
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002975 if (mode == currentMode) {
2976 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002977 return;
2978 }
2979
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002980 hw->setPowerMode(mode);
2981 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2982 ALOGW("Trying to set power mode for virtual display");
2983 return;
2984 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002985
Irvelffc9efc2016-07-27 15:16:37 -07002986 if (mInterceptor.isEnabled()) {
2987 Mutex::Autolock _l(mStateLock);
2988 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2989 if (idx < 0) {
2990 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2991 return;
2992 }
2993 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2994 }
2995
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002996 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002997 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002998 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002999 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3000 // FIXME: eventthread only knows about the main display right now
3001 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003002 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003003 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003005 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003006 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003007 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003008
3009 struct sched_param param = {0};
3010 param.sched_priority = 1;
3011 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3012 ALOGW("Couldn't set SCHED_FIFO on display on");
3013 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003014 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003015 // Turn off the display
3016 struct sched_param param = {0};
3017 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3018 ALOGW("Couldn't set SCHED_OTHER on display off");
3019 }
3020
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003021 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003022 disableHardwareVsync(true); // also cancels any in-progress resync
3023
Mathias Agopiancde87a32012-09-13 14:09:01 -07003024 // FIXME: eventthread only knows about the main display right now
3025 mEventThread->onScreenReleased();
3026 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003027
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003028 getHwComposer().setPowerMode(type, mode);
3029 mVisibleRegionsDirty = true;
3030 // from this point on, SF will stop drawing on this display
3031 } else {
3032 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003033 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003034}
3035
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003036void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3037 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003038 SurfaceFlinger& mFlinger;
3039 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003041 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003042 MessageSetPowerMode(SurfaceFlinger& flinger,
3043 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3044 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003045 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003046 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003047 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003049 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003050 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003051 ALOGW("Attempt to set power mode = %d for virtual display",
3052 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003053 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003054 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003056 return true;
3057 }
3058 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003059 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003060 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003061}
3062
3063// ---------------------------------------------------------------------------
3064
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3066{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003068
Mathias Agopianbd115332013-04-18 16:41:04 -07003069 IPCThreadState* ipc = IPCThreadState::self();
3070 const int pid = ipc->getCallingPid();
3071 const int uid = ipc->getCallingUid();
3072 if ((uid != AID_SHELL) &&
3073 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003074 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003075 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003077 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003078 // (this would indicate SF is stuck, but we want to be able to
3079 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003080 status_t err = mStateLock.timedLock(s2ns(1));
3081 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003082 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003083 result.appendFormat(
3084 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3085 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003086 }
3087
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003088 bool dumpAll = true;
3089 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003090 size_t numArgs = args.size();
3091 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003092 if ((index < numArgs) &&
3093 (args[index] == String16("--list"))) {
3094 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003095 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003096 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003097 }
3098
3099 if ((index < numArgs) &&
3100 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003101 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003102 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003103 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003104 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003105
3106 if ((index < numArgs) &&
3107 (args[index] == String16("--latency-clear"))) {
3108 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003109 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003110 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003111 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003112
3113 if ((index < numArgs) &&
3114 (args[index] == String16("--dispsync"))) {
3115 index++;
3116 mPrimaryDispSync.dump(result);
3117 dumpAll = false;
3118 }
Dan Stozab90cf072015-03-05 11:05:59 -08003119
3120 if ((index < numArgs) &&
3121 (args[index] == String16("--static-screen"))) {
3122 index++;
3123 dumpStaticScreenStats(result);
3124 dumpAll = false;
3125 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003126
3127 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003128 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003129 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003130 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003131 dumpAll = false;
3132 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003134
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003136 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003137 }
3138
Mathias Agopian9795c422009-08-26 16:36:26 -07003139 if (locked) {
3140 mStateLock.unlock();
3141 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 }
3143 write(fd, result.string(), result.size());
3144 return NO_ERROR;
3145}
3146
Dan Stozac7014012014-02-14 15:03:43 -08003147void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3148 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003149{
Robert Carr2047fae2016-11-28 14:09:09 -08003150 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003151 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003152 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003153}
3154
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003155void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003156 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003157{
3158 String8 name;
3159 if (index < args.size()) {
3160 name = String8(args[index]);
3161 index++;
3162 }
3163
Dan Stoza9e56aa02015-11-02 13:00:03 -08003164 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3165 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003166 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003167
3168 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003169 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003170 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003171 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003172 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003173 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003174 }
Robert Carr2047fae2016-11-28 14:09:09 -08003175 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003176 }
3177}
3178
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003179void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003180 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003181{
3182 String8 name;
3183 if (index < args.size()) {
3184 name = String8(args[index]);
3185 index++;
3186 }
3187
Robert Carr2047fae2016-11-28 14:09:09 -08003188 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003189 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003190 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003191 }
Robert Carr2047fae2016-11-28 14:09:09 -08003192 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003193
Svetoslavd85084b2014-03-20 10:28:31 -07003194 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003195}
3196
Jamie Gennis6547ff42013-07-16 20:12:42 -07003197// This should only be called from the main thread. Otherwise it would need
3198// the lock and should use mCurrentState rather than mDrawingState.
3199void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003201 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003202 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003203
3204 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3205}
3206
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003207void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003208{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003209 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003210#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003211 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003212#endif
3213#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003214 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003215#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003216 if (isLayerTripleBufferingDisabled())
3217 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003218 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003219}
3220
Dan Stozab90cf072015-03-05 11:05:59 -08003221void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3222{
3223 result.appendFormat("Static screen stats:\n");
3224 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3225 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3226 float percent = 100.0f *
3227 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3228 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3229 b + 1, bucketTimeSec, percent);
3230 }
3231 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3232 float percent = 100.0f *
3233 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3234 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3235 NUM_BUCKETS - 1, bucketTimeSec, percent);
3236}
3237
Dan Stozae77c7662016-05-13 11:37:28 -07003238void SurfaceFlinger::recordBufferingStats(const char* layerName,
3239 std::vector<OccupancyTracker::Segment>&& history) {
3240 Mutex::Autolock lock(mBufferingStatsMutex);
3241 auto& stats = mBufferingStats[layerName];
3242 for (const auto& segment : history) {
3243 if (!segment.usedThirdBuffer) {
3244 stats.twoBufferTime += segment.totalTime;
3245 }
3246 if (segment.occupancyAverage < 1.0f) {
3247 stats.doubleBufferedTime += segment.totalTime;
3248 } else if (segment.occupancyAverage < 2.0f) {
3249 stats.tripleBufferedTime += segment.totalTime;
3250 }
3251 ++stats.numSegments;
3252 stats.totalTime += segment.totalTime;
3253 }
3254}
3255
Brian Andersond6927fb2016-07-23 23:37:30 -07003256void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3257 result.appendFormat("Layer frame timestamps:\n");
3258
3259 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3260 const size_t count = currentLayers.size();
3261 for (size_t i=0 ; i<count ; i++) {
3262 currentLayers[i]->dumpFrameEvents(result);
3263 }
3264}
3265
Dan Stozae77c7662016-05-13 11:37:28 -07003266void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3267 result.append("Buffering stats:\n");
3268 result.append(" [Layer name] <Active time> <Two buffer> "
3269 "<Double buffered> <Triple buffered>\n");
3270 Mutex::Autolock lock(mBufferingStatsMutex);
3271 typedef std::tuple<std::string, float, float, float> BufferTuple;
3272 std::map<float, BufferTuple, std::greater<float>> sorted;
3273 for (const auto& statsPair : mBufferingStats) {
3274 const char* name = statsPair.first.c_str();
3275 const BufferingStats& stats = statsPair.second;
3276 if (stats.numSegments == 0) {
3277 continue;
3278 }
3279 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3280 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3281 stats.totalTime;
3282 float doubleBufferRatio = static_cast<float>(
3283 stats.doubleBufferedTime) / stats.totalTime;
3284 float tripleBufferRatio = static_cast<float>(
3285 stats.tripleBufferedTime) / stats.totalTime;
3286 sorted.insert({activeTime, {name, twoBufferRatio,
3287 doubleBufferRatio, tripleBufferRatio}});
3288 }
3289 for (const auto& sortedPair : sorted) {
3290 float activeTime = sortedPair.first;
3291 const BufferTuple& values = sortedPair.second;
3292 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3293 std::get<0>(values).c_str(), activeTime,
3294 std::get<1>(values), std::get<2>(values),
3295 std::get<3>(values));
3296 }
3297 result.append("\n");
3298}
3299
3300
Mathias Agopian74d211a2013-04-22 16:55:35 +02003301void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3302 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003303{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003304 bool colorize = false;
3305 if (index < args.size()
3306 && (args[index] == String16("--color"))) {
3307 colorize = true;
3308 index++;
3309 }
3310
3311 Colorizer colorizer(colorize);
3312
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003313 // figure out if we're stuck somewhere
3314 const nsecs_t now = systemTime();
3315 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3316 const nsecs_t inTransaction(mDebugInTransaction);
3317 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3318 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3319
3320 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003321 * Dump library configuration.
3322 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003323
3324 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003325 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003326 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003327 appendSfConfigString(result);
3328 appendUiConfigString(result);
3329 appendGuiConfigString(result);
3330 result.append("\n");
3331
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003332 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003333 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003334 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003335 result.append(SyncFeatures::getInstance().toString());
3336 result.append("\n");
3337
Dan Stoza9e56aa02015-11-02 13:00:03 -08003338 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3339
Andy McFadden41d67d72014-04-25 16:58:34 -07003340 colorizer.bold(result);
3341 result.append("DispSync configuration: ");
3342 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003343 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3344 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003345 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3346 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003347 result.append("\n");
3348
Dan Stozab90cf072015-03-05 11:05:59 -08003349 // Dump static screen stats
3350 result.append("\n");
3351 dumpStaticScreenStats(result);
3352 result.append("\n");
3353
Dan Stozae77c7662016-05-13 11:37:28 -07003354 dumpBufferingStats(result);
3355
Andy McFadden4803b742012-09-24 19:07:20 -07003356 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003357 * Dump the visible layer list
3358 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003359 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003360 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003361 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003362 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003363 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003364 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003365
3366 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003367 * Dump Display state
3368 */
3369
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003371 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003372 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003373 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3374 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003375 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003376 }
3377
3378 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003379 * Dump SurfaceFlinger global state
3380 */
3381
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003382 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003383 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003384 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003385
Mathias Agopian888c8222012-08-04 21:10:38 -07003386 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003387 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003388
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003389 colorizer.bold(result);
3390 result.appendFormat("EGL implementation : %s\n",
3391 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3392 colorizer.reset(result);
3393 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003394 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003395
Mathias Agopian875d8e12013-06-07 15:35:48 -07003396 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003397
Mathias Agopian42977342012-08-05 00:40:46 -07003398 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003399 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3400 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402 " last eglSwapBuffers() time: %f us\n"
3403 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003404 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405 " refresh-rate : %f fps\n"
3406 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003407 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003408 " gpu_to_cpu_unsupported : %d\n"
3409 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003410 mLastSwapBufferTime/1000.0,
3411 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003412 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003413 1e9 / activeConfig->getVsyncPeriod(),
3414 activeConfig->getDpiX(),
3415 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003416 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003417
Mathias Agopian74d211a2013-04-22 16:55:35 +02003418 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420
Mathias Agopian74d211a2013-04-22 16:55:35 +02003421 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003422 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423
3424 /*
3425 * VSYNC state
3426 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003427 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003428 result.append("\n");
3429
3430 /*
3431 * HWC layer minidump
3432 */
3433 for (size_t d = 0; d < mDisplays.size(); d++) {
3434 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3435 int32_t hwcId = displayDevice->getHwcDisplayId();
3436 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3437 continue;
3438 }
3439
3440 result.appendFormat("Display %d HWC layers:\n", hwcId);
3441 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003442 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003443 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003444 });
Dan Stozae22aec72016-08-01 13:20:59 -07003445 result.append("\n");
3446 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003447
3448 /*
3449 * Dump HWComposer state
3450 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003451 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003452 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003453 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003454 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003455 result.appendFormat(" h/w composer %s\n",
3456 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003457 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458
3459 /*
3460 * Dump gralloc state
3461 */
3462 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3463 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003464}
3465
Mathias Agopian13127d82013-03-05 17:47:11 -08003466const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003467SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003468 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003469 wp<IBinder> dpy;
3470 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3471 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3472 dpy = mDisplays.keyAt(i);
3473 break;
3474 }
3475 }
3476 if (dpy == NULL) {
3477 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3478 // Just use the primary display so we have something to return
3479 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3480 }
3481 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003482}
3483
Keun young Park63f165f2012-08-31 10:53:36 -07003484bool SurfaceFlinger::startDdmConnection()
3485{
3486 void* libddmconnection_dso =
3487 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3488 if (!libddmconnection_dso) {
3489 return false;
3490 }
3491 void (*DdmConnection_start)(const char* name);
3492 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003493 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003494 if (!DdmConnection_start) {
3495 dlclose(libddmconnection_dso);
3496 return false;
3497 }
3498 (*DdmConnection_start)(getServiceName());
3499 return true;
3500}
3501
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003502status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503 switch (code) {
3504 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003505 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003507 case CLEAR_ANIMATION_FRAME_STATS:
3508 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003509 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003510 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 {
3512 // codes that require permission check
3513 IPCThreadState* ipc = IPCThreadState::self();
3514 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003515 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003516 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003517 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003518 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003519 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003521 break;
3522 }
Robert Carr1db73f62016-12-21 12:58:51 -08003523 /*
3524 * Calling setTransactionState is safe, because you need to have been
3525 * granted a reference to Client* and Handle* to do anything with it.
3526 *
3527 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3528 */
3529 case SET_TRANSACTION_STATE:
3530 case CREATE_SCOPED_CONNECTION:
3531 {
3532 return OK;
3533 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003534 case CAPTURE_SCREEN:
3535 {
3536 // codes that require permission check
3537 IPCThreadState* ipc = IPCThreadState::self();
3538 const int pid = ipc->getCallingPid();
3539 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003540 if ((uid != AID_GRAPHICS) &&
3541 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003542 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003543 return PERMISSION_DENIED;
3544 }
3545 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546 }
3547 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003548 return OK;
3549}
3550
3551status_t SurfaceFlinger::onTransact(
3552 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3553{
3554 status_t credentialCheck = CheckTransactCodeCredentials(code);
3555 if (credentialCheck != OK) {
3556 return credentialCheck;
3557 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003559 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3560 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003561 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003562 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003563 IPCThreadState* ipc = IPCThreadState::self();
3564 const int pid = ipc->getCallingPid();
3565 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003566 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003567 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 return PERMISSION_DENIED;
3569 }
3570 int n;
3571 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003572 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003573 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 return NO_ERROR;
3575 case 1002: // SHOW_UPDATES
3576 n = data.readInt32();
3577 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003578 invalidateHwcGeometry();
3579 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003582 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003583 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003585 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 setTransactionFlags(
3587 eTransactionNeeded|
3588 eDisplayTransactionNeeded|
3589 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003590 return NO_ERROR;
3591 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003592 case 1006:{ // send empty update
3593 signalRefresh();
3594 return NO_ERROR;
3595 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003596 case 1008: // toggle use of hw composer
3597 n = data.readInt32();
3598 mDebugDisableHWC = n ? 1 : 0;
3599 invalidateHwcGeometry();
3600 repaintEverything();
3601 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003602 case 1009: // toggle use of transform hint
3603 n = data.readInt32();
3604 mDebugDisableTransformHint = n ? 1 : 0;
3605 invalidateHwcGeometry();
3606 repaintEverything();
3607 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003609 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 reply->writeInt32(0);
3611 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003612 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003613 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 return NO_ERROR;
3615 case 1013: {
3616 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003617 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3618 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003619 return NO_ERROR;
3620 }
3621 case 1014: {
3622 // daltonize
3623 n = data.readInt32();
3624 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003625 case 1:
3626 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3627 break;
3628 case 2:
3629 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3630 break;
3631 case 3:
3632 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3633 break;
3634 default:
3635 mDaltonizer.setType(ColorBlindnessType::None);
3636 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003637 }
3638 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003639 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003640 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003641 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003642 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003643 invalidateHwcGeometry();
3644 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003645 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003647 case 1015: {
3648 // apply a color matrix
3649 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003650 if (n) {
3651 // color matrix is sent as mat3 matrix followed by vec3
3652 // offset, then packed into a mat4 where the last row is
3653 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003654 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003655 for (size_t j = 0; j < 4; j++) {
3656 mColorMatrix[i][j] = data.readFloat();
3657 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003658 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003659 } else {
3660 mColorMatrix = mat4();
3661 }
3662 invalidateHwcGeometry();
3663 repaintEverything();
3664 return NO_ERROR;
3665 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003666 // This is an experimental interface
3667 // Needs to be shifted to proper binder interface when we productize
3668 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003669 n = data.readInt32();
3670 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003671 return NO_ERROR;
3672 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003673 case 1017: {
3674 n = data.readInt32();
3675 mForceFullDamage = static_cast<bool>(n);
3676 return NO_ERROR;
3677 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003678 case 1018: { // Modify Choreographer's phase offset
3679 n = data.readInt32();
3680 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3681 return NO_ERROR;
3682 }
3683 case 1019: { // Modify SurfaceFlinger's phase offset
3684 n = data.readInt32();
3685 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3686 return NO_ERROR;
3687 }
Irvel468051e2016-06-13 16:44:44 -07003688 case 1020: { // Layer updates interceptor
3689 n = data.readInt32();
3690 if (n) {
3691 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003692 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003693 }
3694 else{
3695 ALOGV("Interceptor disabled");
3696 mInterceptor.disable();
3697 }
3698 return NO_ERROR;
3699 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003700 case 1021: { // Disable HWC virtual displays
3701 n = data.readInt32();
3702 mUseHwcVirtualDisplays = !n;
3703 return NO_ERROR;
3704 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 }
3706 }
3707 return err;
3708}
3709
Mathias Agopian53331da2011-08-22 21:44:41 -07003710void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003711 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003712 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003713}
3714
Mathias Agopian59119e62010-10-11 12:37:43 -07003715// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003716// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003717// ---------------------------------------------------------------------------
3718
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003719/* The code below is here to handle b/8734824
3720 *
3721 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003722 * from the surfaceflinger thread to the calling binder thread, where they
3723 * are executed. This allows the calling thread in the calling process to be
3724 * reused and not depend on having "enough" binder threads to handle the
3725 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003726 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003727class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003728 /* Parts of GraphicProducerWrapper are run on two different threads,
3729 * communicating by sending messages via Looper but also by shared member
3730 * data. Coherence maintenance is subtle and in places implicit (ugh).
3731 *
3732 * Don't rely on Looper's sendMessage/handleMessage providing
3733 * release/acquire semantics for any data not actually in the Message.
3734 * Data going from surfaceflinger to binder threads needs to be
3735 * synchronized explicitly.
3736 *
3737 * Barrier open/wait do provide release/acquire semantics. This provides
3738 * implicit synchronization for data coming back from binder to
3739 * surfaceflinger threads.
3740 */
3741
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003742 sp<IGraphicBufferProducer> impl;
3743 sp<Looper> looper;
3744 status_t result;
3745 bool exitPending;
3746 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003747 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003748 uint32_t code;
3749 Parcel const* data;
3750 Parcel* reply;
3751
3752 enum {
3753 MSG_API_CALL,
3754 MSG_EXIT
3755 };
3756
3757 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003758 * Called on surfaceflinger thread. This is called by our "fake"
3759 * BpGraphicBufferProducer. We package the data and reply Parcel and
3760 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003761 */
3762 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003763 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003764 this->code = code;
3765 this->data = &data;
3766 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003767 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003768 // if we've exited, we run the message synchronously right here.
3769 // note (JH): as far as I can tell from looking at the code, this
3770 // never actually happens. if it does, i'm not sure if it happens
3771 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003772 handleMessage(Message(MSG_API_CALL));
3773 } else {
3774 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003775 // Prevent stores to this->{code, data, reply} from being
3776 // reordered later than the construction of Message.
3777 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003778 looper->sendMessage(this, Message(MSG_API_CALL));
3779 barrier.wait();
3780 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003781 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003782 }
3783
3784 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003785 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003786 * call the real BpGraphicBufferProducer.
3787 */
3788 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003789 int what = message.what;
3790 // Prevent reads below from happening before the read from Message
3791 atomic_thread_fence(memory_order_acquire);
3792 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003793 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003794 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003795 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003796 exitRequested = true;
3797 }
3798 }
3799
3800public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003801 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003802 : impl(impl),
3803 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003804 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003805 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003806 exitRequested(false),
3807 code(0),
3808 data(NULL),
3809 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003810 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003811
Jesse Hallb154c422014-07-13 12:47:02 -07003812 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003813 status_t waitForResponse() {
3814 do {
3815 looper->pollOnce(-1);
3816 } while (!exitRequested);
3817 return result;
3818 }
3819
Jesse Hallb154c422014-07-13 12:47:02 -07003820 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003821 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003822 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003823 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003824 // Ensure this->result is visible to the binder thread before it
3825 // handles the message.
3826 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003827 looper->sendMessage(this, Message(MSG_EXIT));
3828 }
3829};
3830
3831
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003832status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3833 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003834 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003835 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003836 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003837
3838 if (CC_UNLIKELY(display == 0))
3839 return BAD_VALUE;
3840
3841 if (CC_UNLIKELY(producer == 0))
3842 return BAD_VALUE;
3843
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003844 // if we have secure windows on this display, never allow the screen capture
3845 // unless the producer interface is local (i.e.: we can take a screenshot for
3846 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003847 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003848
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003849 // Convert to surfaceflinger's internal rotation type.
3850 Transform::orientation_flags rotationFlags;
3851 switch (rotation) {
3852 case ISurfaceComposer::eRotateNone:
3853 rotationFlags = Transform::ROT_0;
3854 break;
3855 case ISurfaceComposer::eRotate90:
3856 rotationFlags = Transform::ROT_90;
3857 break;
3858 case ISurfaceComposer::eRotate180:
3859 rotationFlags = Transform::ROT_180;
3860 break;
3861 case ISurfaceComposer::eRotate270:
3862 rotationFlags = Transform::ROT_270;
3863 break;
3864 default:
3865 rotationFlags = Transform::ROT_0;
3866 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3867 break;
3868 }
3869
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003870 class MessageCaptureScreen : public MessageBase {
3871 SurfaceFlinger* flinger;
3872 sp<IBinder> display;
3873 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003874 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003875 uint32_t reqWidth, reqHeight;
3876 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003877 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003878 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003879 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003880 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003881 public:
3882 MessageCaptureScreen(SurfaceFlinger* flinger,
3883 const sp<IBinder>& display,
3884 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003885 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003886 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003887 bool useIdentityTransform,
3888 Transform::orientation_flags rotation,
3889 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003890 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003891 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003892 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003893 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003894 rotation(rotation), result(PERMISSION_DENIED),
3895 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003896 {
3897 }
3898 status_t getResult() const {
3899 return result;
3900 }
3901 virtual bool handler() {
3902 Mutex::Autolock _l(flinger->mStateLock);
3903 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003904 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003905 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003906 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003907 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003908 return true;
3909 }
3910 };
3911
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003912 // this creates a "fake" BBinder which will serve as a "fake" remote
3913 // binder to receive the marshaled calls and forward them to the
3914 // real remote (a BpGraphicBufferProducer)
3915 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3916
3917 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3918 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003919 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003920 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003921 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003922 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003923
3924 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003925 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003926 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003927 }
3928 return res;
3929}
3930
Mathias Agopian180f10d2013-04-10 22:55:41 -07003931
3932void SurfaceFlinger::renderScreenImplLocked(
3933 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003934 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003935 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003936 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003937{
3938 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003939 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003940
3941 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003942 const int32_t hw_w = hw->getWidth();
3943 const int32_t hw_h = hw->getHeight();
3944 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003945 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003946
Dan Stozac1879002014-05-22 15:59:05 -07003947 // if a default or invalid sourceCrop is passed in, set reasonable values
3948 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3949 !sourceCrop.isValid()) {
3950 sourceCrop.setLeftTop(Point(0, 0));
3951 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3952 }
3953
3954 // ensure that sourceCrop is inside screen
3955 if (sourceCrop.left < 0) {
3956 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3957 }
Dan Stozabe31f442014-06-11 11:20:54 -07003958 if (sourceCrop.right > hw_w) {
3959 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003960 }
3961 if (sourceCrop.top < 0) {
3962 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3963 }
Dan Stozabe31f442014-06-11 11:20:54 -07003964 if (sourceCrop.bottom > hw_h) {
3965 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003966 }
3967
Mathias Agopian180f10d2013-04-10 22:55:41 -07003968 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003969 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003970
3971 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003972 engine.setViewportAndProjection(
3973 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003974 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003975
3976 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003977 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003978
Robert Carr1f0a16a2016-10-24 16:27:39 -07003979 // We loop through the first level of layers without traversing,
3980 // as we need to interpret min/max layer Z in the top level Z space.
3981 for (const auto& layer : mDrawingState.layersSortedByZ) {
3982 if (layer->getLayerStack() != hw->getLayerStack()) {
3983 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003984 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003985 const Layer::State& state(layer->getDrawingState());
3986 if (state.z < minLayerZ || state.z > maxLayerZ) {
3987 continue;
3988 }
3989 layer->traverseInZOrder([&](Layer* layer) {
3990 if (!layer->isVisible()) {
3991 return;
3992 }
3993 if (filtering) layer->setFiltering(true);
3994 layer->draw(hw, useIdentityTransform);
3995 if (filtering) layer->setFiltering(false);
3996 });
3997 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003998
Mathias Agopian931bda12013-08-28 18:11:46 -07003999 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004000}
4001
4002
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004003status_t SurfaceFlinger::captureScreenImplLocked(
4004 const sp<const DisplayDevice>& hw,
4005 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004006 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004007 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004008 bool useIdentityTransform, Transform::orientation_flags rotation,
4009 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004010{
4011 ATRACE_CALL();
4012
Mathias Agopian180f10d2013-04-10 22:55:41 -07004013 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004014 uint32_t hw_w = hw->getWidth();
4015 uint32_t hw_h = hw->getHeight();
4016
4017 if (rotation & Transform::ROT_90) {
4018 std::swap(hw_w, hw_h);
4019 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004020
Mathias Agopian180f10d2013-04-10 22:55:41 -07004021 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4022 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4023 reqWidth, reqHeight, hw_w, hw_h);
4024 return BAD_VALUE;
4025 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004026
Mathias Agopian180f10d2013-04-10 22:55:41 -07004027 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4028 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4029
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004030 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004031 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004032 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004033 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4034 (state.z < minLayerZ || state.z > maxLayerZ)) {
4035 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004036 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004037 layer->traverseInZOrder([&](Layer *layer) {
4038 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4039 layer->isSecure());
4040 });
4041 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004042
4043 if (!isLocalScreenshot && secureLayerIsVisible) {
4044 ALOGW("FB is protected: PERMISSION_DENIED");
4045 return PERMISSION_DENIED;
4046 }
4047
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004048 // create a surface (because we're a producer, and we need to
4049 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004050 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004051
4052 // Put the screenshot Surface into async mode so that
4053 // Layer::headFenceHasSignaled will always return true and we'll latch the
4054 // first buffer regardless of whether or not its acquire fence has
4055 // signaled. This is needed to avoid a race condition in the rotation
4056 // animation. See b/30209608
4057 sur->setAsyncMode(true);
4058
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004059 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004060
Michael Lentine5a16a622015-05-21 13:48:24 -07004061 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4062 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004063 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4064 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004065
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004066 int err = 0;
4067 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004068 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004069 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4070 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004071
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004072 if (err == NO_ERROR) {
4073 ANativeWindowBuffer* buffer;
4074 /* TODO: Once we have the sync framework everywhere this can use
4075 * server-side waits on the fence that dequeueBuffer returns.
4076 */
4077 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4078 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004079 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004080 // create an EGLImage from the buffer so we can later
4081 // turn it into a texture
4082 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4083 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4084 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004085 // this binds the given EGLImage as a framebuffer for the
4086 // duration of this scope.
4087 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4088 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004089 // this will in fact render into our dequeued buffer
4090 // via an FBO, which means we didn't have to create
4091 // an EGLSurface and therefore we're not
4092 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004093 renderScreenImplLocked(
4094 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4095 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004096
Riley Andrews86639902014-08-15 12:27:24 -07004097 // Attempt to create a sync khr object that can produce a sync point. If that
4098 // isn't available, create a non-dupable sync object in the fallback path and
4099 // wait on it directly.
4100 EGLSyncKHR sync;
4101 if (!DEBUG_SCREENSHOTS) {
4102 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004103 // native fence fd will not be populated until flush() is done.
4104 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004105 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004106 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004107 }
Riley Andrews86639902014-08-15 12:27:24 -07004108 if (sync != EGL_NO_SYNC_KHR) {
4109 // get the sync fd
4110 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4111 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4112 ALOGW("captureScreen: failed to dup sync khr object");
4113 syncFd = -1;
4114 }
4115 eglDestroySyncKHR(mEGLDisplay, sync);
4116 } else {
4117 // fallback path
4118 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4119 if (sync != EGL_NO_SYNC_KHR) {
4120 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4121 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4122 EGLint eglErr = eglGetError();
4123 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4124 ALOGW("captureScreen: fence wait timed out");
4125 } else {
4126 ALOGW_IF(eglErr != EGL_SUCCESS,
4127 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4128 }
4129 eglDestroySyncKHR(mEGLDisplay, sync);
4130 } else {
4131 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4132 }
4133 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004134 if (DEBUG_SCREENSHOTS) {
4135 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4136 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4137 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4138 hw, minLayerZ, maxLayerZ);
4139 delete [] pixels;
4140 }
4141
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004142 } else {
4143 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4144 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004145 window->cancelBuffer(window, buffer, syncFd);
4146 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004147 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004148 // destroy our image
4149 eglDestroyImageKHR(mEGLDisplay, image);
4150 } else {
4151 result = BAD_VALUE;
4152 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004153 if (buffer) {
4154 // queueBuffer takes ownership of syncFd
4155 result = window->queueBuffer(window, buffer, syncFd);
4156 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004157 }
4158 } else {
4159 result = BAD_VALUE;
4160 }
4161 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4162 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004163
Mathias Agopian74c40c02010-09-29 13:02:36 -07004164 return result;
4165}
4166
Mathias Agopiand5556842013-09-19 17:08:37 -07004167void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004168 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004169 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004170 for (size_t y=0 ; y<h ; y++) {
4171 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4172 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004173 if (p[x] != 0xFF000000) return;
4174 }
4175 }
4176 ALOGE("*** we just took a black screenshot ***\n"
4177 "requested minz=%d, maxz=%d, layerStack=%d",
4178 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004179
Robert Carr2047fae2016-11-28 14:09:09 -08004180 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004181 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004182 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004183 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4184 state.z <= maxLayerZ) {
4185 layer->traverseInZOrder([&](Layer* layer) {
4186 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4187 layer->isVisible() ? '+' : '-',
4188 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004189 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004190 i++;
4191 });
4192 }
4193 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004194 }
4195}
4196
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004197// ---------------------------------------------------------------------------
4198
Robert Carr2047fae2016-11-28 14:09:09 -08004199void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4200 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004201}
4202
Robert Carr2047fae2016-11-28 14:09:09 -08004203void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4204 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004205}
4206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004207}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004208
4209
4210#if defined(__gl_h_)
4211#error "don't include gl/gl.h in this file"
4212#endif
4213
4214#if defined(__gl2_h_)
4215#error "don't include gl2/gl2.h in this file"
4216#endif