blob: b39692c587405bb8dc33b0b29fa96d18ce288b8a [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.
132static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
133
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 Anderson3890c392016-07-25 12:48:08 -0700642 FrameEvent::GL_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
Dan Stoza9e56aa02015-11-02 13:00:03 -08001119void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1120 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1121 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1122 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001123
Dan Stoza9e56aa02015-11-02 13:00:03 -08001124 // All non-virtual displays are currently considered secure.
1125 bool isSecure = true;
1126
1127 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001128
1129 // When we're using the vr composer, the assumption is that we've
1130 // already created the IBinder object for the primary display.
1131 if (!mHwc->isUsingVrComposer()) {
1132 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1133 }
1134
Dan Stoza9e56aa02015-11-02 13:00:03 -08001135 wp<IBinder> token = mBuiltinDisplays[type];
1136
1137 sp<IGraphicBufferProducer> producer;
1138 sp<IGraphicBufferConsumer> consumer;
1139 BufferQueue::createBufferQueue(&producer, &consumer,
1140 new GraphicBufferAlloc());
1141
1142 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1143 DisplayDevice::DISPLAY_PRIMARY, consumer);
1144 sp<DisplayDevice> hw = new DisplayDevice(this,
1145 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1146 producer, mRenderEngine->getEGLConfig());
1147 mDisplays.add(token, hw);
1148 } else {
1149 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001150 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001151 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001152 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001153 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001154 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1155 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001156 }
1157 setTransactionFlags(eDisplayTransactionNeeded);
1158
Andy McFadden9e9689c2012-10-10 18:17:51 -07001159 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001160 }
Mathias Agopian86303202012-07-24 22:46:10 -07001161}
1162
Steven Thomas3cfac282017-02-06 12:29:30 -08001163void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1164 Mutex::Autolock lock(mStateLock);
1165 if (composer == mHwc) {
1166 repaintEverything();
1167 } else {
1168 // This isn't from our current hardware composer. If it's a callback
1169 // from the real composer, forward the refresh request to vr
1170 // flinger. Otherwise ignore it.
1171 if (!composer->isUsingVrComposer()) {
1172 mVrFlinger->OnHardwareComposerRefresh();
1173 }
1174 }
1175}
1176
Dan Stoza9e56aa02015-11-02 13:00:03 -08001177void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001179 getHwComposer().setVsyncEnabled(disp,
1180 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001181}
1182
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001183void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1184 for (size_t i = 0; i < layers.size(); ++i) {
1185 layers[i]->clearHwcLayers();
1186 }
1187}
1188
1189void SurfaceFlinger::resetHwc() {
1190 disableHardwareVsync(true);
1191 clearHwcLayers(mDrawingState.layersSortedByZ);
1192 clearHwcLayers(mCurrentState.layersSortedByZ);
1193 // Clear the drawing state so that the logic inside of
1194 // handleTransactionLocked will fire. It will determine the delta between
1195 // mCurrentState and mDrawingState and re-apply all changes when we make the
1196 // transition.
1197 mDrawingState.displays.clear();
1198 mDisplays.clear();
1199}
1200
1201void SurfaceFlinger::updateVrMode() {
1202 {
1203 Mutex::Autolock _l(mStateLock);
1204 bool enteringVrMode = mEnterVrMode;
1205 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1206 return;
1207 }
1208
1209 if (enteringVrMode) {
1210 // Start vrflinger thread, if it hasn't been started already.
1211 if (!mVrFlinger) {
1212 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1213 int err = mVrFlinger->Run(mHwc->getComposer());
1214 if (err != NO_ERROR) {
1215 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1216 mVrFlinger.reset();
1217 mEnterVrMode = false;
1218 return;
1219 }
1220 }
1221
1222 if (!mVrHwc) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001223 mVrHwc = new HWComposer(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001224 ALOGV("Vr HWC created");
1225 }
1226
1227 resetHwc();
1228
1229 mHwc = mVrHwc;
1230 mVrFlinger->EnterVrMode();
1231 } else {
1232 mVrFlinger->ExitVrMode();
1233
1234 resetHwc();
1235
1236 mHwc = mRealHwc;
1237 enableHardwareVsync();
1238 }
1239
1240 mVisibleRegionsDirty = true;
1241 invalidateHwcGeometry();
1242 android_atomic_or(1, &mRepaintEverything);
1243 setTransactionFlags(eDisplayTransactionNeeded);
1244 }
1245 if (mVrHwc) {
1246 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1247 }
1248}
1249
Mathias Agopian4fec8732012-06-29 14:12:52 -07001250void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001251 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001253 case MessageQueue::INVALIDATE: {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001254 updateVrMode();
1255
Dan Stoza50182882016-07-08 12:02:20 -07001256 bool frameMissed = !mHadClientComposition &&
1257 mPreviousPresentFence != Fence::NO_FENCE &&
1258 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1259 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001260 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001261 signalLayerUpdate();
1262 break;
1263 }
1264
Dan Stoza6b9454d2014-11-07 16:00:59 -08001265 bool refreshNeeded = handleMessageTransaction();
1266 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001267 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001268 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001269 // Signal a refresh if a transaction modified the window state,
1270 // a new buffer was latched, or if HWC has requested a full
1271 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001272 signalRefresh();
1273 }
1274 break;
1275 }
1276 case MessageQueue::REFRESH: {
1277 handleMessageRefresh();
1278 break;
1279 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001280 }
1281}
1282
Dan Stoza6b9454d2014-11-07 16:00:59 -08001283bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001284 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001285 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001286 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001287 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001288 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001290}
1291
Dan Stoza6b9454d2014-11-07 16:00:59 -08001292bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001293 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001294 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001295}
1296
1297void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001298 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001299
Pablo Ceballos40845df2016-01-25 17:41:15 -08001300 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001301
Brian Andersond6927fb2016-07-23 23:37:30 -07001302 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001303 rebuildLayerStacks();
1304 setUpHWComposer();
1305 doDebugFlashRegions();
1306 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001307 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001308
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001309 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001310
1311 mHadClientComposition = false;
1312 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1313 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1314 mHadClientComposition = mHadClientComposition ||
1315 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1316 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001317
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001319}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001320
Mathias Agopiancd60f992012-08-16 16:28:27 -07001321void SurfaceFlinger::doDebugFlashRegions()
1322{
1323 // is debugging enabled
1324 if (CC_LIKELY(!mDebugRegion))
1325 return;
1326
1327 const bool repaintEverything = mRepaintEverything;
1328 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1329 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001330 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001331 // transform the dirty region into this screen's coordinate space
1332 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1333 if (!dirtyRegion.isEmpty()) {
1334 // redraw the whole screen
1335 doComposeSurfaces(hw, Region(hw->bounds()));
1336
1337 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001339 RenderEngine& engine(getRenderEngine());
1340 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1341
Mathias Agopianda27af92012-09-13 18:17:13 -07001342 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001343 }
1344 }
1345 }
1346
1347 postFramebuffer();
1348
1349 if (mDebugRegion > 1) {
1350 usleep(mDebugRegion * 1000);
1351 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001352
Dan Stoza9e56aa02015-11-02 13:00:03 -08001353 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001354 auto& displayDevice = mDisplays[displayId];
1355 if (!displayDevice->isDisplayOn()) {
1356 continue;
1357 }
1358
1359 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1361 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001362 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001363}
1364
Brian Andersond6927fb2016-07-23 23:37:30 -07001365void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001366{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 ATRACE_CALL();
1368 ALOGV("preComposition");
1369
Mathias Agopiancd60f992012-08-16 16:28:27 -07001370 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001371 mDrawingState.traverseInZOrder([&](Layer* layer) {
1372 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373 needExtraInvalidate = true;
1374 }
Robert Carr2047fae2016-11-28 14:09:09 -08001375 });
1376
Mathias Agopiancd60f992012-08-16 16:28:27 -07001377 if (needExtraInvalidate) {
1378 signalLayerUpdate();
1379 }
1380}
1381
Brian Andersond6927fb2016-07-23 23:37:30 -07001382void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 ATRACE_CALL();
1385 ALOGV("postComposition");
1386
Brian Anderson3546a3f2016-07-14 11:51:14 -07001387 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001388 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001389 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001390 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001391 }
1392
Brian Andersond6927fb2016-07-23 23:37:30 -07001393 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001394
1395 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1396 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1397 glCompositionDoneFenceTime =
1398 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1399 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1400 } else {
1401 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1402 }
1403 mGlCompositionDoneTimeline.updateSignalTimes();
1404
1405 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1406 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1407 mDisplayTimeline.push(displayFenceTime);
1408 mDisplayTimeline.updateSignalTimes();
1409
1410 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1411 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1412 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1413 presentFenceTime = &displayFenceTime;
1414 } else {
1415 retireFenceTime = &displayFenceTime;
1416 }
Robert Carr2047fae2016-11-28 14:09:09 -08001417 mDrawingState.traverseInZOrder([&](Layer* layer) {
1418 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1419 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001420 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001421 recordBufferingStats(layer->getName().string(),
1422 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001423 }
Robert Carr2047fae2016-11-28 14:09:09 -08001424 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001425
Brian Anderson3d4039d2016-09-23 16:31:30 -07001426 if (displayFence->isValid()) {
1427 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001428 enableHardwareVsync();
1429 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001430 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001431 }
1432 }
1433
Andy McFadden5167ec62014-05-22 13:08:43 -07001434 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001435 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001436 enableHardwareVsync();
1437 }
1438 }
1439
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001440 if (mAnimCompositionPending) {
1441 mAnimCompositionPending = false;
1442
Brian Anderson3d4039d2016-09-23 16:31:30 -07001443 if (displayFenceTime->isValid()) {
1444 mAnimFrameTracker.setActualPresentFence(
1445 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001446 } else {
1447 // The HWC doesn't support present fences, so use the refresh
1448 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001449 nsecs_t presentTime =
1450 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001451 mAnimFrameTracker.setActualPresentTime(presentTime);
1452 }
1453 mAnimFrameTracker.advanceFrame();
1454 }
Dan Stozab90cf072015-03-05 11:05:59 -08001455
1456 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1457 return;
1458 }
1459
1460 nsecs_t currentTime = systemTime();
1461 if (mHasPoweredOff) {
1462 mHasPoweredOff = false;
1463 } else {
1464 nsecs_t period = mPrimaryDispSync.getPeriod();
1465 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1466 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1467 if (numPeriods < NUM_BUCKETS - 1) {
1468 mFrameBuckets[numPeriods] += elapsedTime;
1469 } else {
1470 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1471 }
1472 mTotalTime += elapsedTime;
1473 }
1474 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475}
1476
1477void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478 ATRACE_CALL();
1479 ALOGV("rebuildLayerStacks");
1480
Mathias Agopiancd60f992012-08-16 16:28:27 -07001481 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001482 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001484 mVisibleRegionsDirty = false;
1485 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001486
Mathias Agopian92a979a2012-08-02 18:32:23 -07001487 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001488 Region opaqueRegion;
1489 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001490 Vector<sp<Layer>> layersSortedByZ;
1491 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1492 const Transform& tr(displayDevice->getTransform());
1493 const Rect bounds(displayDevice->getBounds());
1494 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001495 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 displayDevice->getLayerStack(), dirtyRegion,
1497 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001498
Robert Carr2047fae2016-11-28 14:09:09 -08001499 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001500 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001501 Region drawRegion(tr.transform(
1502 layer->visibleNonTransparentRegion));
1503 drawRegion.andSelf(bounds);
1504 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001505 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 } else {
1507 // Clear out the HWC layer if this layer was
1508 // previously visible, but no longer is
1509 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1510 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001511 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001512 }
Robert Carr2047fae2016-11-28 14:09:09 -08001513 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001514 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001515 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1516 displayDevice->undefinedRegion.set(bounds);
1517 displayDevice->undefinedRegion.subtractSelf(
1518 tr.transform(opaqueRegion));
1519 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001520 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001521 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001523
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 ATRACE_CALL();
1526 ALOGV("setUpHWComposer");
1527
Jesse Hall028dc8f2013-08-20 16:35:32 -07001528 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001529 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1530 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1531 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1532
1533 // If nothing has changed (!dirty), don't recompose.
1534 // If something changed, but we don't currently have any visible layers,
1535 // and didn't when we last did a composition, then skip it this time.
1536 // The second rule does two things:
1537 // - When all layers are removed from a display, we'll emit one black
1538 // frame, then nothing more until we get new layers.
1539 // - When a display is created with a private layer stack, we won't
1540 // emit any black frames until a layer is added to the layer stack.
1541 bool mustRecompose = dirty && !(empty && wasEmpty);
1542
1543 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1544 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1545 mustRecompose ? "doing" : "skipping",
1546 dirty ? "+" : "-",
1547 empty ? "+" : "-",
1548 wasEmpty ? "+" : "-");
1549
Dan Stoza71433162014-02-04 16:22:36 -08001550 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001551
1552 if (mustRecompose) {
1553 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1554 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001555 }
1556
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 // build the h/w work list
1558 if (CC_UNLIKELY(mGeometryInvalid)) {
1559 mGeometryInvalid = false;
1560 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1561 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1562 const auto hwcId = displayDevice->getHwcDisplayId();
1563 if (hwcId >= 0) {
1564 const Vector<sp<Layer>>& currentLayers(
1565 displayDevice->getVisibleLayersSortedByZ());
1566 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001567 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001568 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001569 if (!layer->hasHwcLayer(hwcId)) {
1570 auto hwcLayer = mHwc->createLayer(hwcId);
1571 if (hwcLayer) {
1572 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1573 } else {
1574 layer->forceClientComposition(hwcId);
1575 foundLayerWithoutHwc = true;
1576 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001577 }
1578 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001579
Robert Carrae060832016-11-28 10:51:00 -08001580 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001581 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001583 }
1584 }
1585 }
1586 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001587 }
Riley Andrews03414a12014-07-01 14:22:59 -07001588
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001589
1590 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1591
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 // Set the per-frame data
1593 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1594 auto& displayDevice = mDisplays[displayId];
1595 const auto hwcId = displayDevice->getHwcDisplayId();
1596 if (hwcId < 0) {
1597 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001598 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001599 if (colorMatrix != mPreviousColorMatrix) {
1600 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1601 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1602 "display %zd: %d", displayId, result);
1603 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001604 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1605 layer->setPerFrameData(displayDevice);
1606 }
1607 }
1608
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001609 mPreviousColorMatrix = colorMatrix;
1610
Dan Stoza9e56aa02015-11-02 13:00:03 -08001611 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001612 auto& displayDevice = mDisplays[displayId];
1613 if (!displayDevice->isDisplayOn()) {
1614 continue;
1615 }
1616
1617 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1619 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001620 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001622
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623void SurfaceFlinger::doComposition() {
1624 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001625 ALOGV("doComposition");
1626
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001627 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001628 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001629 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001630 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631 // transform the dirty region into this screen's coordinate space
1632 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001633
1634 // repaint the framebuffer (if needed)
1635 doDisplayComposition(hw, dirtyRegion);
1636
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637 hw->dirtyRegion.clear();
1638 hw->flip(hw->swapRegion);
1639 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001640 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001641 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001642 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001643}
1644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645void SurfaceFlinger::postFramebuffer()
1646{
Mathias Agopian841cde52012-03-01 15:44:37 -08001647 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001649
Mathias Agopiana44b0412011-10-16 18:46:35 -07001650 const nsecs_t now = systemTime();
1651 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001652
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1654 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001655 if (!displayDevice->isDisplayOn()) {
1656 continue;
1657 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 const auto hwcId = displayDevice->getHwcDisplayId();
1659 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001660 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001661 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001662 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001663 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1665 sp<Fence> releaseFence = Fence::NO_FENCE;
1666 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1667 releaseFence = displayDevice->getClientTargetAcquireFence();
1668 } else {
1669 auto hwcLayer = layer->getHwcLayer(hwcId);
1670 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 layer->onLayerDisplayed(releaseFence);
1673 }
1674 if (hwcId >= 0) {
1675 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001676 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001677 }
1678
Mathias Agopiana44b0412011-10-16 18:46:35 -07001679 mLastSwapBufferTime = systemTime() - now;
1680 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001681
1682 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1683 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1684 logFrameStats();
1685 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001686}
1687
Mathias Agopian87baae12012-07-31 12:38:26 -07001688void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001689{
Mathias Agopian841cde52012-03-01 15:44:37 -08001690 ATRACE_CALL();
1691
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001692 // here we keep a copy of the drawing state (that is the state that's
1693 // going to be overwritten by handleTransactionLocked()) outside of
1694 // mStateLock so that the side-effects of the State assignment
1695 // don't happen with mStateLock held (which can cause deadlocks).
1696 State drawingState(mDrawingState);
1697
Mathias Agopianca4d3602011-05-19 15:38:14 -07001698 Mutex::Autolock _l(mStateLock);
1699 const nsecs_t now = systemTime();
1700 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001701
Mathias Agopianca4d3602011-05-19 15:38:14 -07001702 // Here we're guaranteed that some transaction flags are set
1703 // so we can call handleTransactionLocked() unconditionally.
1704 // We call getTransactionFlags(), which will also clear the flags,
1705 // with mStateLock held to guarantee that mCurrentState won't change
1706 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001707
Mathias Agopiane57f2922012-08-09 16:29:12 -07001708 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001709 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001710
Mathias Agopianca4d3602011-05-19 15:38:14 -07001711 mLastTransactionTime = systemTime() - now;
1712 mDebugInTransaction = 0;
1713 invalidateHwcGeometry();
1714 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001715}
1716
Mathias Agopian87baae12012-07-31 12:38:26 -07001717void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001718{
Dan Stoza7dde5992015-05-22 09:51:44 -07001719 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001720 mCurrentState.traverseInZOrder([](Layer* layer) {
1721 layer->notifyAvailableFrames();
1722 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001724 /*
1725 * Traversal of the children
1726 * (perform the transaction for each of them if needed)
1727 */
1728
Mathias Agopian3559b072012-08-15 13:46:03 -07001729 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001730 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001731 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001732 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001733
1734 const uint32_t flags = layer->doTransaction(0);
1735 if (flags & Layer::eVisibleRegion)
1736 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001737 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001738 }
1739
1740 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001741 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001742 */
1743
Mathias Agopiane57f2922012-08-09 16:29:12 -07001744 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001745 // here we take advantage of Vector's copy-on-write semantics to
1746 // improve performance by skipping the transaction entirely when
1747 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001748 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1749 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001750 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001752 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001753 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001754
1755 // find the displays that were removed
1756 // (ie: in drawing state but not in current state)
1757 // also handle displays that changed
1758 // (ie: displays that are in both lists)
1759 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001760 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1761 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001762 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001763 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001764 // Call makeCurrent() on the primary display so we can
1765 // be sure that nothing associated with this display
1766 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001767 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001768 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001769 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1770 if (hw != NULL)
1771 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001772 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001773 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001774 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001775 } else {
1776 ALOGW("trying to remove the main display");
1777 }
1778 } else {
1779 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001780 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001781 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001782 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1783 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001784 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001785 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001786 // recreating the DisplayDevice, so we just remove it
1787 // from the drawing state, so that it get re-added
1788 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001789 sp<DisplayDevice> hw(getDisplayDevice(display));
1790 if (hw != NULL)
1791 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001792 mDisplays.removeItem(display);
1793 mDrawingState.displays.removeItemsAt(i);
1794 dc--; i--;
1795 // at this point we must loop to the next item
1796 continue;
1797 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001798
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001799 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001800 if (disp != NULL) {
1801 if (state.layerStack != draw[i].layerStack) {
1802 disp->setLayerStack(state.layerStack);
1803 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001804 if ((state.orientation != draw[i].orientation)
1805 || (state.viewport != draw[i].viewport)
1806 || (state.frame != draw[i].frame))
1807 {
1808 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001809 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001810 }
Michael Lentine47e45402014-07-18 15:34:25 -07001811 if (state.width != draw[i].width || state.height != draw[i].height) {
1812 disp->setDisplaySize(state.width, state.height);
1813 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001814 }
1815 }
1816 }
1817
1818 // find displays that were added
1819 // (ie: in current state but not in drawing state)
1820 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001821 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001822 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001823
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001824 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001825 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001826 sp<IGraphicBufferProducer> bqProducer;
1827 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001828 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1829 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001830
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001832 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001833 // Virtual displays without a surface are dormant:
1834 // they have external state (layer stack, projection,
1835 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001836 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001837
Dan Stoza8cf150a2016-08-02 10:27:31 -07001838 if (mUseHwcVirtualDisplays) {
1839 int width = 0;
1840 int status = state.surface->query(
1841 NATIVE_WINDOW_WIDTH, &width);
1842 ALOGE_IF(status != NO_ERROR,
1843 "Unable to query width (%d)", status);
1844 int height = 0;
1845 status = state.surface->query(
1846 NATIVE_WINDOW_HEIGHT, &height);
1847 ALOGE_IF(status != NO_ERROR,
1848 "Unable to query height (%d)", status);
1849 int intFormat = 0;
1850 status = state.surface->query(
1851 NATIVE_WINDOW_FORMAT, &intFormat);
1852 ALOGE_IF(status != NO_ERROR,
1853 "Unable to query format (%d)", status);
1854 auto format = static_cast<android_pixel_format_t>(
1855 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001856
Dan Stoza8cf150a2016-08-02 10:27:31 -07001857 mHwc->allocateVirtualDisplay(width, height, &format,
1858 &hwcId);
1859 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860
Dan Stoza5cf424b2016-05-20 14:02:39 -07001861 // TODO: Plumb requested format back up to consumer
1862
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 sp<VirtualDisplaySurface> vds =
1864 new VirtualDisplaySurface(*mHwc,
1865 hwcId, state.surface, bqProducer,
1866 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001867
1868 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001869 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001870 }
1871 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001872 ALOGE_IF(state.surface!=NULL,
1873 "adding a supported display, but rendering "
1874 "surface is provided (%p), ignoring it",
1875 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001876
1877 hwcId = state.type;
1878 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1879 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001880 }
1881
1882 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001883 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001884 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 state.type, hwcId, state.isSecure, display,
1886 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001887 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001888 hw->setLayerStack(state.layerStack);
1889 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001890 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001891 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001892 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001894 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001895 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001896 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001897 }
1898 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001900 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001901
Mathias Agopian84300952012-11-21 16:02:13 -08001902 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1903 // The transform hint might have changed for some layers
1904 // (either because a display has changed, or because a layer
1905 // as changed).
1906 //
1907 // Walk through all the layers in currentLayers,
1908 // and update their transform hint.
1909 //
1910 // If a layer is visible only on a single display, then that
1911 // display is used to calculate the hint, otherwise we use the
1912 // default display.
1913 //
1914 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1915 // the hint is set before we acquire a buffer from the surface texture.
1916 //
1917 // NOTE: layer transactions have taken place already, so we use their
1918 // drawing state. However, SurfaceFlinger's own transaction has not
1919 // happened yet, so we must use the current state layer list
1920 // (soon to become the drawing state list).
1921 //
1922 sp<const DisplayDevice> disp;
1923 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001924 bool first = true;
1925 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001926 // NOTE: we rely on the fact that layers are sorted by
1927 // layerStack first (so we don't have to traverse the list
1928 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001929 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001930 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001931 currentlayerStack = layerStack;
1932 // figure out if this layerstack is mirrored
1933 // (more than one display) if so, pick the default display,
1934 // if not, pick the only display it's on.
1935 disp.clear();
1936 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1937 sp<const DisplayDevice> hw(mDisplays[dpy]);
1938 if (hw->getLayerStack() == currentlayerStack) {
1939 if (disp == NULL) {
1940 disp = hw;
1941 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001942 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001943 break;
1944 }
1945 }
1946 }
1947 }
Chet Haase91d25932013-04-11 15:24:55 -07001948 if (disp == NULL) {
1949 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1950 // redraw after transform hint changes. See bug 8508397.
1951
1952 // could be null when this layer is using a layerStack
1953 // that is not visible on any display. Also can occur at
1954 // screen off/on times.
1955 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001956 }
Chet Haase91d25932013-04-11 15:24:55 -07001957 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001958
1959 first = false;
1960 });
Mathias Agopian84300952012-11-21 16:02:13 -08001961 }
1962
1963
Mathias Agopian3559b072012-08-15 13:46:03 -07001964 /*
1965 * Perform our own transaction if needed
1966 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001967
1968 if (mLayersAdded) {
1969 mLayersAdded = false;
1970 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001971 mVisibleRegionsDirty = true;
1972 }
1973
1974 // some layers might have been removed, so
1975 // we need to update the regions they're exposing.
1976 if (mLayersRemoved) {
1977 mLayersRemoved = false;
1978 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001979 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001980 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001981 // this layer is not visible anymore
1982 // TODO: we could traverse the tree from front to back and
1983 // compute the actual visible region
1984 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001985 Region visibleReg;
1986 visibleReg.set(layer->computeScreenBounds());
1987 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001988 }
Robert Carr2047fae2016-11-28 14:09:09 -08001989 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990 }
1991
1992 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001993
1994 updateCursorAsync();
1995}
1996
1997void SurfaceFlinger::updateCursorAsync()
1998{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2000 auto& displayDevice = mDisplays[displayId];
2001 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002002 continue;
2003 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004
2005 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2006 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002007 }
2008 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009}
2010
2011void SurfaceFlinger::commitTransaction()
2012{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002013 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002015 for (const auto& l : mLayersPendingRemoval) {
2016 recordBufferingStats(l->getName().string(),
2017 l->getOccupancyHistory(true));
2018 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002019 }
2020 mLayersPendingRemoval.clear();
2021 }
2022
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002023 // If this transaction is part of a window animation then the next frame
2024 // we composite should be considered an animation as well.
2025 mAnimCompositionPending = mAnimTransactionPending;
2026
Mathias Agopian4fec8732012-06-29 14:12:52 -07002027 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002028 mDrawingState.traverseInZOrder([](Layer* layer) {
2029 layer->commitChildList();
2030 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002031 mTransactionPending = false;
2032 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002034}
2035
Robert Carr2047fae2016-11-28 14:09:09 -08002036void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002037 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038{
Mathias Agopian841cde52012-03-01 15:44:37 -08002039 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042 Region aboveOpaqueLayers;
2043 Region aboveCoveredLayers;
2044 Region dirty;
2045
Mathias Agopian87baae12012-07-31 12:38:26 -07002046 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047
Robert Carr2047fae2016-11-28 14:09:09 -08002048 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002050 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051
Jesse Hall01e29052013-02-19 16:13:35 -08002052 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002053 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002054 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002055
Mathias Agopianab028732010-03-16 16:41:46 -07002056 /*
2057 * opaqueRegion: area of a surface that is fully opaque.
2058 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002060
2061 /*
2062 * visibleRegion: area of a surface that is visible on screen
2063 * and not fully transparent. This is essentially the layer's
2064 * footprint minus the opaque regions above it.
2065 * Areas covered by a translucent surface are considered visible.
2066 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002068
2069 /*
2070 * coveredRegion: area of a surface that is covered by all
2071 * visible regions above it (which includes the translucent areas).
2072 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002073 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002074
Jesse Halla8026d22012-09-25 13:25:04 -07002075 /*
2076 * transparentRegion: area of a surface that is hinted to be completely
2077 * transparent. This is only used to tell when the layer has no visible
2078 * non-transparent regions and can be removed from the layer list. It
2079 * does not affect the visibleRegion of this layer or any layers
2080 * beneath it. The hint may not be correct if apps don't respect the
2081 * SurfaceView restrictions (which, sadly, some don't).
2082 */
2083 Region transparentRegion;
2084
Mathias Agopianab028732010-03-16 16:41:46 -07002085
2086 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002087 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002088 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002089 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002091 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002092 if (!visibleRegion.isEmpty()) {
2093 // Remove the transparent area from the visible region
2094 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002095 if (tr.preserveRects()) {
2096 // transform the transparent region
2097 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002099 // transformation too complex, can't do the
2100 // transparent region optimization.
2101 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102 }
Mathias Agopianab028732010-03-16 16:41:46 -07002103 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104
Mathias Agopianab028732010-03-16 16:41:46 -07002105 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002106 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002108 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2109 // the opaque region is the layer's footprint
2110 opaqueRegion = visibleRegion;
2111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112 }
2113 }
2114
Mathias Agopianab028732010-03-16 16:41:46 -07002115 // Clip the covered region to the visible region
2116 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2117
2118 // Update aboveCoveredLayers for next (lower) layer
2119 aboveCoveredLayers.orSelf(visibleRegion);
2120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 // subtract the opaque region covered by the layers above us
2122 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123
2124 // compute this layer's dirty region
2125 if (layer->contentDirty) {
2126 // we need to invalidate the whole region
2127 dirty = visibleRegion;
2128 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002129 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130 layer->contentDirty = false;
2131 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002132 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002133 * the exposed region consists of two components:
2134 * 1) what's VISIBLE now and was COVERED before
2135 * 2) what's EXPOSED now less what was EXPOSED before
2136 *
2137 * note that (1) is conservative, we start with the whole
2138 * visible region but only keep what used to be covered by
2139 * something -- which mean it may have been exposed.
2140 *
2141 * (2) handles areas that were not covered by anything but got
2142 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002143 */
Mathias Agopianab028732010-03-16 16:41:46 -07002144 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002145 const Region oldVisibleRegion = layer->visibleRegion;
2146 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002147 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2148 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 }
2150 dirty.subtractSelf(aboveOpaqueLayers);
2151
2152 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002153 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154
Mathias Agopianab028732010-03-16 16:41:46 -07002155 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002157
Jesse Halla8026d22012-09-25 13:25:04 -07002158 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159 layer->setVisibleRegion(visibleRegion);
2160 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002161 layer->setVisibleNonTransparentRegion(
2162 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002163 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164
Mathias Agopian87baae12012-07-31 12:38:26 -07002165 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166}
2167
Mathias Agopian87baae12012-07-31 12:38:26 -07002168void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2169 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002170 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002171 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2172 if (hw->getLayerStack() == layerStack) {
2173 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002174 }
2175 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002176}
2177
Dan Stoza6b9454d2014-11-07 16:00:59 -08002178bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 ALOGV("handlePageFlip");
2181
Brian Andersond6927fb2016-07-23 23:37:30 -07002182 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183
Mathias Agopian4fec8732012-06-29 14:12:52 -07002184 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002185 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002186
2187 // Store the set of layers that need updates. This set must not change as
2188 // buffers are being latched, as this could result in a deadlock.
2189 // Example: Two producers share the same command stream and:
2190 // 1.) Layer 0 is latched
2191 // 2.) Layer 0 gets a new frame
2192 // 2.) Layer 1 gets a new frame
2193 // 3.) Layer 1 is latched.
2194 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2195 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002196 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002197 if (layer->hasQueuedFrame()) {
2198 frameQueued = true;
2199 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002200 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002201 } else {
2202 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002203 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002204 } else {
2205 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002206 }
Robert Carr2047fae2016-11-28 14:09:09 -08002207 });
2208
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002210 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002211 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002212 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002213 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002214
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002215 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002216
2217 // If we will need to wake up at some time in the future to deal with a
2218 // queued frame that shouldn't be displayed during this vsync period, wake
2219 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002221 signalLayerUpdate();
2222 }
2223
2224 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226}
2227
Mathias Agopianad456f92011-01-13 17:53:01 -08002228void SurfaceFlinger::invalidateHwcGeometry()
2229{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002231}
2232
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002233
Fabien Sanglard830b8472016-11-30 16:35:58 -08002234void SurfaceFlinger::doDisplayComposition(
2235 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002236 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237{
Dan Stoza71433162014-02-04 16:22:36 -08002238 // We only need to actually compose the display if:
2239 // 1) It is being handled by hardware composer, which may need this to
2240 // keep its virtual display state machine in sync, or
2241 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002242 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002243 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002245 return;
2246 }
2247
Dan Stoza9e56aa02015-11-02 13:00:03 -08002248 ALOGV("doDisplayComposition");
2249
Mathias Agopian87baae12012-07-31 12:38:26 -07002250 Region dirtyRegion(inDirtyRegion);
2251
Mathias Agopianb8a55602009-06-26 19:06:36 -07002252 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002253 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254
Fabien Sanglard830b8472016-11-30 16:35:58 -08002255 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002256 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002257 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2258 // takes a rectangle, we must make sure to update that whole
2259 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002260 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002261 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002262 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002263 // We need to redraw the rectangle that will be updated
2264 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002265 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002266 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002267 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002268 } else {
2269 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002270 dirtyRegion.set(displayDevice->bounds());
2271 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272 }
2273 }
2274
Fabien Sanglard830b8472016-11-30 16:35:58 -08002275 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002277 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002278 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002279
2280 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002281 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282}
2283
Dan Stoza9e56aa02015-11-02 13:00:03 -08002284bool SurfaceFlinger::doComposeSurfaces(
2285 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002286{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002288
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002290
2291 mat4 oldColorMatrix;
2292 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2293 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2294 if (applyColorMatrix) {
2295 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2296 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2297 }
2298
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2300 if (hasClientComposition) {
2301 ALOGV("hasClientComposition");
2302
2303 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002304 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002306 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2307 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2308 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2309 }
2310 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002311 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002312
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002313 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2315 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002316 // when using overlays, we assume a fully transparent framebuffer
2317 // NOTE: we could reduce how much we need to clear, for instance
2318 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002319 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002320 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002321 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002322 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002323 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002325
2326 // we remove the scissor part
2327 // we're left with the letterbox region
2328 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002329 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002330
2331 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002333
2334 // but limit it to the dirty region
2335 region.andSelf(dirty);
2336
Mathias Agopianb9494d52012-04-18 02:28:45 -07002337 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002338 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002339 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002340 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002341 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002342 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002343
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002345 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002346 // scissor on the main display. It should never be needed
2347 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002348 const Rect& bounds(displayDevice->getBounds());
2349 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002350 if (scissor != bounds) {
2351 // scissor doesn't match the screen's dimensions, so we
2352 // need to clear everything outside of it and enable
2353 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002354
Mathias Agopianf45c5102012-10-24 16:29:17 -07002355 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002356 const uint32_t height = displayDevice->getHeight();
2357 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002358 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002359 }
2360 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002361 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002362
Mathias Agopian85d751c2012-08-29 16:59:24 -07002363 /*
2364 * and then, render the layers targeted at the framebuffer
2365 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002366
Dan Stoza9e56aa02015-11-02 13:00:03 -08002367 ALOGV("Rendering client layers");
2368 const Transform& displayTransform = displayDevice->getTransform();
2369 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002370 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 bool firstLayer = true;
2372 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2373 const Region clip(dirty.intersect(
2374 displayTransform.transform(layer->visibleRegion)));
2375 ALOGV("Layer: %s", layer->getName().string());
2376 ALOGV(" Composition type: %s",
2377 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002378 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002379 switch (layer->getCompositionType(hwcId)) {
2380 case HWC2::Composition::Cursor:
2381 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002382 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002383 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002384 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002385 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2386 layer->isOpaque(state) && (state.alpha == 1.0f)
2387 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002388 // never clear the very first layer since we're
2389 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002390 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002391 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002392 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002393 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 case HWC2::Composition::Client: {
2395 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002396 break;
2397 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002399 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002400 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 } else {
2402 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002403 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002405 }
2406 } else {
2407 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002409 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002411 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002413 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002414 }
2415 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002416
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002417 if (applyColorMatrix) {
2418 getRenderEngine().setupColorTransform(oldColorMatrix);
2419 }
2420
Mathias Agopianf45c5102012-10-24 16:29:17 -07002421 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002423 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424}
2425
Fabien Sanglard830b8472016-11-30 16:35:58 -08002426void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2427 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002428 RenderEngine& engine(getRenderEngine());
2429 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430}
2431
Dan Stoza7d89d062015-04-30 13:29:25 -07002432status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002433 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002434 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002435 const sp<Layer>& lbc,
2436 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002437{
Dan Stoza7d89d062015-04-30 13:29:25 -07002438 // add this layer to the current state list
2439 {
2440 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002441 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002442 return NO_MEMORY;
2443 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002444 if (parent == nullptr) {
2445 mCurrentState.layersSortedByZ.add(lbc);
2446 } else {
2447 parent->addChild(lbc);
2448 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002449 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 mLayersAdded = true;
2451 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002452 }
2453
Mathias Agopian96f08192010-06-02 23:28:45 -07002454 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002455 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002456
Dan Stoza7d89d062015-04-30 13:29:25 -07002457 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002458}
2459
Dan Stoza22851c32016-08-09 13:21:03 -07002460status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002462 sp<Layer> layer = weakLayer.promote();
2463 if (layer == nullptr) {
2464 // The layer has already been removed, carry on
2465 return NO_ERROR;
2466 }
2467
Robert Carr1f0a16a2016-10-24 16:27:39 -07002468 const auto& p = layer->getParent();
2469 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2470 mCurrentState.layersSortedByZ.remove(layer);
2471
2472 if (index < 0) {
2473 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2474 layer->getName().string(),
2475 (p != nullptr) ? p->getName().string() : "no-parent");
2476 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002477 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002478
2479 mLayersPendingRemoval.add(layer);
2480 mLayersRemoved = true;
2481 mNumLayers--;
2482 setTransactionFlags(eTransactionNeeded);
2483 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484}
2485
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002486uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002487 return android_atomic_release_load(&mTransactionFlags);
2488}
2489
Mathias Agopian3f844832013-08-07 21:24:32 -07002490uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2492}
2493
Mathias Agopian3f844832013-08-07 21:24:32 -07002494uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2496 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002497 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 }
2499 return old;
2500}
2501
Mathias Agopian8b33f032012-07-24 20:43:54 -07002502void SurfaceFlinger::setTransactionState(
2503 const Vector<ComposerState>& state,
2504 const Vector<DisplayState>& displays,
2505 uint32_t flags)
2506{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002507 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002508 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002509 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002510
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002511 if (flags & eAnimation) {
2512 // For window updates that are part of an animation we must wait for
2513 // previous animation "frames" to be handled.
2514 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002515 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002516 if (CC_UNLIKELY(err != NO_ERROR)) {
2517 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002518 // caller after a few seconds.
2519 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2520 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002521 mAnimTransactionPending = false;
2522 break;
2523 }
2524 }
2525 }
2526
Mathias Agopiane57f2922012-08-09 16:29:12 -07002527 size_t count = displays.size();
2528 for (size_t i=0 ; i<count ; i++) {
2529 const DisplayState& s(displays[i]);
2530 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002531 }
2532
Mathias Agopiane57f2922012-08-09 16:29:12 -07002533 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002534 for (size_t i=0 ; i<count ; i++) {
2535 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002536 // Here we need to check that the interface we're given is indeed
2537 // one of our own. A malicious client could give us a NULL
2538 // IInterface, or one of its own or even one of our own but a
2539 // different type. All these situations would cause us to crash.
2540 //
2541 // NOTE: it would be better to use RTTI as we could directly check
2542 // that we have a Client*. however, RTTI is disabled in Android.
2543 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002544 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002545 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002546 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002547 sp<Client> client( static_cast<Client *>(s.client.get()) );
2548 transactionFlags |= setClientStateLocked(client, s.state);
2549 }
2550 }
2551 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002552 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002553
Robert Carr2a7dbb42016-05-24 11:41:28 -07002554 // If a synchronous transaction is explicitly requested without any changes,
2555 // force a transaction anyway. This can be used as a flush mechanism for
2556 // previous async transactions.
2557 if (transactionFlags == 0 && (flags & eSynchronous)) {
2558 transactionFlags = eTransactionNeeded;
2559 }
2560
Mathias Agopian386aa982011-11-07 21:58:03 -08002561 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002562 if (mInterceptor.isEnabled()) {
2563 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2564 }
Irvel468051e2016-06-13 16:44:44 -07002565
Mathias Agopian386aa982011-11-07 21:58:03 -08002566 // this triggers the transaction
2567 setTransactionFlags(transactionFlags);
2568
2569 // if this is a synchronous transaction, wait for it to take effect
2570 // before returning.
2571 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002572 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002573 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002574 if (flags & eAnimation) {
2575 mAnimTransactionPending = true;
2576 }
2577 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002578 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2579 if (CC_UNLIKELY(err != NO_ERROR)) {
2580 // just in case something goes wrong in SF, return to the
2581 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002582 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2583 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002584 break;
2585 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588}
2589
Mathias Agopiane57f2922012-08-09 16:29:12 -07002590uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2591{
Jesse Hall9a143922012-10-04 16:29:19 -07002592 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2593 if (dpyIdx < 0)
2594 return 0;
2595
Mathias Agopiane57f2922012-08-09 16:29:12 -07002596 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002597 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002598 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002599 const uint32_t what = s.what;
2600 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002601 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002602 disp.surface = s.surface;
2603 flags |= eDisplayTransactionNeeded;
2604 }
2605 }
2606 if (what & DisplayState::eLayerStackChanged) {
2607 if (disp.layerStack != s.layerStack) {
2608 disp.layerStack = s.layerStack;
2609 flags |= eDisplayTransactionNeeded;
2610 }
2611 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002612 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002613 if (disp.orientation != s.orientation) {
2614 disp.orientation = s.orientation;
2615 flags |= eDisplayTransactionNeeded;
2616 }
2617 if (disp.frame != s.frame) {
2618 disp.frame = s.frame;
2619 flags |= eDisplayTransactionNeeded;
2620 }
2621 if (disp.viewport != s.viewport) {
2622 disp.viewport = s.viewport;
2623 flags |= eDisplayTransactionNeeded;
2624 }
2625 }
Michael Lentine47e45402014-07-18 15:34:25 -07002626 if (what & DisplayState::eDisplaySizeChanged) {
2627 if (disp.width != s.width) {
2628 disp.width = s.width;
2629 flags |= eDisplayTransactionNeeded;
2630 }
2631 if (disp.height != s.height) {
2632 disp.height = s.height;
2633 flags |= eDisplayTransactionNeeded;
2634 }
2635 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002636 }
2637 return flags;
2638}
2639
2640uint32_t SurfaceFlinger::setClientStateLocked(
2641 const sp<Client>& client,
2642 const layer_state_t& s)
2643{
2644 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002645 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002646 if (layer != 0) {
2647 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002648 bool geometryAppliesWithResize =
2649 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002650 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002651 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002652 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002653 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002654 }
2655 if (what & layer_state_t::eLayerChanged) {
2656 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 const auto& p = layer->getParent();
2658 if (p == nullptr) {
2659 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2660 if (layer->setLayer(s.z) && idx >= 0) {
2661 mCurrentState.layersSortedByZ.removeAt(idx);
2662 mCurrentState.layersSortedByZ.add(layer);
2663 // we need traversal (state changed)
2664 // AND transaction (list changed)
2665 flags |= eTransactionNeeded|eTraversalNeeded;
2666 }
2667 } else {
2668 if (p->setChildLayer(layer, s.z)) {
2669 flags |= eTransactionNeeded|eTraversalNeeded;
2670 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002671 }
2672 }
2673 if (what & layer_state_t::eSizeChanged) {
2674 if (layer->setSize(s.w, s.h)) {
2675 flags |= eTraversalNeeded;
2676 }
2677 }
2678 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002680 flags |= eTraversalNeeded;
2681 }
2682 if (what & layer_state_t::eMatrixChanged) {
2683 if (layer->setMatrix(s.matrix))
2684 flags |= eTraversalNeeded;
2685 }
2686 if (what & layer_state_t::eTransparentRegionChanged) {
2687 if (layer->setTransparentRegionHint(s.transparentRegion))
2688 flags |= eTraversalNeeded;
2689 }
Dan Stoza23116082015-06-18 14:58:39 -07002690 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002691 if (layer->setFlags(s.flags, s.mask))
2692 flags |= eTraversalNeeded;
2693 }
2694 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002695 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002696 flags |= eTraversalNeeded;
2697 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002698 if (what & layer_state_t::eFinalCropChanged) {
2699 if (layer->setFinalCrop(s.finalCrop))
2700 flags |= eTraversalNeeded;
2701 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002702 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002703 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 // We only allow setting layer stacks for top level layers,
2705 // everything else inherits layer stack from its parent.
2706 if (layer->hasParent()) {
2707 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2708 layer->getName().string());
2709 } else if (idx < 0) {
2710 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2711 "that also does not appear in the top level layer list. Something"
2712 " has gone wrong.", layer->getName().string());
2713 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002714 mCurrentState.layersSortedByZ.removeAt(idx);
2715 mCurrentState.layersSortedByZ.add(layer);
2716 // we need traversal (state changed)
2717 // AND transaction (list changed)
2718 flags |= eTransactionNeeded|eTraversalNeeded;
2719 }
2720 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002721 if (what & layer_state_t::eDeferTransaction) {
2722 layer->deferTransactionUntil(s.handle, s.frameNumber);
2723 // We don't trigger a traversal here because if no other state is
2724 // changed, we don't want this to cause any more work
2725 }
Robert Carr1db73f62016-12-21 12:58:51 -08002726 if (what & layer_state_t::eReparentChildren) {
2727 if (layer->reparentChildren(s.reparentHandle)) {
2728 flags |= eTransactionNeeded|eTraversalNeeded;
2729 }
2730 }
Robert Carrc3574f72016-03-24 12:19:32 -07002731 if (what & layer_state_t::eOverrideScalingModeChanged) {
2732 layer->setOverrideScalingMode(s.overrideScalingMode);
2733 // We don't trigger a traversal here because if no other state is
2734 // changed, we don't want this to cause any more work
2735 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002736 }
2737 return flags;
2738}
2739
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002740status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002741 const String8& name,
2742 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002743 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002744 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2745 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002747 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002748 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002749 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002750 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002751 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002752
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002753 status_t result = NO_ERROR;
2754
2755 sp<Layer> layer;
2756
Mathias Agopian3165cc22012-08-08 19:42:09 -07002757 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2758 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002759 result = createNormalLayer(client,
2760 name, w, h, flags, format,
2761 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002763 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002764 result = createDimLayer(client,
2765 name, w, h, flags,
2766 handle, gbp, &layer);
2767 break;
2768 default:
2769 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 break;
2771 }
2772
Dan Stoza7d89d062015-04-30 13:29:25 -07002773 if (result != NO_ERROR) {
2774 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002776
Albert Chaulk479c60c2017-01-27 14:21:34 -05002777 layer->setInfo(windowType, ownerUid);
2778
Robert Carr1f0a16a2016-10-24 16:27:39 -07002779 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 if (result != NO_ERROR) {
2781 return result;
2782 }
Irvelffc9efc2016-07-27 15:16:37 -07002783 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002784
2785 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002786 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787}
2788
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002789status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2790 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2791 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792{
2793 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002794 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 case PIXEL_FORMAT_TRANSPARENT:
2796 case PIXEL_FORMAT_TRANSLUCENT:
2797 format = PIXEL_FORMAT_RGBA_8888;
2798 break;
2799 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002800 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 break;
2802 }
2803
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002804 *outLayer = new Layer(this, client, name, w, h, flags);
2805 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2806 if (err == NO_ERROR) {
2807 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002808 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002810
2811 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2812 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813}
2814
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002815status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2816 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2817 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002819 *outLayer = new LayerDim(this, client, name, w, h, flags);
2820 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002821 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002822 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002823}
2824
Mathias Agopianac9fa422013-02-11 16:40:36 -08002825status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826{
Mathias Agopian67106042013-03-14 19:18:13 -07002827 // called by the window manager when it wants to remove a Layer
2828 status_t err = NO_ERROR;
2829 sp<Layer> l(client->getLayerUser(handle));
2830 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002831 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002832 err = removeLayer(l);
2833 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2834 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002835 }
2836 return err;
2837}
2838
Mathias Agopian13127d82013-03-05 17:47:11 -08002839status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002840{
Mathias Agopian67106042013-03-14 19:18:13 -07002841 // called by ~LayerCleaner() when all references to the IBinder (handle)
2842 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002843 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844}
2845
Mathias Agopianb60314a2012-04-10 22:09:54 -07002846// ---------------------------------------------------------------------------
2847
Andy McFadden13a082e2012-08-24 10:16:42 -07002848void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002849 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002850 Vector<ComposerState> state;
2851 Vector<DisplayState> displays;
2852 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002853 d.what = DisplayState::eDisplayProjectionChanged |
2854 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002855 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002856 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002857 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002858 d.frame.makeInvalid();
2859 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002860 d.width = 0;
2861 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002862 displays.add(d);
2863 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002864 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002865
Dan Stoza9e56aa02015-11-02 13:00:03 -08002866 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2867 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002868 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002869}
2870
2871void SurfaceFlinger::initializeDisplays() {
2872 class MessageScreenInitialized : public MessageBase {
2873 SurfaceFlinger* flinger;
2874 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002875 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002876 virtual bool handler() {
2877 flinger->onInitializeDisplays();
2878 return true;
2879 }
2880 };
2881 sp<MessageBase> msg = new MessageScreenInitialized(this);
2882 postMessageAsync(msg); // we may be called from main thread, use async message
2883}
2884
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002885void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2886 int mode) {
2887 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2888 this);
2889 int32_t type = hw->getDisplayType();
2890 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002891
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002892 if (mode == currentMode) {
2893 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002894 return;
2895 }
2896
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002897 hw->setPowerMode(mode);
2898 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2899 ALOGW("Trying to set power mode for virtual display");
2900 return;
2901 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002902
Irvelffc9efc2016-07-27 15:16:37 -07002903 if (mInterceptor.isEnabled()) {
2904 Mutex::Autolock _l(mStateLock);
2905 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2906 if (idx < 0) {
2907 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2908 return;
2909 }
2910 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2911 }
2912
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002913 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002914 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002915 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002916 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2917 // FIXME: eventthread only knows about the main display right now
2918 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002919 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002920 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002922 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002923 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002924 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002925
2926 struct sched_param param = {0};
2927 param.sched_priority = 1;
2928 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2929 ALOGW("Couldn't set SCHED_FIFO on display on");
2930 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002931 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002932 // Turn off the display
2933 struct sched_param param = {0};
2934 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2935 ALOGW("Couldn't set SCHED_OTHER on display off");
2936 }
2937
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002938 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002939 disableHardwareVsync(true); // also cancels any in-progress resync
2940
Mathias Agopiancde87a32012-09-13 14:09:01 -07002941 // FIXME: eventthread only knows about the main display right now
2942 mEventThread->onScreenReleased();
2943 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002944
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002945 getHwComposer().setPowerMode(type, mode);
2946 mVisibleRegionsDirty = true;
2947 // from this point on, SF will stop drawing on this display
2948 } else {
2949 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002950 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002951}
2952
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002953void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2954 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002955 SurfaceFlinger& mFlinger;
2956 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002957 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002958 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002959 MessageSetPowerMode(SurfaceFlinger& flinger,
2960 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2961 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002962 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002963 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002964 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002965 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002966 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002967 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002968 ALOGW("Attempt to set power mode = %d for virtual display",
2969 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002970 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002971 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002972 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002973 return true;
2974 }
2975 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002977 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002978}
2979
2980// ---------------------------------------------------------------------------
2981
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2983{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002985
Mathias Agopianbd115332013-04-18 16:41:04 -07002986 IPCThreadState* ipc = IPCThreadState::self();
2987 const int pid = ipc->getCallingPid();
2988 const int uid = ipc->getCallingUid();
2989 if ((uid != AID_SHELL) &&
2990 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002991 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002992 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002994 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002995 // (this would indicate SF is stuck, but we want to be able to
2996 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002997 status_t err = mStateLock.timedLock(s2ns(1));
2998 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002999 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003000 result.appendFormat(
3001 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3002 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003003 }
3004
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003005 bool dumpAll = true;
3006 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003007 size_t numArgs = args.size();
3008 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003009 if ((index < numArgs) &&
3010 (args[index] == String16("--list"))) {
3011 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003012 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003013 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003014 }
3015
3016 if ((index < numArgs) &&
3017 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003018 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003019 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003020 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003021 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003022
3023 if ((index < numArgs) &&
3024 (args[index] == String16("--latency-clear"))) {
3025 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003026 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003027 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003028 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003029
3030 if ((index < numArgs) &&
3031 (args[index] == String16("--dispsync"))) {
3032 index++;
3033 mPrimaryDispSync.dump(result);
3034 dumpAll = false;
3035 }
Dan Stozab90cf072015-03-05 11:05:59 -08003036
3037 if ((index < numArgs) &&
3038 (args[index] == String16("--static-screen"))) {
3039 index++;
3040 dumpStaticScreenStats(result);
3041 dumpAll = false;
3042 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003043
3044 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003045 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003046 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003047 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003048 dumpAll = false;
3049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003051
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003052 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003053 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003054 }
3055
Mathias Agopian9795c422009-08-26 16:36:26 -07003056 if (locked) {
3057 mStateLock.unlock();
3058 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 }
3060 write(fd, result.string(), result.size());
3061 return NO_ERROR;
3062}
3063
Dan Stozac7014012014-02-14 15:03:43 -08003064void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3065 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003066{
Robert Carr2047fae2016-11-28 14:09:09 -08003067 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003068 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003069 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003070}
3071
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003072void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003073 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003074{
3075 String8 name;
3076 if (index < args.size()) {
3077 name = String8(args[index]);
3078 index++;
3079 }
3080
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3082 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003083 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003084
3085 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003086 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003087 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003088 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003089 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003090 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003091 }
Robert Carr2047fae2016-11-28 14:09:09 -08003092 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003093 }
3094}
3095
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003096void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003097 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003098{
3099 String8 name;
3100 if (index < args.size()) {
3101 name = String8(args[index]);
3102 index++;
3103 }
3104
Robert Carr2047fae2016-11-28 14:09:09 -08003105 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003106 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003107 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003108 }
Robert Carr2047fae2016-11-28 14:09:09 -08003109 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003110
Svetoslavd85084b2014-03-20 10:28:31 -07003111 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112}
3113
Jamie Gennis6547ff42013-07-16 20:12:42 -07003114// This should only be called from the main thread. Otherwise it would need
3115// the lock and should use mCurrentState rather than mDrawingState.
3116void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003117 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003118 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003119 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003120
3121 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3122}
3123
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003124void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003125{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003126 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003127#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003128 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003129#endif
3130#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003131 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003132#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003133 if (isLayerTripleBufferingDisabled())
3134 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003135 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003136}
3137
Dan Stozab90cf072015-03-05 11:05:59 -08003138void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3139{
3140 result.appendFormat("Static screen stats:\n");
3141 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3142 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3143 float percent = 100.0f *
3144 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3145 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3146 b + 1, bucketTimeSec, percent);
3147 }
3148 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3149 float percent = 100.0f *
3150 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3151 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3152 NUM_BUCKETS - 1, bucketTimeSec, percent);
3153}
3154
Dan Stozae77c7662016-05-13 11:37:28 -07003155void SurfaceFlinger::recordBufferingStats(const char* layerName,
3156 std::vector<OccupancyTracker::Segment>&& history) {
3157 Mutex::Autolock lock(mBufferingStatsMutex);
3158 auto& stats = mBufferingStats[layerName];
3159 for (const auto& segment : history) {
3160 if (!segment.usedThirdBuffer) {
3161 stats.twoBufferTime += segment.totalTime;
3162 }
3163 if (segment.occupancyAverage < 1.0f) {
3164 stats.doubleBufferedTime += segment.totalTime;
3165 } else if (segment.occupancyAverage < 2.0f) {
3166 stats.tripleBufferedTime += segment.totalTime;
3167 }
3168 ++stats.numSegments;
3169 stats.totalTime += segment.totalTime;
3170 }
3171}
3172
Brian Andersond6927fb2016-07-23 23:37:30 -07003173void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3174 result.appendFormat("Layer frame timestamps:\n");
3175
3176 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3177 const size_t count = currentLayers.size();
3178 for (size_t i=0 ; i<count ; i++) {
3179 currentLayers[i]->dumpFrameEvents(result);
3180 }
3181}
3182
Dan Stozae77c7662016-05-13 11:37:28 -07003183void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3184 result.append("Buffering stats:\n");
3185 result.append(" [Layer name] <Active time> <Two buffer> "
3186 "<Double buffered> <Triple buffered>\n");
3187 Mutex::Autolock lock(mBufferingStatsMutex);
3188 typedef std::tuple<std::string, float, float, float> BufferTuple;
3189 std::map<float, BufferTuple, std::greater<float>> sorted;
3190 for (const auto& statsPair : mBufferingStats) {
3191 const char* name = statsPair.first.c_str();
3192 const BufferingStats& stats = statsPair.second;
3193 if (stats.numSegments == 0) {
3194 continue;
3195 }
3196 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3197 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3198 stats.totalTime;
3199 float doubleBufferRatio = static_cast<float>(
3200 stats.doubleBufferedTime) / stats.totalTime;
3201 float tripleBufferRatio = static_cast<float>(
3202 stats.tripleBufferedTime) / stats.totalTime;
3203 sorted.insert({activeTime, {name, twoBufferRatio,
3204 doubleBufferRatio, tripleBufferRatio}});
3205 }
3206 for (const auto& sortedPair : sorted) {
3207 float activeTime = sortedPair.first;
3208 const BufferTuple& values = sortedPair.second;
3209 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3210 std::get<0>(values).c_str(), activeTime,
3211 std::get<1>(values), std::get<2>(values),
3212 std::get<3>(values));
3213 }
3214 result.append("\n");
3215}
3216
3217
Mathias Agopian74d211a2013-04-22 16:55:35 +02003218void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3219 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003220{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003221 bool colorize = false;
3222 if (index < args.size()
3223 && (args[index] == String16("--color"))) {
3224 colorize = true;
3225 index++;
3226 }
3227
3228 Colorizer colorizer(colorize);
3229
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003230 // figure out if we're stuck somewhere
3231 const nsecs_t now = systemTime();
3232 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3233 const nsecs_t inTransaction(mDebugInTransaction);
3234 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3235 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3236
3237 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003238 * Dump library configuration.
3239 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003240
3241 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003242 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003243 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003244 appendSfConfigString(result);
3245 appendUiConfigString(result);
3246 appendGuiConfigString(result);
3247 result.append("\n");
3248
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003249 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003250 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003251 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003252 result.append(SyncFeatures::getInstance().toString());
3253 result.append("\n");
3254
Dan Stoza9e56aa02015-11-02 13:00:03 -08003255 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3256
Andy McFadden41d67d72014-04-25 16:58:34 -07003257 colorizer.bold(result);
3258 result.append("DispSync configuration: ");
3259 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003260 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3261 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003262 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3263 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003264 result.append("\n");
3265
Dan Stozab90cf072015-03-05 11:05:59 -08003266 // Dump static screen stats
3267 result.append("\n");
3268 dumpStaticScreenStats(result);
3269 result.append("\n");
3270
Dan Stozae77c7662016-05-13 11:37:28 -07003271 dumpBufferingStats(result);
3272
Andy McFadden4803b742012-09-24 19:07:20 -07003273 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003274 * Dump the visible layer list
3275 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003276 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003277 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003278 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003279 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003280 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003281 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003282
3283 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003284 * Dump Display state
3285 */
3286
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003287 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003288 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003289 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003290 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3291 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003292 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003293 }
3294
3295 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003296 * Dump SurfaceFlinger global state
3297 */
3298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003299 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003300 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003301 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003302
Mathias Agopian888c8222012-08-04 21:10:38 -07003303 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003304 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003305
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003306 colorizer.bold(result);
3307 result.appendFormat("EGL implementation : %s\n",
3308 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3309 colorizer.reset(result);
3310 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003311 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003312
Mathias Agopian875d8e12013-06-07 15:35:48 -07003313 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314
Mathias Agopian42977342012-08-05 00:40:46 -07003315 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003316 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3317 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003318 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003319 " last eglSwapBuffers() time: %f us\n"
3320 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003321 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003322 " refresh-rate : %f fps\n"
3323 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003324 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003325 " gpu_to_cpu_unsupported : %d\n"
3326 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003327 mLastSwapBufferTime/1000.0,
3328 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003329 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003330 1e9 / activeConfig->getVsyncPeriod(),
3331 activeConfig->getDpiX(),
3332 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003333 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003334
Mathias Agopian74d211a2013-04-22 16:55:35 +02003335 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003336 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003337
Mathias Agopian74d211a2013-04-22 16:55:35 +02003338 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003339 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003340
3341 /*
3342 * VSYNC state
3343 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003344 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003345 result.append("\n");
3346
3347 /*
3348 * HWC layer minidump
3349 */
3350 for (size_t d = 0; d < mDisplays.size(); d++) {
3351 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3352 int32_t hwcId = displayDevice->getHwcDisplayId();
3353 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3354 continue;
3355 }
3356
3357 result.appendFormat("Display %d HWC layers:\n", hwcId);
3358 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003359 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003360 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 });
Dan Stozae22aec72016-08-01 13:20:59 -07003362 result.append("\n");
3363 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003364
3365 /*
3366 * Dump HWComposer state
3367 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003368 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003369 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003370 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003371 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003372 result.appendFormat(" h/w composer %s\n",
3373 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003374 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003375
3376 /*
3377 * Dump gralloc state
3378 */
3379 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3380 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003381}
3382
Mathias Agopian13127d82013-03-05 17:47:11 -08003383const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003384SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003385 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003386 wp<IBinder> dpy;
3387 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3388 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3389 dpy = mDisplays.keyAt(i);
3390 break;
3391 }
3392 }
3393 if (dpy == NULL) {
3394 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3395 // Just use the primary display so we have something to return
3396 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3397 }
3398 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003399}
3400
Keun young Park63f165f2012-08-31 10:53:36 -07003401bool SurfaceFlinger::startDdmConnection()
3402{
3403 void* libddmconnection_dso =
3404 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3405 if (!libddmconnection_dso) {
3406 return false;
3407 }
3408 void (*DdmConnection_start)(const char* name);
3409 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003410 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003411 if (!DdmConnection_start) {
3412 dlclose(libddmconnection_dso);
3413 return false;
3414 }
3415 (*DdmConnection_start)(getServiceName());
3416 return true;
3417}
3418
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003419status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003420 switch (code) {
3421 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003422 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003424 case CLEAR_ANIMATION_FRAME_STATS:
3425 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003426 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003427 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428 {
3429 // codes that require permission check
3430 IPCThreadState* ipc = IPCThreadState::self();
3431 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003432 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003433 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003434 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003435 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003436 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003438 break;
3439 }
Robert Carr1db73f62016-12-21 12:58:51 -08003440 /*
3441 * Calling setTransactionState is safe, because you need to have been
3442 * granted a reference to Client* and Handle* to do anything with it.
3443 *
3444 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3445 */
3446 case SET_TRANSACTION_STATE:
3447 case CREATE_SCOPED_CONNECTION:
3448 {
3449 return OK;
3450 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003451 case CAPTURE_SCREEN:
3452 {
3453 // codes that require permission check
3454 IPCThreadState* ipc = IPCThreadState::self();
3455 const int pid = ipc->getCallingPid();
3456 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003457 if ((uid != AID_GRAPHICS) &&
3458 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003459 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003460 return PERMISSION_DENIED;
3461 }
3462 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003463 }
3464 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003465 return OK;
3466}
3467
3468status_t SurfaceFlinger::onTransact(
3469 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3470{
3471 status_t credentialCheck = CheckTransactCodeCredentials(code);
3472 if (credentialCheck != OK) {
3473 return credentialCheck;
3474 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003475
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3477 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003478 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003479 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003480 IPCThreadState* ipc = IPCThreadState::self();
3481 const int pid = ipc->getCallingPid();
3482 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003483 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003484 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003485 return PERMISSION_DENIED;
3486 }
3487 int n;
3488 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003489 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003490 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491 return NO_ERROR;
3492 case 1002: // SHOW_UPDATES
3493 n = data.readInt32();
3494 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003495 invalidateHwcGeometry();
3496 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003498 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003499 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003500 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003502 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003503 setTransactionFlags(
3504 eTransactionNeeded|
3505 eDisplayTransactionNeeded|
3506 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003507 return NO_ERROR;
3508 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003509 case 1006:{ // send empty update
3510 signalRefresh();
3511 return NO_ERROR;
3512 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003513 case 1008: // toggle use of hw composer
3514 n = data.readInt32();
3515 mDebugDisableHWC = n ? 1 : 0;
3516 invalidateHwcGeometry();
3517 repaintEverything();
3518 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003519 case 1009: // toggle use of transform hint
3520 n = data.readInt32();
3521 mDebugDisableTransformHint = n ? 1 : 0;
3522 invalidateHwcGeometry();
3523 repaintEverything();
3524 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003526 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 reply->writeInt32(0);
3528 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003529 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003530 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 return NO_ERROR;
3532 case 1013: {
3533 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003534 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3535 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003536 return NO_ERROR;
3537 }
3538 case 1014: {
3539 // daltonize
3540 n = data.readInt32();
3541 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003542 case 1:
3543 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3544 break;
3545 case 2:
3546 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3547 break;
3548 case 3:
3549 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3550 break;
3551 default:
3552 mDaltonizer.setType(ColorBlindnessType::None);
3553 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003554 }
3555 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003556 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003557 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003558 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003559 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003560 invalidateHwcGeometry();
3561 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003564 case 1015: {
3565 // apply a color matrix
3566 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003567 if (n) {
3568 // color matrix is sent as mat3 matrix followed by vec3
3569 // offset, then packed into a mat4 where the last row is
3570 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003571 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003572 for (size_t j = 0; j < 4; j++) {
3573 mColorMatrix[i][j] = data.readFloat();
3574 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003575 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003576 } else {
3577 mColorMatrix = mat4();
3578 }
3579 invalidateHwcGeometry();
3580 repaintEverything();
3581 return NO_ERROR;
3582 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003583 // This is an experimental interface
3584 // Needs to be shifted to proper binder interface when we productize
3585 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003586 n = data.readInt32();
3587 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003588 return NO_ERROR;
3589 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003590 case 1017: {
3591 n = data.readInt32();
3592 mForceFullDamage = static_cast<bool>(n);
3593 return NO_ERROR;
3594 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003595 case 1018: { // Modify Choreographer's phase offset
3596 n = data.readInt32();
3597 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3598 return NO_ERROR;
3599 }
3600 case 1019: { // Modify SurfaceFlinger's phase offset
3601 n = data.readInt32();
3602 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3603 return NO_ERROR;
3604 }
Irvel468051e2016-06-13 16:44:44 -07003605 case 1020: { // Layer updates interceptor
3606 n = data.readInt32();
3607 if (n) {
3608 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003609 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003610 }
3611 else{
3612 ALOGV("Interceptor disabled");
3613 mInterceptor.disable();
3614 }
3615 return NO_ERROR;
3616 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003617 case 1021: { // Disable HWC virtual displays
3618 n = data.readInt32();
3619 mUseHwcVirtualDisplays = !n;
3620 return NO_ERROR;
3621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 }
3623 }
3624 return err;
3625}
3626
Mathias Agopian53331da2011-08-22 21:44:41 -07003627void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003628 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003629 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003630}
3631
Mathias Agopian59119e62010-10-11 12:37:43 -07003632// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003633// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003634// ---------------------------------------------------------------------------
3635
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003636/* The code below is here to handle b/8734824
3637 *
3638 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003639 * from the surfaceflinger thread to the calling binder thread, where they
3640 * are executed. This allows the calling thread in the calling process to be
3641 * reused and not depend on having "enough" binder threads to handle the
3642 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003643 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003644class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003645 /* Parts of GraphicProducerWrapper are run on two different threads,
3646 * communicating by sending messages via Looper but also by shared member
3647 * data. Coherence maintenance is subtle and in places implicit (ugh).
3648 *
3649 * Don't rely on Looper's sendMessage/handleMessage providing
3650 * release/acquire semantics for any data not actually in the Message.
3651 * Data going from surfaceflinger to binder threads needs to be
3652 * synchronized explicitly.
3653 *
3654 * Barrier open/wait do provide release/acquire semantics. This provides
3655 * implicit synchronization for data coming back from binder to
3656 * surfaceflinger threads.
3657 */
3658
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003659 sp<IGraphicBufferProducer> impl;
3660 sp<Looper> looper;
3661 status_t result;
3662 bool exitPending;
3663 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003664 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003665 uint32_t code;
3666 Parcel const* data;
3667 Parcel* reply;
3668
3669 enum {
3670 MSG_API_CALL,
3671 MSG_EXIT
3672 };
3673
3674 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003675 * Called on surfaceflinger thread. This is called by our "fake"
3676 * BpGraphicBufferProducer. We package the data and reply Parcel and
3677 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003678 */
3679 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003680 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003681 this->code = code;
3682 this->data = &data;
3683 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003684 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003685 // if we've exited, we run the message synchronously right here.
3686 // note (JH): as far as I can tell from looking at the code, this
3687 // never actually happens. if it does, i'm not sure if it happens
3688 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003689 handleMessage(Message(MSG_API_CALL));
3690 } else {
3691 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003692 // Prevent stores to this->{code, data, reply} from being
3693 // reordered later than the construction of Message.
3694 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003695 looper->sendMessage(this, Message(MSG_API_CALL));
3696 barrier.wait();
3697 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003698 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003699 }
3700
3701 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003702 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003703 * call the real BpGraphicBufferProducer.
3704 */
3705 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003706 int what = message.what;
3707 // Prevent reads below from happening before the read from Message
3708 atomic_thread_fence(memory_order_acquire);
3709 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003710 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003711 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003712 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003713 exitRequested = true;
3714 }
3715 }
3716
3717public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003718 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003719 : impl(impl),
3720 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003721 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003722 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003723 exitRequested(false),
3724 code(0),
3725 data(NULL),
3726 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003727 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003728
Jesse Hallb154c422014-07-13 12:47:02 -07003729 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003730 status_t waitForResponse() {
3731 do {
3732 looper->pollOnce(-1);
3733 } while (!exitRequested);
3734 return result;
3735 }
3736
Jesse Hallb154c422014-07-13 12:47:02 -07003737 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003738 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003739 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003740 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003741 // Ensure this->result is visible to the binder thread before it
3742 // handles the message.
3743 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003744 looper->sendMessage(this, Message(MSG_EXIT));
3745 }
3746};
3747
3748
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003749status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3750 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003751 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003752 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003753 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003754
3755 if (CC_UNLIKELY(display == 0))
3756 return BAD_VALUE;
3757
3758 if (CC_UNLIKELY(producer == 0))
3759 return BAD_VALUE;
3760
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003761 // if we have secure windows on this display, never allow the screen capture
3762 // unless the producer interface is local (i.e.: we can take a screenshot for
3763 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003764 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003765
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003766 // Convert to surfaceflinger's internal rotation type.
3767 Transform::orientation_flags rotationFlags;
3768 switch (rotation) {
3769 case ISurfaceComposer::eRotateNone:
3770 rotationFlags = Transform::ROT_0;
3771 break;
3772 case ISurfaceComposer::eRotate90:
3773 rotationFlags = Transform::ROT_90;
3774 break;
3775 case ISurfaceComposer::eRotate180:
3776 rotationFlags = Transform::ROT_180;
3777 break;
3778 case ISurfaceComposer::eRotate270:
3779 rotationFlags = Transform::ROT_270;
3780 break;
3781 default:
3782 rotationFlags = Transform::ROT_0;
3783 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3784 break;
3785 }
3786
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003787 class MessageCaptureScreen : public MessageBase {
3788 SurfaceFlinger* flinger;
3789 sp<IBinder> display;
3790 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003791 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003792 uint32_t reqWidth, reqHeight;
3793 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003794 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003795 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003796 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003797 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003798 public:
3799 MessageCaptureScreen(SurfaceFlinger* flinger,
3800 const sp<IBinder>& display,
3801 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003802 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003803 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003804 bool useIdentityTransform,
3805 Transform::orientation_flags rotation,
3806 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003807 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003808 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003809 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003810 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003811 rotation(rotation), result(PERMISSION_DENIED),
3812 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003813 {
3814 }
3815 status_t getResult() const {
3816 return result;
3817 }
3818 virtual bool handler() {
3819 Mutex::Autolock _l(flinger->mStateLock);
3820 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003821 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003822 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003823 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003824 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003825 return true;
3826 }
3827 };
3828
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829 // this creates a "fake" BBinder which will serve as a "fake" remote
3830 // binder to receive the marshaled calls and forward them to the
3831 // real remote (a BpGraphicBufferProducer)
3832 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3833
3834 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3835 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003836 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003837 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003838 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003839 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003840
3841 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003842 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003843 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003844 }
3845 return res;
3846}
3847
Mathias Agopian180f10d2013-04-10 22:55:41 -07003848
3849void SurfaceFlinger::renderScreenImplLocked(
3850 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003851 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003852 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003853 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003854{
3855 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003856 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003857
3858 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003859 const int32_t hw_w = hw->getWidth();
3860 const int32_t hw_h = hw->getHeight();
3861 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003862 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003863
Dan Stozac1879002014-05-22 15:59:05 -07003864 // if a default or invalid sourceCrop is passed in, set reasonable values
3865 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3866 !sourceCrop.isValid()) {
3867 sourceCrop.setLeftTop(Point(0, 0));
3868 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3869 }
3870
3871 // ensure that sourceCrop is inside screen
3872 if (sourceCrop.left < 0) {
3873 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3874 }
Dan Stozabe31f442014-06-11 11:20:54 -07003875 if (sourceCrop.right > hw_w) {
3876 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003877 }
3878 if (sourceCrop.top < 0) {
3879 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3880 }
Dan Stozabe31f442014-06-11 11:20:54 -07003881 if (sourceCrop.bottom > hw_h) {
3882 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003883 }
3884
Mathias Agopian180f10d2013-04-10 22:55:41 -07003885 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003886 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003887
3888 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003889 engine.setViewportAndProjection(
3890 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003891 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003892
3893 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003894 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003895
Robert Carr1f0a16a2016-10-24 16:27:39 -07003896 // We loop through the first level of layers without traversing,
3897 // as we need to interpret min/max layer Z in the top level Z space.
3898 for (const auto& layer : mDrawingState.layersSortedByZ) {
3899 if (layer->getLayerStack() != hw->getLayerStack()) {
3900 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003901 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003902 const Layer::State& state(layer->getDrawingState());
3903 if (state.z < minLayerZ || state.z > maxLayerZ) {
3904 continue;
3905 }
3906 layer->traverseInZOrder([&](Layer* layer) {
3907 if (!layer->isVisible()) {
3908 return;
3909 }
3910 if (filtering) layer->setFiltering(true);
3911 layer->draw(hw, useIdentityTransform);
3912 if (filtering) layer->setFiltering(false);
3913 });
3914 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003915
Mathias Agopian931bda12013-08-28 18:11:46 -07003916 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003917}
3918
3919
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003920status_t SurfaceFlinger::captureScreenImplLocked(
3921 const sp<const DisplayDevice>& hw,
3922 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003923 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003924 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003925 bool useIdentityTransform, Transform::orientation_flags rotation,
3926 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003927{
3928 ATRACE_CALL();
3929
Mathias Agopian180f10d2013-04-10 22:55:41 -07003930 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003931 uint32_t hw_w = hw->getWidth();
3932 uint32_t hw_h = hw->getHeight();
3933
3934 if (rotation & Transform::ROT_90) {
3935 std::swap(hw_w, hw_h);
3936 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003937
Mathias Agopian180f10d2013-04-10 22:55:41 -07003938 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3939 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3940 reqWidth, reqHeight, hw_w, hw_h);
3941 return BAD_VALUE;
3942 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003943
Mathias Agopian180f10d2013-04-10 22:55:41 -07003944 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3945 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3946
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003947 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003948 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003949 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003950 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3951 (state.z < minLayerZ || state.z > maxLayerZ)) {
3952 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003953 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003954 layer->traverseInZOrder([&](Layer *layer) {
3955 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3956 layer->isSecure());
3957 });
3958 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003959
3960 if (!isLocalScreenshot && secureLayerIsVisible) {
3961 ALOGW("FB is protected: PERMISSION_DENIED");
3962 return PERMISSION_DENIED;
3963 }
3964
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003965 // create a surface (because we're a producer, and we need to
3966 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003967 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003968
3969 // Put the screenshot Surface into async mode so that
3970 // Layer::headFenceHasSignaled will always return true and we'll latch the
3971 // first buffer regardless of whether or not its acquire fence has
3972 // signaled. This is needed to avoid a race condition in the rotation
3973 // animation. See b/30209608
3974 sur->setAsyncMode(true);
3975
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003976 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003977
Michael Lentine5a16a622015-05-21 13:48:24 -07003978 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3979 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003980 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3981 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003982
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003983 int err = 0;
3984 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003985 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003986 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3987 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003988
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003989 if (err == NO_ERROR) {
3990 ANativeWindowBuffer* buffer;
3991 /* TODO: Once we have the sync framework everywhere this can use
3992 * server-side waits on the fence that dequeueBuffer returns.
3993 */
3994 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3995 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003996 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003997 // create an EGLImage from the buffer so we can later
3998 // turn it into a texture
3999 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4000 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4001 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004002 // this binds the given EGLImage as a framebuffer for the
4003 // duration of this scope.
4004 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4005 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004006 // this will in fact render into our dequeued buffer
4007 // via an FBO, which means we didn't have to create
4008 // an EGLSurface and therefore we're not
4009 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004010 renderScreenImplLocked(
4011 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4012 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004013
Riley Andrews86639902014-08-15 12:27:24 -07004014 // Attempt to create a sync khr object that can produce a sync point. If that
4015 // isn't available, create a non-dupable sync object in the fallback path and
4016 // wait on it directly.
4017 EGLSyncKHR sync;
4018 if (!DEBUG_SCREENSHOTS) {
4019 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004020 // native fence fd will not be populated until flush() is done.
4021 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004022 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004023 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004024 }
Riley Andrews86639902014-08-15 12:27:24 -07004025 if (sync != EGL_NO_SYNC_KHR) {
4026 // get the sync fd
4027 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4028 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4029 ALOGW("captureScreen: failed to dup sync khr object");
4030 syncFd = -1;
4031 }
4032 eglDestroySyncKHR(mEGLDisplay, sync);
4033 } else {
4034 // fallback path
4035 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4036 if (sync != EGL_NO_SYNC_KHR) {
4037 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4038 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4039 EGLint eglErr = eglGetError();
4040 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4041 ALOGW("captureScreen: fence wait timed out");
4042 } else {
4043 ALOGW_IF(eglErr != EGL_SUCCESS,
4044 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4045 }
4046 eglDestroySyncKHR(mEGLDisplay, sync);
4047 } else {
4048 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4049 }
4050 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004051 if (DEBUG_SCREENSHOTS) {
4052 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4053 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4054 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4055 hw, minLayerZ, maxLayerZ);
4056 delete [] pixels;
4057 }
4058
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004059 } else {
4060 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4061 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004062 window->cancelBuffer(window, buffer, syncFd);
4063 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004064 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004065 // destroy our image
4066 eglDestroyImageKHR(mEGLDisplay, image);
4067 } else {
4068 result = BAD_VALUE;
4069 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004070 if (buffer) {
4071 // queueBuffer takes ownership of syncFd
4072 result = window->queueBuffer(window, buffer, syncFd);
4073 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 }
4075 } else {
4076 result = BAD_VALUE;
4077 }
4078 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4079 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004080
Mathias Agopian74c40c02010-09-29 13:02:36 -07004081 return result;
4082}
4083
Mathias Agopiand5556842013-09-19 17:08:37 -07004084void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004085 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004086 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004087 for (size_t y=0 ; y<h ; y++) {
4088 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4089 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004090 if (p[x] != 0xFF000000) return;
4091 }
4092 }
4093 ALOGE("*** we just took a black screenshot ***\n"
4094 "requested minz=%d, maxz=%d, layerStack=%d",
4095 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004096
Robert Carr2047fae2016-11-28 14:09:09 -08004097 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004098 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004099 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004100 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4101 state.z <= maxLayerZ) {
4102 layer->traverseInZOrder([&](Layer* layer) {
4103 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4104 layer->isVisible() ? '+' : '-',
4105 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004106 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004107 i++;
4108 });
4109 }
4110 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004111 }
4112}
4113
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004114// ---------------------------------------------------------------------------
4115
Robert Carr2047fae2016-11-28 14:09:09 -08004116void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4117 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004118}
4119
Robert Carr2047fae2016-11-28 14:09:09 -08004120void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4121 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004122}
4123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004125
4126
4127#if defined(__gl_h_)
4128#error "don't include gl/gl.h in this file"
4129#endif
4130
4131#if defined(__gl2_h_)
4132#error "don't include gl2/gl2.h in this file"
4133#endif