blob: 1c18ff980223e65eabfdac90e867a932b0a534ed [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>
90
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
105static sp<ISurfaceFlingerConfigs> getConfigs() {
106 static sp<ISurfaceFlingerConfigs> configs
107 = ISurfaceFlingerConfigs::getService();
108 return configs;
109}
110
111static int64_t getVsyncEventPhaseOffsetNs() {
112 int64_t ret = 1000000; // default value
113 getConfigs()->vsyncEventPhaseOffsetNs([&](OptionalInt64 value) {
114 if (value.specified) ret = value.value;
115 });
116 return ret;
117}
118
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700119// This is the phase offset in nanoseconds of the software vsync event
120// relative to the vsync event reported by HWComposer. The software vsync
121// event is when SurfaceFlinger and Choreographer-based applications run each
122// frame.
123//
124// This phase offset allows adjustment of the minimum latency from application
125// wake-up (by Choregographer) time to the time at which the resulting window
126// image is displayed. This value may be either positive (after the HW vsync)
127// or negative (before the HW vsync). Setting it to 0 will result in a
128// minimum latency of two vsync periods because the app and SurfaceFlinger
129// will run just after the HW vsync. Setting it to a positive number will
130// result in the minimum latency being:
131//
132// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
133//
134// Note that reducing this latency makes it more likely for the applications
135// to not have their window content image ready in time. When this happens
136// the latency will end up being an additional vsync period, and animations
137// will hiccup. Therefore, this latency should be tuned somewhat
138// conservatively (or at least with awareness of the trade-off being made).
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900139static int64_t vsyncPhaseOffsetNs = getVsyncEventPhaseOffsetNs();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700140
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700141// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800142static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144// ---------------------------------------------------------------------------
145
Mathias Agopian99b49842011-06-27 16:05:52 -0700146const String16 sHardwareTest("android.permission.HARDWARE_TEST");
147const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
148const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
149const String16 sDump("android.permission.DUMP");
150
151// ---------------------------------------------------------------------------
152
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700154 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700156 mTransactionPending(false),
157 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700158 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700159 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700160 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800161 mHwc(nullptr),
162 mRealHwc(nullptr),
163 mVrHwc(nullptr),
164 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800166 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800169 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700171 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700172 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700173 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700174 mDebugInSwapBuffers(0),
175 mLastSwapBufferTime(0),
176 mDebugInTransaction(0),
177 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700178 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700179 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700180 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000181 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700182 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700183 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800184 mHasColorMatrix(false),
185 mHasPoweredOff(false),
186 mFrameBuckets(),
187 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700188 mLastSwapTime(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800189 mNumLayers(0),
190 mEnterVrMode(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191{
Steve Blocka19954a2012-01-04 20:05:49 +0000192 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193
194 // debugging stuff...
195 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196
Mathias Agopianb4b17302013-03-20 18:36:41 -0700197 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700198 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 property_get("debug.sf.showupdates", value, "0");
201 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700203 property_get("debug.sf.ddms", value, "0");
204 mDebugDDMS = atoi(value);
205 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700206 if (!startDdmConnection()) {
207 // start failed, and DDMS debugging not enabled
208 mDebugDDMS = 0;
209 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700210 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700211 ALOGI_IF(mDebugRegion, "showupdates enabled");
212 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700213
214 property_get("debug.sf.disable_backpressure", value, "0");
215 mPropagateBackpressure = !atoi(value);
216 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700217
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800218 property_get("debug.sf.enable_hwc_vds", value, "0");
219 mUseHwcVirtualDisplays = atoi(value);
220 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800221
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800222 property_get("ro.sf.disable_triple_buffer", value, "1");
223 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225}
226
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800227void SurfaceFlinger::onFirstRef()
228{
229 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230}
231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232SurfaceFlinger::~SurfaceFlinger()
233{
Mathias Agopiana4912602012-07-12 14:25:33 -0700234 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
235 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
236 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800237
238 if (mVrStateCallbacks.get()) {
239 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
240 defaultServiceManager()->checkService(String16("vrmanager")));
241 if (vrManagerService.get()) {
242 vrManagerService->unregisterListener(mVrStateCallbacks);
243 }
244 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245}
246
Dan Stozac7014012014-02-14 15:03:43 -0800247void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248{
249 // the window manager died on us. prepare its eulogy.
250
Andy McFadden13a082e2012-08-24 10:16:42 -0700251 // restore initial conditions (default device unblank, etc)
252 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800253
254 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700255 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800256}
257
Robert Carr1db73f62016-12-21 12:58:51 -0800258static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700259 status_t err = client->initCheck();
260 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800261 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 }
Robert Carr1db73f62016-12-21 12:58:51 -0800263 return nullptr;
264}
265
266sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
267 return initClient(new Client(this));
268}
269
270sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
271 const sp<IGraphicBufferProducer>& gbp) {
272 if (authenticateSurfaceTexture(gbp) == false) {
273 return nullptr;
274 }
275 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
276 if (layer == nullptr) {
277 return nullptr;
278 }
279
280 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281}
282
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700283sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
284 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285{
286 class DisplayToken : public BBinder {
287 sp<SurfaceFlinger> flinger;
288 virtual ~DisplayToken() {
289 // no more references, this display must be terminated
290 Mutex::Autolock _l(flinger->mStateLock);
291 flinger->mCurrentState.displays.removeItem(this);
292 flinger->setTransactionFlags(eDisplayTransactionNeeded);
293 }
294 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700295 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700296 : flinger(flinger) {
297 }
298 };
299
300 sp<BBinder> token = new DisplayToken(this);
301
302 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700303 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700304 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700305 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700306 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700307 return token;
308}
309
Jesse Hall6c913be2013-08-08 12:15:49 -0700310void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
311 Mutex::Autolock _l(mStateLock);
312
313 ssize_t idx = mCurrentState.displays.indexOfKey(display);
314 if (idx < 0) {
315 ALOGW("destroyDisplay: invalid display token");
316 return;
317 }
318
319 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
320 if (!info.isVirtualDisplay()) {
321 ALOGE("destroyDisplay called for non-virtual display");
322 return;
323 }
Irvelffc9efc2016-07-27 15:16:37 -0700324 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700325 mCurrentState.displays.removeItemsAt(idx);
326 setTransactionFlags(eDisplayTransactionNeeded);
327}
328
Jesse Hall692c7232012-11-08 15:41:56 -0800329void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800330 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 ALOGW_IF(mBuiltinDisplays[type],
332 "Overwriting display token for display type %d", type);
333 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800334 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700335 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800336 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700337 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800338}
339
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700341 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700342 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
343 return NULL;
344 }
Jesse Hall692c7232012-11-08 15:41:56 -0800345 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346}
347
Jamie Gennis9a78c902011-01-12 18:30:40 -0800348sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
349{
350 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
351 return gba;
352}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354void SurfaceFlinger::bootFinished()
355{
Wei Wangb254fa32017-01-31 17:43:23 -0800356 if (mStartBootAnimThread->join() != NO_ERROR) {
357 ALOGE("Join StartBootAnimThread failed!");
358 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800359 const nsecs_t now = systemTime();
360 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000361 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700362 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363
364 // wait patiently for the window manager death
365 const String16 name("window");
366 sp<IBinder> window(defaultServiceManager()->getService(name));
367 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700368 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700369 }
370
371 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 // formerly we would just kill the process, but we now ask it to exit so it
373 // can choose where to stop the animation.
374 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700375
376 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
377 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
378 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800379
380 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
381 defaultServiceManager()->checkService(String16("vrmanager")));
382 if (vrManagerService.get()) {
383 mVrStateCallbacks = new VrStateCallbacks(*this);
384 vrManagerService->registerListener(mVrStateCallbacks);
385 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386}
387
Mathias Agopian3f844832013-08-07 21:24:32 -0700388void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 RenderEngine& engine;
391 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
394 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 }
396 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700397 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700398 return true;
399 }
400 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700401 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700402}
403
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404class DispSyncSource : public VSyncSource, private DispSync::Callback {
405public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700406 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000407 const char* name) :
408 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700409 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700410 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
412 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700413 mDispSync(dispSync),
414 mCallbackMutex(),
415 mCallback(),
416 mVsyncMutex(),
417 mPhaseOffset(phaseOffset),
418 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700419
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700420 virtual ~DispSyncSource() {}
421
422 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000425 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error registering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 } else {
433 status_t err = mDispSync->removeEventListener(
434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error unregistering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700439 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 }
443
444 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 mCallback = callback;
447 }
448
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449 virtual void setPhaseOffset(nsecs_t phaseOffset) {
450 Mutex::Autolock lock(mVsyncMutex);
451
452 // Normalize phaseOffset to [0, period)
453 auto period = mDispSync->getPeriod();
454 phaseOffset %= period;
455 if (phaseOffset < 0) {
456 // If we're here, then phaseOffset is in (-period, 0). After this
457 // operation, it will be in (0, period)
458 phaseOffset += period;
459 }
460 mPhaseOffset = phaseOffset;
461
462 // If we're not enabled, we don't need to mess with the listeners
463 if (!mEnabled) {
464 return;
465 }
466
467 // Remove the listener with the old offset
468 status_t err = mDispSync->removeEventListener(
469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error unregistering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474
475 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000476 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700477 static_cast<DispSync::Callback*>(this));
478 if (err != NO_ERROR) {
479 ALOGE("error registering vsync callback: %s (%d)",
480 strerror(-err), err);
481 }
482 }
483
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484private:
485 virtual void onDispSyncEvent(nsecs_t when) {
486 sp<VSyncSource::Callback> callback;
487 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700488 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 callback = mCallback;
490
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 if (mTraceVsync) {
492 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700493 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700494 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 }
496
497 if (callback != NULL) {
498 callback->onVSyncEvent(when);
499 }
500 }
501
Tim Murray4a4e4a22016-04-19 16:29:23 +0000502 const char* const mName;
503
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700504 int mValue;
505
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700507 const String8 mVsyncOnLabel;
508 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700509
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511
512 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700514
515 Mutex mVsyncMutex; // Protects the following
516 nsecs_t mPhaseOffset;
517 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518};
519
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700520class InjectVSyncSource : public VSyncSource {
521public:
522 InjectVSyncSource() {}
523
524 virtual ~InjectVSyncSource() {}
525
526 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
527 std::lock_guard<std::mutex> lock(mCallbackMutex);
528 mCallback = callback;
529 }
530
531 virtual void onInjectSyncEvent(nsecs_t when) {
532 std::lock_guard<std::mutex> lock(mCallbackMutex);
533 mCallback->onVSyncEvent(when);
534 }
535
536 virtual void setVSyncEnabled(bool) {}
537 virtual void setPhaseOffset(nsecs_t) {}
538
539private:
540 std::mutex mCallbackMutex; // Protects the following
541 sp<VSyncSource::Callback> mCallback;
542};
543
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700545 ALOGI( "SurfaceFlinger's main thread ready to run. "
546 "Initializing graphics H/W...");
547
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900548 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
549
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 { // Autolock scope
551 Mutex::Autolock _l(mStateLock);
552
553 // initialize EGL for the default display
554 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
555 eglInitialize(mEGLDisplay, NULL, NULL);
556
557 // start the EventThread
558 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
559 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700560 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
562 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700563 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800564 mEventQueue.setEventThread(mSFEventThread);
565
Tim Murrayacff43d2016-07-29 13:57:24 -0700566 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700567 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700568 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700569 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
570 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
571 }
572
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 // Get a RenderEngine for the given display / config (can't fail)
574 mRenderEngine = RenderEngine::create(mEGLDisplay,
575 HAL_PIXEL_FORMAT_RGBA_8888);
576 }
577
578 // Drop the state lock while we initialize the hardware composer. We drop
579 // the lock because on creation, it will call back into SurfaceFlinger to
580 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800581 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800582 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800583 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
585
Jesse Hall692c7232012-11-08 15:41:56 -0800586 Mutex::Autolock _l(mStateLock);
587
Mathias Agopian875d8e12013-06-07 15:35:48 -0700588 // retrieve the EGL context that was selected/created
589 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700590
Mathias Agopianda27af92012-09-13 18:17:13 -0700591 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
592 "couldn't create EGLContext");
593
Dan Stoza9e56aa02015-11-02 13:00:03 -0800594 // make the GLContext current so that we can create textures when creating
595 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700596 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
597
Jamie Gennisd1700752013-10-14 12:22:52 -0700598 mEventControlThread = new EventControlThread(this);
599 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
600
Mathias Agopian92a979a2012-08-02 18:32:23 -0700601 // initialize our drawing state
602 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700603
Andy McFadden13a082e2012-08-24 10:16:42 -0700604 // set initial conditions (e.g. unblank default device)
605 initializeDisplays();
606
Dan Stoza4e637772016-07-28 13:31:51 -0700607 mRenderEngine->primeCache();
608
Wei Wangb254fa32017-01-31 17:43:23 -0800609 mStartBootAnimThread = new StartBootAnimThread();
610 if (mStartBootAnimThread->Start() != NO_ERROR) {
611 ALOGE("Run StartBootAnimThread failed!");
612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800613
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700615}
616
Mathias Agopiana67e4182012-06-19 17:26:12 -0700617void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800618 // Start boot animation service by setting a property mailbox
619 // if property setting thread is already running, Start() will be just a NOP
620 mStartBootAnimThread->Start();
621 // Wait until property was set
622 if (mStartBootAnimThread->join() != NO_ERROR) {
623 ALOGE("Join StartBootAnimThread failed!");
624 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700625}
626
Mathias Agopian875d8e12013-06-07 15:35:48 -0700627size_t SurfaceFlinger::getMaxTextureSize() const {
628 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700629}
630
Mathias Agopian875d8e12013-06-07 15:35:48 -0700631size_t SurfaceFlinger::getMaxViewportDims() const {
632 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700633}
634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800635// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800636
Jamie Gennis582270d2011-08-17 18:19:00 -0700637bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800638 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800639 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800640 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700641 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800642}
643
Brian Anderson069b3652016-07-22 10:32:47 -0700644status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700645 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700646 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700647 FrameEvent::REQUESTED_PRESENT,
648 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700649 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700650 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700651 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700652 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700653 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700654 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700655 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700656 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700657 };
658 return NO_ERROR;
659}
660
Dan Stoza7f7da322014-05-02 15:26:25 -0700661status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
662 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700663 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700664 return BAD_VALUE;
665 }
666
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500667 if (!display.get())
668 return NAME_NOT_FOUND;
669
Jesse Hall692c7232012-11-08 15:41:56 -0800670 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700671 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800672 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700673 type = i;
674 break;
675 }
676 }
677
678 if (type < 0) {
679 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700680 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700681
Mathias Agopian8b736f12012-08-13 17:54:26 -0700682 // TODO: Not sure if display density should handled by SF any longer
683 class Density {
684 static int getDensityFromProperty(char const* propName) {
685 char property[PROPERTY_VALUE_MAX];
686 int density = 0;
687 if (property_get(propName, property, NULL) > 0) {
688 density = atoi(property);
689 }
690 return density;
691 }
692 public:
693 static int getEmuDensity() {
694 return getDensityFromProperty("qemu.sf.lcd_density"); }
695 static int getBuildDensity() {
696 return getDensityFromProperty("ro.sf.lcd_density"); }
697 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700698
Dan Stoza7f7da322014-05-02 15:26:25 -0700699 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700700
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700702 DisplayInfo info = DisplayInfo();
703
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 float xdpi = hwConfig->getDpiX();
705 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700706
707 if (type == DisplayDevice::DISPLAY_PRIMARY) {
708 // The density of the device is provided by a build property
709 float density = Density::getBuildDensity() / 160.0f;
710 if (density == 0) {
711 // the build doesn't provide a density -- this is wrong!
712 // use xdpi instead
713 ALOGE("ro.sf.lcd_density must be defined as a build property");
714 density = xdpi / 160.0f;
715 }
716 if (Density::getEmuDensity()) {
717 // if "qemu.sf.lcd_density" is specified, it overrides everything
718 xdpi = ydpi = density = Density::getEmuDensity();
719 density /= 160.0f;
720 }
721 info.density = density;
722
723 // TODO: this needs to go away (currently needed only by webkit)
724 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
725 info.orientation = hw->getOrientation();
726 } else {
727 // TODO: where should this value come from?
728 static const int TV_DENSITY = 213;
729 info.density = TV_DENSITY / 160.0f;
730 info.orientation = 0;
731 }
732
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733 info.w = hwConfig->getWidth();
734 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 info.xdpi = xdpi;
736 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900738 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739
Andy McFadden91b2ca82014-06-13 14:04:23 -0700740 // This is how far in advance a buffer must be queued for
741 // presentation at a given time. If you want a buffer to appear
742 // on the screen at time N, you must submit the buffer before
743 // (N - presentationDeadline).
744 //
745 // Normally it's one full refresh period (to give SF a chance to
746 // latch the buffer), but this can be reduced by configuring a
747 // DispSync offset. Any additional delays introduced by the hardware
748 // composer or panel must be accounted for here.
749 //
750 // We add an additional 1ms to allow for processing time and
751 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 info.presentationDeadline = hwConfig->getVsyncPeriod() -
753 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700754
755 // All non-virtual displays are currently considered secure.
756 info.secure = true;
757
Michael Wright28f24d02016-07-12 13:30:53 -0700758 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 }
760
Dan Stoza7f7da322014-05-02 15:26:25 -0700761 return NO_ERROR;
762}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700763
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800764status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700765 DisplayStatInfo* stats) {
766 if (stats == NULL) {
767 return BAD_VALUE;
768 }
769
770 // FIXME for now we always return stats for the primary display
771 memset(stats, 0, sizeof(*stats));
772 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
773 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
774 return NO_ERROR;
775}
776
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700777int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800778 if (display == NULL) {
779 ALOGE("%s : display is NULL", __func__);
780 return BAD_VALUE;
781 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700782 sp<DisplayDevice> device(getDisplayDevice(display));
783 if (device != NULL) {
784 return device->getActiveConfig();
785 }
786 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700787}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700788
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700789void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
790 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
791 this);
792 int32_t type = hw->getDisplayType();
793 int currentMode = hw->getActiveConfig();
794
795 if (mode == currentMode) {
796 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
797 return;
798 }
799
800 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
801 ALOGW("Trying to set config for virtual display");
802 return;
803 }
804
805 hw->setActiveConfig(mode);
806 getHwComposer().setActiveConfig(type, mode);
807}
808
809status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
810 class MessageSetActiveConfig: public MessageBase {
811 SurfaceFlinger& mFlinger;
812 sp<IBinder> mDisplay;
813 int mMode;
814 public:
815 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
816 int mode) :
817 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
818 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700819 Vector<DisplayInfo> configs;
820 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700821 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700822 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700823 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700824 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700825 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700826 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
827 if (hw == NULL) {
828 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700829 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700830 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
831 ALOGW("Attempt to set active config = %d for virtual display",
832 mMode);
833 } else {
834 mFlinger.setActiveConfigInternal(hw, mMode);
835 }
836 return true;
837 }
838 };
839 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
840 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700841 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700842}
Michael Wright28f24d02016-07-12 13:30:53 -0700843status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
844 Vector<android_color_mode_t>* outColorModes) {
845 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
846 return BAD_VALUE;
847 }
848
849 if (!display.get()) {
850 return NAME_NOT_FOUND;
851 }
852
853 int32_t type = NAME_NOT_FOUND;
854 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
855 if (display == mBuiltinDisplays[i]) {
856 type = i;
857 break;
858 }
859 }
860
861 if (type < 0) {
862 return type;
863 }
864
865 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
866 outColorModes->clear();
867 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
868
869 return NO_ERROR;
870}
871
872android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
873 sp<DisplayDevice> device(getDisplayDevice(display));
874 if (device != nullptr) {
875 return device->getActiveColorMode();
876 }
877 return static_cast<android_color_mode_t>(BAD_VALUE);
878}
879
880void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
881 android_color_mode_t mode) {
882 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
883 this);
884 int32_t type = hw->getDisplayType();
885 android_color_mode_t currentMode = hw->getActiveColorMode();
886
887 if (mode == currentMode) {
888 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
889 return;
890 }
891
892 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
893 ALOGW("Trying to set config for virtual display");
894 return;
895 }
896
897 hw->setActiveColorMode(mode);
898 getHwComposer().setActiveColorMode(type, mode);
899}
900
901
902status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
903 android_color_mode_t colorMode) {
904 class MessageSetActiveColorMode: public MessageBase {
905 SurfaceFlinger& mFlinger;
906 sp<IBinder> mDisplay;
907 android_color_mode_t mMode;
908 public:
909 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
910 android_color_mode_t mode) :
911 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
912 virtual bool handler() {
913 Vector<android_color_mode_t> modes;
914 mFlinger.getDisplayColorModes(mDisplay, &modes);
915 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
916 if (mMode < 0 || !exists) {
917 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
918 mDisplay.get());
919 return true;
920 }
921 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
922 if (hw == nullptr) {
923 ALOGE("Attempt to set active color mode = %d for null display %p",
924 mMode, mDisplay.get());
925 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
926 ALOGW("Attempt to set active color mode= %d for virtual display",
927 mMode);
928 } else {
929 mFlinger.setActiveColorModeInternal(hw, mMode);
930 }
931 return true;
932 }
933 };
934 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
935 postMessageSync(msg);
936 return NO_ERROR;
937}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700938
Svetoslavd85084b2014-03-20 10:28:31 -0700939status_t SurfaceFlinger::clearAnimationFrameStats() {
940 Mutex::Autolock _l(mStateLock);
941 mAnimFrameTracker.clearStats();
942 return NO_ERROR;
943}
944
945status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
946 Mutex::Autolock _l(mStateLock);
947 mAnimFrameTracker.getStats(outStats);
948 return NO_ERROR;
949}
950
Dan Stozac4f471e2016-03-24 09:31:08 -0700951status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
952 HdrCapabilities* outCapabilities) const {
953 Mutex::Autolock _l(mStateLock);
954
955 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
956 if (displayDevice == nullptr) {
957 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
958 return BAD_VALUE;
959 }
960
961 std::unique_ptr<HdrCapabilities> capabilities =
962 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
963 if (capabilities) {
964 std::swap(*outCapabilities, *capabilities);
965 } else {
966 return BAD_VALUE;
967 }
968
969 return NO_ERROR;
970}
971
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700972status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
973 if (enable == mInjectVSyncs) {
974 return NO_ERROR;
975 }
976
977 if (enable) {
978 mInjectVSyncs = enable;
979 ALOGV("VSync Injections enabled");
980 if (mVSyncInjector.get() == nullptr) {
981 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700982 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700983 }
984 mEventQueue.setEventThread(mInjectorEventThread);
985 } else {
986 mInjectVSyncs = enable;
987 ALOGV("VSync Injections disabled");
988 mEventQueue.setEventThread(mSFEventThread);
989 mVSyncInjector.clear();
990 }
991 return NO_ERROR;
992}
993
994status_t SurfaceFlinger::injectVSync(nsecs_t when) {
995 if (!mInjectVSyncs) {
996 ALOGE("VSync Injections not enabled");
997 return BAD_VALUE;
998 }
999 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1000 ALOGV("Injecting VSync inside SurfaceFlinger");
1001 mVSyncInjector->onInjectSyncEvent(when);
1002 }
1003 return NO_ERROR;
1004}
1005
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001006// ----------------------------------------------------------------------------
1007
1008sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001009 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001010}
1011
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001012// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001013
1014void SurfaceFlinger::waitForEvent() {
1015 mEventQueue.waitMessage();
1016}
1017
1018void SurfaceFlinger::signalTransaction() {
1019 mEventQueue.invalidate();
1020}
1021
1022void SurfaceFlinger::signalLayerUpdate() {
1023 mEventQueue.invalidate();
1024}
1025
1026void SurfaceFlinger::signalRefresh() {
1027 mEventQueue.refresh();
1028}
1029
1030status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001031 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001032 return mEventQueue.postMessage(msg, reltime);
1033}
1034
1035status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001036 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001037 status_t res = mEventQueue.postMessage(msg, reltime);
1038 if (res == NO_ERROR) {
1039 msg->wait();
1040 }
1041 return res;
1042}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001044void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001045 do {
1046 waitForEvent();
1047 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048}
1049
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050void SurfaceFlinger::enableHardwareVsync() {
1051 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001054 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1055 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001056 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001057 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001058}
1059
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061 Mutex::Autolock _l(mHWVsyncLock);
1062
Jesse Hall948fe0c2013-10-14 12:56:09 -07001063 if (makeAvailable) {
1064 mHWVsyncAvailable = true;
1065 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001066 // Hardware vsync is not currently available, so abort the resync
1067 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001068 return;
1069 }
1070
Dan Stoza9e56aa02015-11-02 13:00:03 -08001071 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1072 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073
1074 mPrimaryDispSync.reset();
1075 mPrimaryDispSync.setPeriod(period);
1076
1077 if (!mPrimaryHWVsyncEnabled) {
1078 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001079 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1080 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001081 mPrimaryHWVsyncEnabled = true;
1082 }
1083}
1084
Jesse Hall948fe0c2013-10-14 12:56:09 -07001085void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001086 Mutex::Autolock _l(mHWVsyncLock);
1087 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001088 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1089 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090 mPrimaryDispSync.endResync();
1091 mPrimaryHWVsyncEnabled = false;
1092 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001093 if (makeUnavailable) {
1094 mHWVsyncAvailable = false;
1095 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001096}
1097
Tim Murray4a4e4a22016-04-19 16:29:23 +00001098void SurfaceFlinger::resyncWithRateLimit() {
1099 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1100 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001101 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001102 }
1103}
1104
Steven Thomas3cfac282017-02-06 12:29:30 -08001105void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1106 nsecs_t timestamp) {
1107 Mutex::Autolock lock(mStateLock);
1108 // Ignore any vsyncs from the non-active hardware composer.
1109 if (composer != mHwc) {
1110 return;
1111 }
1112
Jamie Gennisd1700752013-10-14 12:22:52 -07001113 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 { // Scope for the lock
1116 Mutex::Autolock _l(mHWVsyncLock);
1117 if (type == 0 && mPrimaryHWVsyncEnabled) {
1118 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001120 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001121
1122 if (needsHwVsync) {
1123 enableHardwareVsync();
1124 } else {
1125 disableHardwareVsync(false);
1126 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001127}
1128
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001129void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1130 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1131 *compositorTiming = mCompositorTiming;
1132}
1133
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1135 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1136 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1137 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001138
Dan Stoza9e56aa02015-11-02 13:00:03 -08001139 // All non-virtual displays are currently considered secure.
1140 bool isSecure = true;
1141
1142 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001143
1144 // When we're using the vr composer, the assumption is that we've
1145 // already created the IBinder object for the primary display.
1146 if (!mHwc->isUsingVrComposer()) {
1147 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1148 }
1149
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 wp<IBinder> token = mBuiltinDisplays[type];
1151
1152 sp<IGraphicBufferProducer> producer;
1153 sp<IGraphicBufferConsumer> consumer;
1154 BufferQueue::createBufferQueue(&producer, &consumer,
1155 new GraphicBufferAlloc());
1156
1157 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1158 DisplayDevice::DISPLAY_PRIMARY, consumer);
1159 sp<DisplayDevice> hw = new DisplayDevice(this,
1160 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1161 producer, mRenderEngine->getEGLConfig());
1162 mDisplays.add(token, hw);
1163 } else {
1164 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001165 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001166 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001167 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001168 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001169 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1170 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001171 }
1172 setTransactionFlags(eDisplayTransactionNeeded);
1173
Andy McFadden9e9689c2012-10-10 18:17:51 -07001174 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001175 }
Mathias Agopian86303202012-07-24 22:46:10 -07001176}
1177
Steven Thomas3cfac282017-02-06 12:29:30 -08001178void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1179 Mutex::Autolock lock(mStateLock);
1180 if (composer == mHwc) {
1181 repaintEverything();
1182 } else {
1183 // This isn't from our current hardware composer. If it's a callback
1184 // from the real composer, forward the refresh request to vr
1185 // flinger. Otherwise ignore it.
1186 if (!composer->isUsingVrComposer()) {
1187 mVrFlinger->OnHardwareComposerRefresh();
1188 }
1189 }
1190}
1191
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 getHwComposer().setVsyncEnabled(disp,
1195 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001196}
1197
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001198void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1199 for (size_t i = 0; i < layers.size(); ++i) {
1200 layers[i]->clearHwcLayers();
1201 }
1202}
1203
1204void SurfaceFlinger::resetHwc() {
1205 disableHardwareVsync(true);
1206 clearHwcLayers(mDrawingState.layersSortedByZ);
1207 clearHwcLayers(mCurrentState.layersSortedByZ);
1208 // Clear the drawing state so that the logic inside of
1209 // handleTransactionLocked will fire. It will determine the delta between
1210 // mCurrentState and mDrawingState and re-apply all changes when we make the
1211 // transition.
1212 mDrawingState.displays.clear();
1213 mDisplays.clear();
1214}
1215
1216void SurfaceFlinger::updateVrMode() {
1217 {
1218 Mutex::Autolock _l(mStateLock);
1219 bool enteringVrMode = mEnterVrMode;
1220 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1221 return;
1222 }
1223
1224 if (enteringVrMode) {
1225 // Start vrflinger thread, if it hasn't been started already.
1226 if (!mVrFlinger) {
1227 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1228 int err = mVrFlinger->Run(mHwc->getComposer());
1229 if (err != NO_ERROR) {
1230 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1231 mVrFlinger.reset();
1232 mEnterVrMode = false;
1233 return;
1234 }
1235 }
1236
1237 if (!mVrHwc) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001238 mVrHwc = new HWComposer(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001239 ALOGV("Vr HWC created");
1240 }
1241
1242 resetHwc();
1243
1244 mHwc = mVrHwc;
1245 mVrFlinger->EnterVrMode();
1246 } else {
1247 mVrFlinger->ExitVrMode();
1248
1249 resetHwc();
1250
1251 mHwc = mRealHwc;
1252 enableHardwareVsync();
1253 }
1254
1255 mVisibleRegionsDirty = true;
1256 invalidateHwcGeometry();
1257 android_atomic_or(1, &mRepaintEverything);
1258 setTransactionFlags(eDisplayTransactionNeeded);
1259 }
1260 if (mVrHwc) {
1261 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1262 }
1263}
1264
Mathias Agopian4fec8732012-06-29 14:12:52 -07001265void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001266 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001268 case MessageQueue::INVALIDATE: {
Corey Tabakace2c1982017-02-15 17:07:20 -08001269 // TODO(eieio): Disabled until SELinux issues are resolved.
1270 //updateVrMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001271
Dan Stoza50182882016-07-08 12:02:20 -07001272 bool frameMissed = !mHadClientComposition &&
1273 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001274 (mPreviousPresentFence->getSignalTime() ==
1275 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001276 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001277 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001278 signalLayerUpdate();
1279 break;
1280 }
1281
Dan Stoza6b9454d2014-11-07 16:00:59 -08001282 bool refreshNeeded = handleMessageTransaction();
1283 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001284 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001285 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001286 // Signal a refresh if a transaction modified the window state,
1287 // a new buffer was latched, or if HWC has requested a full
1288 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 signalRefresh();
1290 }
1291 break;
1292 }
1293 case MessageQueue::REFRESH: {
1294 handleMessageRefresh();
1295 break;
1296 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001297 }
1298}
1299
Dan Stoza6b9454d2014-11-07 16:00:59 -08001300bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001301 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001302 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001303 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001304 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001305 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001306 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001307}
1308
Dan Stoza6b9454d2014-11-07 16:00:59 -08001309bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001310 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001311 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001312}
1313
1314void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001315 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001316
Pablo Ceballos40845df2016-01-25 17:41:15 -08001317 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001318
Brian Andersond6927fb2016-07-23 23:37:30 -07001319 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001320 rebuildLayerStacks();
1321 setUpHWComposer();
1322 doDebugFlashRegions();
1323 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001324 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001325
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001326 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001327
1328 mHadClientComposition = false;
1329 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1330 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1331 mHadClientComposition = mHadClientComposition ||
1332 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1333 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001334
Dan Stoza9e56aa02015-11-02 13:00:03 -08001335 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001336}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001337
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338void SurfaceFlinger::doDebugFlashRegions()
1339{
1340 // is debugging enabled
1341 if (CC_LIKELY(!mDebugRegion))
1342 return;
1343
1344 const bool repaintEverything = mRepaintEverything;
1345 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1346 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001347 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001348 // transform the dirty region into this screen's coordinate space
1349 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1350 if (!dirtyRegion.isEmpty()) {
1351 // redraw the whole screen
1352 doComposeSurfaces(hw, Region(hw->bounds()));
1353
1354 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001355 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001356 RenderEngine& engine(getRenderEngine());
1357 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1358
Mathias Agopianda27af92012-09-13 18:17:13 -07001359 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001360 }
1361 }
1362 }
1363
1364 postFramebuffer();
1365
1366 if (mDebugRegion > 1) {
1367 usleep(mDebugRegion * 1000);
1368 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001369
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001371 auto& displayDevice = mDisplays[displayId];
1372 if (!displayDevice->isDisplayOn()) {
1373 continue;
1374 }
1375
1376 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1378 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001379 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380}
1381
Brian Andersond6927fb2016-07-23 23:37:30 -07001382void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 ATRACE_CALL();
1385 ALOGV("preComposition");
1386
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001388 mDrawingState.traverseInZOrder([&](Layer* layer) {
1389 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001390 needExtraInvalidate = true;
1391 }
Robert Carr2047fae2016-11-28 14:09:09 -08001392 });
1393
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394 if (needExtraInvalidate) {
1395 signalLayerUpdate();
1396 }
1397}
1398
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001399void SurfaceFlinger::updateCompositorTiming(
1400 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1401 std::shared_ptr<FenceTime>& presentFenceTime) {
1402 // Update queue of past composite+present times and determine the
1403 // most recently known composite to present latency.
1404 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1405 nsecs_t compositeToPresentLatency = -1;
1406 while (!mCompositePresentTimes.empty()) {
1407 CompositePresentTime& cpt = mCompositePresentTimes.front();
1408 // Cached values should have been updated before calling this method,
1409 // which helps avoid duplicate syscalls.
1410 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1411 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1412 break;
1413 }
1414 compositeToPresentLatency = displayTime - cpt.composite;
1415 mCompositePresentTimes.pop();
1416 }
1417
1418 // Don't let mCompositePresentTimes grow unbounded, just in case.
1419 while (mCompositePresentTimes.size() > 16) {
1420 mCompositePresentTimes.pop();
1421 }
1422
1423 // Integer division and modulo round toward 0 not -inf, so we need to
1424 // treat negative and positive offsets differently.
1425 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1426 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1427 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1428
1429 // Snap the latency to a value that removes scheduling jitter from the
1430 // composition and present times, which often have >1ms of jitter.
1431 // Reducing jitter is important if an app attempts to extrapolate
1432 // something (such as user input) to an accurate diasplay time.
1433 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1434 // with (presentLatency % interval).
1435 nsecs_t snappedCompositeToPresentLatency = -1;
1436 if (compositeToPresentLatency >= 0) {
1437 nsecs_t bias = vsyncInterval / 2;
1438 int64_t extraVsyncs =
1439 (compositeToPresentLatency - idealLatency + bias) /
1440 vsyncInterval;
1441 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1442 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1443 }
1444
1445 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1446 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1447 mCompositorTiming.interval = vsyncInterval;
1448 if (snappedCompositeToPresentLatency >= 0) {
1449 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1450 }
1451}
1452
1453void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 ATRACE_CALL();
1456 ALOGV("postComposition");
1457
Brian Anderson3546a3f2016-07-14 11:51:14 -07001458 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001459 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001460 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001461 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001462 }
1463
Brian Andersond6927fb2016-07-23 23:37:30 -07001464 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001465
1466 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1467 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1468 glCompositionDoneFenceTime =
1469 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1470 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1471 } else {
1472 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1473 }
1474 mGlCompositionDoneTimeline.updateSignalTimes();
1475
1476 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1477 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1478 mDisplayTimeline.push(displayFenceTime);
1479 mDisplayTimeline.updateSignalTimes();
1480
1481 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1482 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1483 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1484 presentFenceTime = &displayFenceTime;
1485 } else {
1486 retireFenceTime = &displayFenceTime;
1487 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001488
1489 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1490 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1491
1492 // We use the refreshStartTime which might be sampled a little later than
1493 // when we started doing work for this frame, but that should be okay
1494 // since updateCompositorTiming has snapping logic.
1495 updateCompositorTiming(
1496 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1497
Robert Carr2047fae2016-11-28 14:09:09 -08001498 mDrawingState.traverseInZOrder([&](Layer* layer) {
1499 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001500 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001501 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001502 recordBufferingStats(layer->getName().string(),
1503 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001504 }
Robert Carr2047fae2016-11-28 14:09:09 -08001505 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001506
Brian Anderson3d4039d2016-09-23 16:31:30 -07001507 if (displayFence->isValid()) {
1508 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001509 enableHardwareVsync();
1510 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001511 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001512 }
1513 }
1514
Andy McFadden5167ec62014-05-22 13:08:43 -07001515 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001516 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001517 enableHardwareVsync();
1518 }
1519 }
1520
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001521 if (mAnimCompositionPending) {
1522 mAnimCompositionPending = false;
1523
Brian Anderson3d4039d2016-09-23 16:31:30 -07001524 if (displayFenceTime->isValid()) {
1525 mAnimFrameTracker.setActualPresentFence(
1526 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001527 } else {
1528 // The HWC doesn't support present fences, so use the refresh
1529 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001530 nsecs_t presentTime =
1531 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001532 mAnimFrameTracker.setActualPresentTime(presentTime);
1533 }
1534 mAnimFrameTracker.advanceFrame();
1535 }
Dan Stozab90cf072015-03-05 11:05:59 -08001536
1537 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1538 return;
1539 }
1540
1541 nsecs_t currentTime = systemTime();
1542 if (mHasPoweredOff) {
1543 mHasPoweredOff = false;
1544 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001545 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001547 if (numPeriods < NUM_BUCKETS - 1) {
1548 mFrameBuckets[numPeriods] += elapsedTime;
1549 } else {
1550 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1551 }
1552 mTotalTime += elapsedTime;
1553 }
1554 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555}
1556
1557void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001558 ATRACE_CALL();
1559 ALOGV("rebuildLayerStacks");
1560
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001562 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001564 mVisibleRegionsDirty = false;
1565 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001566
Mathias Agopian92a979a2012-08-02 18:32:23 -07001567 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001568 Region opaqueRegion;
1569 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001570 Vector<sp<Layer>> layersSortedByZ;
1571 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1572 const Transform& tr(displayDevice->getTransform());
1573 const Rect bounds(displayDevice->getBounds());
1574 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001575 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001576 displayDevice->getLayerStack(), dirtyRegion,
1577 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001578
Robert Carr2047fae2016-11-28 14:09:09 -08001579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001580 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001581 Region drawRegion(tr.transform(
1582 layer->visibleNonTransparentRegion));
1583 drawRegion.andSelf(bounds);
1584 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001585 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 } else {
1587 // Clear out the HWC layer if this layer was
1588 // previously visible, but no longer is
1589 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1590 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001591 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001592 }
Robert Carr2047fae2016-11-28 14:09:09 -08001593 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001594 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1596 displayDevice->undefinedRegion.set(bounds);
1597 displayDevice->undefinedRegion.subtractSelf(
1598 tr.transform(opaqueRegion));
1599 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001600 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001601 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001602}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001603
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 ATRACE_CALL();
1606 ALOGV("setUpHWComposer");
1607
Jesse Hall028dc8f2013-08-20 16:35:32 -07001608 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001609 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1610 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1611 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1612
1613 // If nothing has changed (!dirty), don't recompose.
1614 // If something changed, but we don't currently have any visible layers,
1615 // and didn't when we last did a composition, then skip it this time.
1616 // The second rule does two things:
1617 // - When all layers are removed from a display, we'll emit one black
1618 // frame, then nothing more until we get new layers.
1619 // - When a display is created with a private layer stack, we won't
1620 // emit any black frames until a layer is added to the layer stack.
1621 bool mustRecompose = dirty && !(empty && wasEmpty);
1622
1623 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1624 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1625 mustRecompose ? "doing" : "skipping",
1626 dirty ? "+" : "-",
1627 empty ? "+" : "-",
1628 wasEmpty ? "+" : "-");
1629
Dan Stoza71433162014-02-04 16:22:36 -08001630 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001631
1632 if (mustRecompose) {
1633 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1634 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001635 }
1636
Dan Stoza9e56aa02015-11-02 13:00:03 -08001637 // build the h/w work list
1638 if (CC_UNLIKELY(mGeometryInvalid)) {
1639 mGeometryInvalid = false;
1640 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1641 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1642 const auto hwcId = displayDevice->getHwcDisplayId();
1643 if (hwcId >= 0) {
1644 const Vector<sp<Layer>>& currentLayers(
1645 displayDevice->getVisibleLayersSortedByZ());
1646 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001647 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001648 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001649 if (!layer->hasHwcLayer(hwcId)) {
1650 auto hwcLayer = mHwc->createLayer(hwcId);
1651 if (hwcLayer) {
1652 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1653 } else {
1654 layer->forceClientComposition(hwcId);
1655 foundLayerWithoutHwc = true;
1656 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001657 }
1658 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001659
Robert Carrae060832016-11-28 10:51:00 -08001660 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001661 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001663 }
1664 }
1665 }
1666 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001667 }
Riley Andrews03414a12014-07-01 14:22:59 -07001668
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001669
1670 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1671
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 // Set the per-frame data
1673 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1674 auto& displayDevice = mDisplays[displayId];
1675 const auto hwcId = displayDevice->getHwcDisplayId();
1676 if (hwcId < 0) {
1677 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001678 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001679 if (colorMatrix != mPreviousColorMatrix) {
1680 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1681 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1682 "display %zd: %d", displayId, result);
1683 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1685 layer->setPerFrameData(displayDevice);
1686 }
1687 }
1688
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001689 mPreviousColorMatrix = colorMatrix;
1690
Dan Stoza9e56aa02015-11-02 13:00:03 -08001691 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001692 auto& displayDevice = mDisplays[displayId];
1693 if (!displayDevice->isDisplayOn()) {
1694 continue;
1695 }
1696
1697 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1699 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001700 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703void SurfaceFlinger::doComposition() {
1704 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 ALOGV("doComposition");
1706
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001707 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001708 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001709 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001710 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711 // transform the dirty region into this screen's coordinate space
1712 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001713
1714 // repaint the framebuffer (if needed)
1715 doDisplayComposition(hw, dirtyRegion);
1716
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717 hw->dirtyRegion.clear();
1718 hw->flip(hw->swapRegion);
1719 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001720 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001722 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723}
1724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725void SurfaceFlinger::postFramebuffer()
1726{
Mathias Agopian841cde52012-03-01 15:44:37 -08001727 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001729
Mathias Agopiana44b0412011-10-16 18:46:35 -07001730 const nsecs_t now = systemTime();
1731 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001732
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1734 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001735 if (!displayDevice->isDisplayOn()) {
1736 continue;
1737 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 const auto hwcId = displayDevice->getHwcDisplayId();
1739 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001740 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001741 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001742 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001743 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1745 sp<Fence> releaseFence = Fence::NO_FENCE;
1746 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1747 releaseFence = displayDevice->getClientTargetAcquireFence();
1748 } else {
1749 auto hwcLayer = layer->getHwcLayer(hwcId);
1750 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001751 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 layer->onLayerDisplayed(releaseFence);
1753 }
1754 if (hwcId >= 0) {
1755 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001756 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001757 }
1758
Mathias Agopiana44b0412011-10-16 18:46:35 -07001759 mLastSwapBufferTime = systemTime() - now;
1760 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001761
1762 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1763 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1764 logFrameStats();
1765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001766}
1767
Mathias Agopian87baae12012-07-31 12:38:26 -07001768void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769{
Mathias Agopian841cde52012-03-01 15:44:37 -08001770 ATRACE_CALL();
1771
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001772 // here we keep a copy of the drawing state (that is the state that's
1773 // going to be overwritten by handleTransactionLocked()) outside of
1774 // mStateLock so that the side-effects of the State assignment
1775 // don't happen with mStateLock held (which can cause deadlocks).
1776 State drawingState(mDrawingState);
1777
Mathias Agopianca4d3602011-05-19 15:38:14 -07001778 Mutex::Autolock _l(mStateLock);
1779 const nsecs_t now = systemTime();
1780 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781
Mathias Agopianca4d3602011-05-19 15:38:14 -07001782 // Here we're guaranteed that some transaction flags are set
1783 // so we can call handleTransactionLocked() unconditionally.
1784 // We call getTransactionFlags(), which will also clear the flags,
1785 // with mStateLock held to guarantee that mCurrentState won't change
1786 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001787
Mathias Agopiane57f2922012-08-09 16:29:12 -07001788 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001789 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001790
Mathias Agopianca4d3602011-05-19 15:38:14 -07001791 mLastTransactionTime = systemTime() - now;
1792 mDebugInTransaction = 0;
1793 invalidateHwcGeometry();
1794 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001795}
1796
Mathias Agopian87baae12012-07-31 12:38:26 -07001797void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001798{
Dan Stoza7dde5992015-05-22 09:51:44 -07001799 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001800 mCurrentState.traverseInZOrder([](Layer* layer) {
1801 layer->notifyAvailableFrames();
1802 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 /*
1805 * Traversal of the children
1806 * (perform the transaction for each of them if needed)
1807 */
1808
Mathias Agopian3559b072012-08-15 13:46:03 -07001809 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001810 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001812 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813
1814 const uint32_t flags = layer->doTransaction(0);
1815 if (flags & Layer::eVisibleRegion)
1816 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001817 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001818 }
1819
1820 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001821 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822 */
1823
Mathias Agopiane57f2922012-08-09 16:29:12 -07001824 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001825 // here we take advantage of Vector's copy-on-write semantics to
1826 // improve performance by skipping the transaction entirely when
1827 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001828 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1829 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001830 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001833 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001834
1835 // find the displays that were removed
1836 // (ie: in drawing state but not in current state)
1837 // also handle displays that changed
1838 // (ie: displays that are in both lists)
1839 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001840 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1841 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001842 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001843 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001844 // Call makeCurrent() on the primary display so we can
1845 // be sure that nothing associated with this display
1846 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001847 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001848 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001849 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1850 if (hw != NULL)
1851 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001852 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001853 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001854 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001855 } else {
1856 ALOGW("trying to remove the main display");
1857 }
1858 } else {
1859 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001860 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001861 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001862 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1863 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001864 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001865 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001866 // recreating the DisplayDevice, so we just remove it
1867 // from the drawing state, so that it get re-added
1868 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001869 sp<DisplayDevice> hw(getDisplayDevice(display));
1870 if (hw != NULL)
1871 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001872 mDisplays.removeItem(display);
1873 mDrawingState.displays.removeItemsAt(i);
1874 dc--; i--;
1875 // at this point we must loop to the next item
1876 continue;
1877 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001878
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001879 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001880 if (disp != NULL) {
1881 if (state.layerStack != draw[i].layerStack) {
1882 disp->setLayerStack(state.layerStack);
1883 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001884 if ((state.orientation != draw[i].orientation)
1885 || (state.viewport != draw[i].viewport)
1886 || (state.frame != draw[i].frame))
1887 {
1888 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001889 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001890 }
Michael Lentine47e45402014-07-18 15:34:25 -07001891 if (state.width != draw[i].width || state.height != draw[i].height) {
1892 disp->setDisplaySize(state.width, state.height);
1893 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001894 }
1895 }
1896 }
1897
1898 // find displays that were added
1899 // (ie: in current state but not in drawing state)
1900 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001901 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001902 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001903
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001904 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001905 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001906 sp<IGraphicBufferProducer> bqProducer;
1907 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001908 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1909 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001910
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001912 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001913 // Virtual displays without a surface are dormant:
1914 // they have external state (layer stack, projection,
1915 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001916 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001917
Dan Stoza8cf150a2016-08-02 10:27:31 -07001918 if (mUseHwcVirtualDisplays) {
1919 int width = 0;
1920 int status = state.surface->query(
1921 NATIVE_WINDOW_WIDTH, &width);
1922 ALOGE_IF(status != NO_ERROR,
1923 "Unable to query width (%d)", status);
1924 int height = 0;
1925 status = state.surface->query(
1926 NATIVE_WINDOW_HEIGHT, &height);
1927 ALOGE_IF(status != NO_ERROR,
1928 "Unable to query height (%d)", status);
1929 int intFormat = 0;
1930 status = state.surface->query(
1931 NATIVE_WINDOW_FORMAT, &intFormat);
1932 ALOGE_IF(status != NO_ERROR,
1933 "Unable to query format (%d)", status);
1934 auto format = static_cast<android_pixel_format_t>(
1935 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001936
Dan Stoza8cf150a2016-08-02 10:27:31 -07001937 mHwc->allocateVirtualDisplay(width, height, &format,
1938 &hwcId);
1939 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940
Dan Stoza5cf424b2016-05-20 14:02:39 -07001941 // TODO: Plumb requested format back up to consumer
1942
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 sp<VirtualDisplaySurface> vds =
1944 new VirtualDisplaySurface(*mHwc,
1945 hwcId, state.surface, bqProducer,
1946 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001947
1948 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001949 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001950 }
1951 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001952 ALOGE_IF(state.surface!=NULL,
1953 "adding a supported display, but rendering "
1954 "surface is provided (%p), ignoring it",
1955 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001956
1957 hwcId = state.type;
1958 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1959 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001960 }
1961
1962 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001963 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001964 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 state.type, hwcId, state.isSecure, display,
1966 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001967 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001968 hw->setLayerStack(state.layerStack);
1969 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001970 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001971 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001972 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001974 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001975 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001976 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001977 }
1978 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001979 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981
Mathias Agopian84300952012-11-21 16:02:13 -08001982 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1983 // The transform hint might have changed for some layers
1984 // (either because a display has changed, or because a layer
1985 // as changed).
1986 //
1987 // Walk through all the layers in currentLayers,
1988 // and update their transform hint.
1989 //
1990 // If a layer is visible only on a single display, then that
1991 // display is used to calculate the hint, otherwise we use the
1992 // default display.
1993 //
1994 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1995 // the hint is set before we acquire a buffer from the surface texture.
1996 //
1997 // NOTE: layer transactions have taken place already, so we use their
1998 // drawing state. However, SurfaceFlinger's own transaction has not
1999 // happened yet, so we must use the current state layer list
2000 // (soon to become the drawing state list).
2001 //
2002 sp<const DisplayDevice> disp;
2003 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002004 bool first = true;
2005 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002006 // NOTE: we rely on the fact that layers are sorted by
2007 // layerStack first (so we don't have to traverse the list
2008 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002009 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002010 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002011 currentlayerStack = layerStack;
2012 // figure out if this layerstack is mirrored
2013 // (more than one display) if so, pick the default display,
2014 // if not, pick the only display it's on.
2015 disp.clear();
2016 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2017 sp<const DisplayDevice> hw(mDisplays[dpy]);
2018 if (hw->getLayerStack() == currentlayerStack) {
2019 if (disp == NULL) {
2020 disp = hw;
2021 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002022 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002023 break;
2024 }
2025 }
2026 }
2027 }
Chet Haase91d25932013-04-11 15:24:55 -07002028 if (disp == NULL) {
2029 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2030 // redraw after transform hint changes. See bug 8508397.
2031
2032 // could be null when this layer is using a layerStack
2033 // that is not visible on any display. Also can occur at
2034 // screen off/on times.
2035 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002036 }
Chet Haase91d25932013-04-11 15:24:55 -07002037 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002038
2039 first = false;
2040 });
Mathias Agopian84300952012-11-21 16:02:13 -08002041 }
2042
2043
Mathias Agopian3559b072012-08-15 13:46:03 -07002044 /*
2045 * Perform our own transaction if needed
2046 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002047
2048 if (mLayersAdded) {
2049 mLayersAdded = false;
2050 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002051 mVisibleRegionsDirty = true;
2052 }
2053
2054 // some layers might have been removed, so
2055 // we need to update the regions they're exposing.
2056 if (mLayersRemoved) {
2057 mLayersRemoved = false;
2058 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002059 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002060 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002061 // this layer is not visible anymore
2062 // TODO: we could traverse the tree from front to back and
2063 // compute the actual visible region
2064 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002065 Region visibleReg;
2066 visibleReg.set(layer->computeScreenBounds());
2067 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002068 }
Robert Carr2047fae2016-11-28 14:09:09 -08002069 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 }
2071
2072 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002073
2074 updateCursorAsync();
2075}
2076
2077void SurfaceFlinger::updateCursorAsync()
2078{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2080 auto& displayDevice = mDisplays[displayId];
2081 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002082 continue;
2083 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084
2085 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2086 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002087 }
2088 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002089}
2090
2091void SurfaceFlinger::commitTransaction()
2092{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002093 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002095 for (const auto& l : mLayersPendingRemoval) {
2096 recordBufferingStats(l->getName().string(),
2097 l->getOccupancyHistory(true));
2098 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002099 }
2100 mLayersPendingRemoval.clear();
2101 }
2102
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002103 // If this transaction is part of a window animation then the next frame
2104 // we composite should be considered an animation as well.
2105 mAnimCompositionPending = mAnimTransactionPending;
2106
Mathias Agopian4fec8732012-06-29 14:12:52 -07002107 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002108 mDrawingState.traverseInZOrder([](Layer* layer) {
2109 layer->commitChildList();
2110 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002111 mTransactionPending = false;
2112 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002113 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114}
2115
Robert Carr2047fae2016-11-28 14:09:09 -08002116void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002117 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118{
Mathias Agopian841cde52012-03-01 15:44:37 -08002119 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122 Region aboveOpaqueLayers;
2123 Region aboveCoveredLayers;
2124 Region dirty;
2125
Mathias Agopian87baae12012-07-31 12:38:26 -07002126 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002127
Robert Carr2047fae2016-11-28 14:09:09 -08002128 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002130 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131
Jesse Hall01e29052013-02-19 16:13:35 -08002132 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002133 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002134 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002135
Mathias Agopianab028732010-03-16 16:41:46 -07002136 /*
2137 * opaqueRegion: area of a surface that is fully opaque.
2138 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002140
2141 /*
2142 * visibleRegion: area of a surface that is visible on screen
2143 * and not fully transparent. This is essentially the layer's
2144 * footprint minus the opaque regions above it.
2145 * Areas covered by a translucent surface are considered visible.
2146 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002148
2149 /*
2150 * coveredRegion: area of a surface that is covered by all
2151 * visible regions above it (which includes the translucent areas).
2152 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002154
Jesse Halla8026d22012-09-25 13:25:04 -07002155 /*
2156 * transparentRegion: area of a surface that is hinted to be completely
2157 * transparent. This is only used to tell when the layer has no visible
2158 * non-transparent regions and can be removed from the layer list. It
2159 * does not affect the visibleRegion of this layer or any layers
2160 * beneath it. The hint may not be correct if apps don't respect the
2161 * SurfaceView restrictions (which, sadly, some don't).
2162 */
2163 Region transparentRegion;
2164
Mathias Agopianab028732010-03-16 16:41:46 -07002165
2166 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002167 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002168 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002169 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002170 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002171 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002172 if (!visibleRegion.isEmpty()) {
2173 // Remove the transparent area from the visible region
2174 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002175 if (tr.preserveRects()) {
2176 // transform the transparent region
2177 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002178 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002179 // transformation too complex, can't do the
2180 // transparent region optimization.
2181 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002182 }
Mathias Agopianab028732010-03-16 16:41:46 -07002183 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002184
Mathias Agopianab028732010-03-16 16:41:46 -07002185 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002186 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002188 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2189 // the opaque region is the layer's footprint
2190 opaqueRegion = visibleRegion;
2191 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192 }
2193 }
2194
Mathias Agopianab028732010-03-16 16:41:46 -07002195 // Clip the covered region to the visible region
2196 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2197
2198 // Update aboveCoveredLayers for next (lower) layer
2199 aboveCoveredLayers.orSelf(visibleRegion);
2200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201 // subtract the opaque region covered by the layers above us
2202 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203
2204 // compute this layer's dirty region
2205 if (layer->contentDirty) {
2206 // we need to invalidate the whole region
2207 dirty = visibleRegion;
2208 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002209 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210 layer->contentDirty = false;
2211 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002212 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002213 * the exposed region consists of two components:
2214 * 1) what's VISIBLE now and was COVERED before
2215 * 2) what's EXPOSED now less what was EXPOSED before
2216 *
2217 * note that (1) is conservative, we start with the whole
2218 * visible region but only keep what used to be covered by
2219 * something -- which mean it may have been exposed.
2220 *
2221 * (2) handles areas that were not covered by anything but got
2222 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002223 */
Mathias Agopianab028732010-03-16 16:41:46 -07002224 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002225 const Region oldVisibleRegion = layer->visibleRegion;
2226 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002227 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2228 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229 }
2230 dirty.subtractSelf(aboveOpaqueLayers);
2231
2232 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002233 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopianab028732010-03-16 16:41:46 -07002235 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002237
Jesse Halla8026d22012-09-25 13:25:04 -07002238 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239 layer->setVisibleRegion(visibleRegion);
2240 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002241 layer->setVisibleNonTransparentRegion(
2242 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002243 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244
Mathias Agopian87baae12012-07-31 12:38:26 -07002245 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246}
2247
Mathias Agopian87baae12012-07-31 12:38:26 -07002248void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2249 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002250 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002251 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2252 if (hw->getLayerStack() == layerStack) {
2253 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002254 }
2255 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002256}
2257
Dan Stoza6b9454d2014-11-07 16:00:59 -08002258bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002260 ALOGV("handlePageFlip");
2261
Brian Andersond6927fb2016-07-23 23:37:30 -07002262 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002263
Mathias Agopian4fec8732012-06-29 14:12:52 -07002264 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002265 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002266
2267 // Store the set of layers that need updates. This set must not change as
2268 // buffers are being latched, as this could result in a deadlock.
2269 // Example: Two producers share the same command stream and:
2270 // 1.) Layer 0 is latched
2271 // 2.) Layer 0 gets a new frame
2272 // 2.) Layer 1 gets a new frame
2273 // 3.) Layer 1 is latched.
2274 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2275 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002276 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002277 if (layer->hasQueuedFrame()) {
2278 frameQueued = true;
2279 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002280 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002281 } else {
2282 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002283 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002284 } else {
2285 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002286 }
Robert Carr2047fae2016-11-28 14:09:09 -08002287 });
2288
Dan Stoza9e56aa02015-11-02 13:00:03 -08002289 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002290 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002291 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002292 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002294
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002295 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002296
2297 // If we will need to wake up at some time in the future to deal with a
2298 // queued frame that shouldn't be displayed during this vsync period, wake
2299 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002300 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002301 signalLayerUpdate();
2302 }
2303
2304 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306}
2307
Mathias Agopianad456f92011-01-13 17:53:01 -08002308void SurfaceFlinger::invalidateHwcGeometry()
2309{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002310 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002311}
2312
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002313
Fabien Sanglard830b8472016-11-30 16:35:58 -08002314void SurfaceFlinger::doDisplayComposition(
2315 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002316 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317{
Dan Stoza71433162014-02-04 16:22:36 -08002318 // We only need to actually compose the display if:
2319 // 1) It is being handled by hardware composer, which may need this to
2320 // keep its virtual display state machine in sync, or
2321 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002322 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002323 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002325 return;
2326 }
2327
Dan Stoza9e56aa02015-11-02 13:00:03 -08002328 ALOGV("doDisplayComposition");
2329
Mathias Agopian87baae12012-07-31 12:38:26 -07002330 Region dirtyRegion(inDirtyRegion);
2331
Mathias Agopianb8a55602009-06-26 19:06:36 -07002332 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002333 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002334
Fabien Sanglard830b8472016-11-30 16:35:58 -08002335 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002336 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002337 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2338 // takes a rectangle, we must make sure to update that whole
2339 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002340 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002341 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002342 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002343 // We need to redraw the rectangle that will be updated
2344 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002345 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002346 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002347 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002348 } else {
2349 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002350 dirtyRegion.set(displayDevice->bounds());
2351 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352 }
2353 }
2354
Fabien Sanglard830b8472016-11-30 16:35:58 -08002355 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002357 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002358 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002359
2360 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002361 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362}
2363
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364bool SurfaceFlinger::doComposeSurfaces(
2365 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002366{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002367 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002368
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002370
2371 mat4 oldColorMatrix;
2372 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2373 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2374 if (applyColorMatrix) {
2375 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2376 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2377 }
2378
Dan Stoza9e56aa02015-11-02 13:00:03 -08002379 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2380 if (hasClientComposition) {
2381 ALOGV("hasClientComposition");
2382
2383 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002384 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002385 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002386 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2387 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2388 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2389 }
2390 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002391 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002392
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002393 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2395 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002396 // when using overlays, we assume a fully transparent framebuffer
2397 // NOTE: we could reduce how much we need to clear, for instance
2398 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002399 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002400 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002402 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002403 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002405
2406 // we remove the scissor part
2407 // we're left with the letterbox region
2408 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002410
2411 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002413
2414 // but limit it to the dirty region
2415 region.andSelf(dirty);
2416
Mathias Agopianb9494d52012-04-18 02:28:45 -07002417 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002418 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002419 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002421 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002422 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002423
Dan Stoza9e56aa02015-11-02 13:00:03 -08002424 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002425 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002426 // scissor on the main display. It should never be needed
2427 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 const Rect& bounds(displayDevice->getBounds());
2429 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002430 if (scissor != bounds) {
2431 // scissor doesn't match the screen's dimensions, so we
2432 // need to clear everything outside of it and enable
2433 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002434
Mathias Agopianf45c5102012-10-24 16:29:17 -07002435 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 const uint32_t height = displayDevice->getHeight();
2437 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002438 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002439 }
2440 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002441 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002442
Mathias Agopian85d751c2012-08-29 16:59:24 -07002443 /*
2444 * and then, render the layers targeted at the framebuffer
2445 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002446
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 ALOGV("Rendering client layers");
2448 const Transform& displayTransform = displayDevice->getTransform();
2449 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002450 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 bool firstLayer = true;
2452 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2453 const Region clip(dirty.intersect(
2454 displayTransform.transform(layer->visibleRegion)));
2455 ALOGV("Layer: %s", layer->getName().string());
2456 ALOGV(" Composition type: %s",
2457 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002458 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 switch (layer->getCompositionType(hwcId)) {
2460 case HWC2::Composition::Cursor:
2461 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002462 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002464 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2466 layer->isOpaque(state) && (state.alpha == 1.0f)
2467 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002468 // never clear the very first layer since we're
2469 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002470 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002471 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002472 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002474 case HWC2::Composition::Client: {
2475 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002476 break;
2477 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002479 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002480 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 } else {
2482 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002483 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002485 }
2486 } else {
2487 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002489 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002491 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002493 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002494 }
2495 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002496
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002497 if (applyColorMatrix) {
2498 getRenderEngine().setupColorTransform(oldColorMatrix);
2499 }
2500
Mathias Agopianf45c5102012-10-24 16:29:17 -07002501 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002502 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002503 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504}
2505
Fabien Sanglard830b8472016-11-30 16:35:58 -08002506void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2507 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002508 RenderEngine& engine(getRenderEngine());
2509 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510}
2511
Dan Stoza7d89d062015-04-30 13:29:25 -07002512status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002513 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002514 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515 const sp<Layer>& lbc,
2516 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002517{
Dan Stoza7d89d062015-04-30 13:29:25 -07002518 // add this layer to the current state list
2519 {
2520 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002521 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002522 return NO_MEMORY;
2523 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 if (parent == nullptr) {
2525 mCurrentState.layersSortedByZ.add(lbc);
2526 } else {
2527 parent->addChild(lbc);
2528 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002529 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 mLayersAdded = true;
2531 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002532 }
2533
Mathias Agopian96f08192010-06-02 23:28:45 -07002534 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002535 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002536
Dan Stoza7d89d062015-04-30 13:29:25 -07002537 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002538}
2539
Dan Stoza22851c32016-08-09 13:21:03 -07002540status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002542 sp<Layer> layer = weakLayer.promote();
2543 if (layer == nullptr) {
2544 // The layer has already been removed, carry on
2545 return NO_ERROR;
2546 }
2547
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 const auto& p = layer->getParent();
2549 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2550 mCurrentState.layersSortedByZ.remove(layer);
2551
2552 if (index < 0) {
2553 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2554 layer->getName().string(),
2555 (p != nullptr) ? p->getName().string() : "no-parent");
2556 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002557 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002558
2559 mLayersPendingRemoval.add(layer);
2560 mLayersRemoved = true;
2561 mNumLayers--;
2562 setTransactionFlags(eTransactionNeeded);
2563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002566uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002567 return android_atomic_release_load(&mTransactionFlags);
2568}
2569
Mathias Agopian3f844832013-08-07 21:24:32 -07002570uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2572}
2573
Mathias Agopian3f844832013-08-07 21:24:32 -07002574uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2576 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002577 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 }
2579 return old;
2580}
2581
Mathias Agopian8b33f032012-07-24 20:43:54 -07002582void SurfaceFlinger::setTransactionState(
2583 const Vector<ComposerState>& state,
2584 const Vector<DisplayState>& displays,
2585 uint32_t flags)
2586{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002587 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002588 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002589 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002590
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002591 if (flags & eAnimation) {
2592 // For window updates that are part of an animation we must wait for
2593 // previous animation "frames" to be handled.
2594 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002595 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002596 if (CC_UNLIKELY(err != NO_ERROR)) {
2597 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002598 // caller after a few seconds.
2599 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2600 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002601 mAnimTransactionPending = false;
2602 break;
2603 }
2604 }
2605 }
2606
Mathias Agopiane57f2922012-08-09 16:29:12 -07002607 size_t count = displays.size();
2608 for (size_t i=0 ; i<count ; i++) {
2609 const DisplayState& s(displays[i]);
2610 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002611 }
2612
Mathias Agopiane57f2922012-08-09 16:29:12 -07002613 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002614 for (size_t i=0 ; i<count ; i++) {
2615 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002616 // Here we need to check that the interface we're given is indeed
2617 // one of our own. A malicious client could give us a NULL
2618 // IInterface, or one of its own or even one of our own but a
2619 // different type. All these situations would cause us to crash.
2620 //
2621 // NOTE: it would be better to use RTTI as we could directly check
2622 // that we have a Client*. however, RTTI is disabled in Android.
2623 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002624 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002625 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002626 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002627 sp<Client> client( static_cast<Client *>(s.client.get()) );
2628 transactionFlags |= setClientStateLocked(client, s.state);
2629 }
2630 }
2631 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002632 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002633
Robert Carr2a7dbb42016-05-24 11:41:28 -07002634 // If a synchronous transaction is explicitly requested without any changes,
2635 // force a transaction anyway. This can be used as a flush mechanism for
2636 // previous async transactions.
2637 if (transactionFlags == 0 && (flags & eSynchronous)) {
2638 transactionFlags = eTransactionNeeded;
2639 }
2640
Mathias Agopian386aa982011-11-07 21:58:03 -08002641 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002642 if (mInterceptor.isEnabled()) {
2643 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2644 }
Irvel468051e2016-06-13 16:44:44 -07002645
Mathias Agopian386aa982011-11-07 21:58:03 -08002646 // this triggers the transaction
2647 setTransactionFlags(transactionFlags);
2648
2649 // if this is a synchronous transaction, wait for it to take effect
2650 // before returning.
2651 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002652 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002653 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002654 if (flags & eAnimation) {
2655 mAnimTransactionPending = true;
2656 }
2657 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002658 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2659 if (CC_UNLIKELY(err != NO_ERROR)) {
2660 // just in case something goes wrong in SF, return to the
2661 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002662 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2663 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002664 break;
2665 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 }
2668}
2669
Mathias Agopiane57f2922012-08-09 16:29:12 -07002670uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2671{
Jesse Hall9a143922012-10-04 16:29:19 -07002672 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2673 if (dpyIdx < 0)
2674 return 0;
2675
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002677 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002678 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002679 const uint32_t what = s.what;
2680 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002681 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002682 disp.surface = s.surface;
2683 flags |= eDisplayTransactionNeeded;
2684 }
2685 }
2686 if (what & DisplayState::eLayerStackChanged) {
2687 if (disp.layerStack != s.layerStack) {
2688 disp.layerStack = s.layerStack;
2689 flags |= eDisplayTransactionNeeded;
2690 }
2691 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002692 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002693 if (disp.orientation != s.orientation) {
2694 disp.orientation = s.orientation;
2695 flags |= eDisplayTransactionNeeded;
2696 }
2697 if (disp.frame != s.frame) {
2698 disp.frame = s.frame;
2699 flags |= eDisplayTransactionNeeded;
2700 }
2701 if (disp.viewport != s.viewport) {
2702 disp.viewport = s.viewport;
2703 flags |= eDisplayTransactionNeeded;
2704 }
2705 }
Michael Lentine47e45402014-07-18 15:34:25 -07002706 if (what & DisplayState::eDisplaySizeChanged) {
2707 if (disp.width != s.width) {
2708 disp.width = s.width;
2709 flags |= eDisplayTransactionNeeded;
2710 }
2711 if (disp.height != s.height) {
2712 disp.height = s.height;
2713 flags |= eDisplayTransactionNeeded;
2714 }
2715 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002716 }
2717 return flags;
2718}
2719
2720uint32_t SurfaceFlinger::setClientStateLocked(
2721 const sp<Client>& client,
2722 const layer_state_t& s)
2723{
2724 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002725 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002726 if (layer != 0) {
2727 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002728 bool geometryAppliesWithResize =
2729 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002730 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002731 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002732 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002733 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002734 }
2735 if (what & layer_state_t::eLayerChanged) {
2736 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 const auto& p = layer->getParent();
2738 if (p == nullptr) {
2739 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2740 if (layer->setLayer(s.z) && idx >= 0) {
2741 mCurrentState.layersSortedByZ.removeAt(idx);
2742 mCurrentState.layersSortedByZ.add(layer);
2743 // we need traversal (state changed)
2744 // AND transaction (list changed)
2745 flags |= eTransactionNeeded|eTraversalNeeded;
2746 }
2747 } else {
2748 if (p->setChildLayer(layer, s.z)) {
2749 flags |= eTransactionNeeded|eTraversalNeeded;
2750 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002751 }
2752 }
2753 if (what & layer_state_t::eSizeChanged) {
2754 if (layer->setSize(s.w, s.h)) {
2755 flags |= eTraversalNeeded;
2756 }
2757 }
2758 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002759 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002760 flags |= eTraversalNeeded;
2761 }
2762 if (what & layer_state_t::eMatrixChanged) {
2763 if (layer->setMatrix(s.matrix))
2764 flags |= eTraversalNeeded;
2765 }
2766 if (what & layer_state_t::eTransparentRegionChanged) {
2767 if (layer->setTransparentRegionHint(s.transparentRegion))
2768 flags |= eTraversalNeeded;
2769 }
Dan Stoza23116082015-06-18 14:58:39 -07002770 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002771 if (layer->setFlags(s.flags, s.mask))
2772 flags |= eTraversalNeeded;
2773 }
2774 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002775 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002776 flags |= eTraversalNeeded;
2777 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002778 if (what & layer_state_t::eFinalCropChanged) {
2779 if (layer->setFinalCrop(s.finalCrop))
2780 flags |= eTraversalNeeded;
2781 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002783 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 // We only allow setting layer stacks for top level layers,
2785 // everything else inherits layer stack from its parent.
2786 if (layer->hasParent()) {
2787 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2788 layer->getName().string());
2789 } else if (idx < 0) {
2790 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2791 "that also does not appear in the top level layer list. Something"
2792 " has gone wrong.", layer->getName().string());
2793 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794 mCurrentState.layersSortedByZ.removeAt(idx);
2795 mCurrentState.layersSortedByZ.add(layer);
2796 // we need traversal (state changed)
2797 // AND transaction (list changed)
2798 flags |= eTransactionNeeded|eTraversalNeeded;
2799 }
2800 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002801 if (what & layer_state_t::eDeferTransaction) {
2802 layer->deferTransactionUntil(s.handle, s.frameNumber);
2803 // We don't trigger a traversal here because if no other state is
2804 // changed, we don't want this to cause any more work
2805 }
Robert Carr1db73f62016-12-21 12:58:51 -08002806 if (what & layer_state_t::eReparentChildren) {
2807 if (layer->reparentChildren(s.reparentHandle)) {
2808 flags |= eTransactionNeeded|eTraversalNeeded;
2809 }
2810 }
Robert Carrc3574f72016-03-24 12:19:32 -07002811 if (what & layer_state_t::eOverrideScalingModeChanged) {
2812 layer->setOverrideScalingMode(s.overrideScalingMode);
2813 // We don't trigger a traversal here because if no other state is
2814 // changed, we don't want this to cause any more work
2815 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 }
2817 return flags;
2818}
2819
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002820status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002821 const String8& name,
2822 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002823 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002824 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2825 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002827 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002828 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002829 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002830 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002831 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002832
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002833 status_t result = NO_ERROR;
2834
2835 sp<Layer> layer;
2836
Mathias Agopian3165cc22012-08-08 19:42:09 -07002837 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2838 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002839 result = createNormalLayer(client,
2840 name, w, h, flags, format,
2841 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002843 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002844 result = createDimLayer(client,
2845 name, w, h, flags,
2846 handle, gbp, &layer);
2847 break;
2848 default:
2849 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 break;
2851 }
2852
Dan Stoza7d89d062015-04-30 13:29:25 -07002853 if (result != NO_ERROR) {
2854 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002856
Albert Chaulk479c60c2017-01-27 14:21:34 -05002857 layer->setInfo(windowType, ownerUid);
2858
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002860 if (result != NO_ERROR) {
2861 return result;
2862 }
Irvelffc9efc2016-07-27 15:16:37 -07002863 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002864
2865 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002866 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002869status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2870 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2871 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872{
2873 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002874 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 case PIXEL_FORMAT_TRANSPARENT:
2876 case PIXEL_FORMAT_TRANSLUCENT:
2877 format = PIXEL_FORMAT_RGBA_8888;
2878 break;
2879 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002880 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 break;
2882 }
2883
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002884 *outLayer = new Layer(this, client, name, w, h, flags);
2885 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2886 if (err == NO_ERROR) {
2887 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002888 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002890
2891 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2892 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893}
2894
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002895status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2896 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2897 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002899 *outLayer = new LayerDim(this, client, name, w, h, flags);
2900 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002901 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002902 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002903}
2904
Mathias Agopianac9fa422013-02-11 16:40:36 -08002905status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906{
Mathias Agopian67106042013-03-14 19:18:13 -07002907 // called by the window manager when it wants to remove a Layer
2908 status_t err = NO_ERROR;
2909 sp<Layer> l(client->getLayerUser(handle));
2910 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002911 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002912 err = removeLayer(l);
2913 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2914 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002915 }
2916 return err;
2917}
2918
Mathias Agopian13127d82013-03-05 17:47:11 -08002919status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002920{
Mathias Agopian67106042013-03-14 19:18:13 -07002921 // called by ~LayerCleaner() when all references to the IBinder (handle)
2922 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002923 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924}
2925
Mathias Agopianb60314a2012-04-10 22:09:54 -07002926// ---------------------------------------------------------------------------
2927
Andy McFadden13a082e2012-08-24 10:16:42 -07002928void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002929 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002930 Vector<ComposerState> state;
2931 Vector<DisplayState> displays;
2932 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002933 d.what = DisplayState::eDisplayProjectionChanged |
2934 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002935 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002936 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002937 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002938 d.frame.makeInvalid();
2939 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002940 d.width = 0;
2941 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002942 displays.add(d);
2943 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002944 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002945
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2947 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002948 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002949
2950 {
2951 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2952 mCompositorTiming.interval = period;
2953 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002954}
2955
2956void SurfaceFlinger::initializeDisplays() {
2957 class MessageScreenInitialized : public MessageBase {
2958 SurfaceFlinger* flinger;
2959 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002960 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002961 virtual bool handler() {
2962 flinger->onInitializeDisplays();
2963 return true;
2964 }
2965 };
2966 sp<MessageBase> msg = new MessageScreenInitialized(this);
2967 postMessageAsync(msg); // we may be called from main thread, use async message
2968}
2969
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002970void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2971 int mode) {
2972 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2973 this);
2974 int32_t type = hw->getDisplayType();
2975 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002976
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002977 if (mode == currentMode) {
2978 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002979 return;
2980 }
2981
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002982 hw->setPowerMode(mode);
2983 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2984 ALOGW("Trying to set power mode for virtual display");
2985 return;
2986 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002987
Irvelffc9efc2016-07-27 15:16:37 -07002988 if (mInterceptor.isEnabled()) {
2989 Mutex::Autolock _l(mStateLock);
2990 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2991 if (idx < 0) {
2992 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2993 return;
2994 }
2995 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2996 }
2997
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002998 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002999 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003000 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003001 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3002 // FIXME: eventthread only knows about the main display right now
3003 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003004 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003005 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003007 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003008 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003009 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003010
3011 struct sched_param param = {0};
3012 param.sched_priority = 1;
3013 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3014 ALOGW("Couldn't set SCHED_FIFO on display on");
3015 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003016 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003017 // Turn off the display
3018 struct sched_param param = {0};
3019 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3020 ALOGW("Couldn't set SCHED_OTHER on display off");
3021 }
3022
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003023 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003024 disableHardwareVsync(true); // also cancels any in-progress resync
3025
Mathias Agopiancde87a32012-09-13 14:09:01 -07003026 // FIXME: eventthread only knows about the main display right now
3027 mEventThread->onScreenReleased();
3028 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003029
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003030 getHwComposer().setPowerMode(type, mode);
3031 mVisibleRegionsDirty = true;
3032 // from this point on, SF will stop drawing on this display
3033 } else {
3034 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003035 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003036}
3037
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003038void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3039 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003040 SurfaceFlinger& mFlinger;
3041 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003042 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003043 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044 MessageSetPowerMode(SurfaceFlinger& flinger,
3045 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3046 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003047 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003048 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003049 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003050 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003051 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003052 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003053 ALOGW("Attempt to set power mode = %d for virtual display",
3054 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003055 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003056 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003057 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003058 return true;
3059 }
3060 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003061 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003062 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003063}
3064
3065// ---------------------------------------------------------------------------
3066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3068{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003070
Mathias Agopianbd115332013-04-18 16:41:04 -07003071 IPCThreadState* ipc = IPCThreadState::self();
3072 const int pid = ipc->getCallingPid();
3073 const int uid = ipc->getCallingUid();
3074 if ((uid != AID_SHELL) &&
3075 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003076 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003077 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003079 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003080 // (this would indicate SF is stuck, but we want to be able to
3081 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003082 status_t err = mStateLock.timedLock(s2ns(1));
3083 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003084 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003085 result.appendFormat(
3086 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3087 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003088 }
3089
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003090 bool dumpAll = true;
3091 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003092 size_t numArgs = args.size();
3093 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003094 if ((index < numArgs) &&
3095 (args[index] == String16("--list"))) {
3096 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003097 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003098 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003099 }
3100
3101 if ((index < numArgs) &&
3102 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003103 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003104 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003105 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003106 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003107
3108 if ((index < numArgs) &&
3109 (args[index] == String16("--latency-clear"))) {
3110 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003111 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003112 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003113 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003114
3115 if ((index < numArgs) &&
3116 (args[index] == String16("--dispsync"))) {
3117 index++;
3118 mPrimaryDispSync.dump(result);
3119 dumpAll = false;
3120 }
Dan Stozab90cf072015-03-05 11:05:59 -08003121
3122 if ((index < numArgs) &&
3123 (args[index] == String16("--static-screen"))) {
3124 index++;
3125 dumpStaticScreenStats(result);
3126 dumpAll = false;
3127 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003128
3129 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003130 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003131 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003132 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003133 dumpAll = false;
3134 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003136
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003137 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003138 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003139 }
3140
Mathias Agopian9795c422009-08-26 16:36:26 -07003141 if (locked) {
3142 mStateLock.unlock();
3143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144 }
3145 write(fd, result.string(), result.size());
3146 return NO_ERROR;
3147}
3148
Dan Stozac7014012014-02-14 15:03:43 -08003149void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3150 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003151{
Robert Carr2047fae2016-11-28 14:09:09 -08003152 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003153 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003154 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003155}
3156
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003157void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003158 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003159{
3160 String8 name;
3161 if (index < args.size()) {
3162 name = String8(args[index]);
3163 index++;
3164 }
3165
Dan Stoza9e56aa02015-11-02 13:00:03 -08003166 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3167 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003168 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003169
3170 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003171 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003172 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003173 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003174 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003175 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003176 }
Robert Carr2047fae2016-11-28 14:09:09 -08003177 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003178 }
3179}
3180
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003181void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003182 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003183{
3184 String8 name;
3185 if (index < args.size()) {
3186 name = String8(args[index]);
3187 index++;
3188 }
3189
Robert Carr2047fae2016-11-28 14:09:09 -08003190 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003191 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003192 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003193 }
Robert Carr2047fae2016-11-28 14:09:09 -08003194 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003195
Svetoslavd85084b2014-03-20 10:28:31 -07003196 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003197}
3198
Jamie Gennis6547ff42013-07-16 20:12:42 -07003199// This should only be called from the main thread. Otherwise it would need
3200// the lock and should use mCurrentState rather than mDrawingState.
3201void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003202 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003203 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003204 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003205
3206 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3207}
3208
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003209void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003210{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003211 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003212#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003213 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003214#endif
3215#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003216 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003217#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003218 if (isLayerTripleBufferingDisabled())
3219 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003220 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003221}
3222
Dan Stozab90cf072015-03-05 11:05:59 -08003223void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3224{
3225 result.appendFormat("Static screen stats:\n");
3226 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3227 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3228 float percent = 100.0f *
3229 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3230 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3231 b + 1, bucketTimeSec, percent);
3232 }
3233 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3234 float percent = 100.0f *
3235 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3236 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3237 NUM_BUCKETS - 1, bucketTimeSec, percent);
3238}
3239
Dan Stozae77c7662016-05-13 11:37:28 -07003240void SurfaceFlinger::recordBufferingStats(const char* layerName,
3241 std::vector<OccupancyTracker::Segment>&& history) {
3242 Mutex::Autolock lock(mBufferingStatsMutex);
3243 auto& stats = mBufferingStats[layerName];
3244 for (const auto& segment : history) {
3245 if (!segment.usedThirdBuffer) {
3246 stats.twoBufferTime += segment.totalTime;
3247 }
3248 if (segment.occupancyAverage < 1.0f) {
3249 stats.doubleBufferedTime += segment.totalTime;
3250 } else if (segment.occupancyAverage < 2.0f) {
3251 stats.tripleBufferedTime += segment.totalTime;
3252 }
3253 ++stats.numSegments;
3254 stats.totalTime += segment.totalTime;
3255 }
3256}
3257
Brian Andersond6927fb2016-07-23 23:37:30 -07003258void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3259 result.appendFormat("Layer frame timestamps:\n");
3260
3261 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3262 const size_t count = currentLayers.size();
3263 for (size_t i=0 ; i<count ; i++) {
3264 currentLayers[i]->dumpFrameEvents(result);
3265 }
3266}
3267
Dan Stozae77c7662016-05-13 11:37:28 -07003268void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3269 result.append("Buffering stats:\n");
3270 result.append(" [Layer name] <Active time> <Two buffer> "
3271 "<Double buffered> <Triple buffered>\n");
3272 Mutex::Autolock lock(mBufferingStatsMutex);
3273 typedef std::tuple<std::string, float, float, float> BufferTuple;
3274 std::map<float, BufferTuple, std::greater<float>> sorted;
3275 for (const auto& statsPair : mBufferingStats) {
3276 const char* name = statsPair.first.c_str();
3277 const BufferingStats& stats = statsPair.second;
3278 if (stats.numSegments == 0) {
3279 continue;
3280 }
3281 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3282 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3283 stats.totalTime;
3284 float doubleBufferRatio = static_cast<float>(
3285 stats.doubleBufferedTime) / stats.totalTime;
3286 float tripleBufferRatio = static_cast<float>(
3287 stats.tripleBufferedTime) / stats.totalTime;
3288 sorted.insert({activeTime, {name, twoBufferRatio,
3289 doubleBufferRatio, tripleBufferRatio}});
3290 }
3291 for (const auto& sortedPair : sorted) {
3292 float activeTime = sortedPair.first;
3293 const BufferTuple& values = sortedPair.second;
3294 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3295 std::get<0>(values).c_str(), activeTime,
3296 std::get<1>(values), std::get<2>(values),
3297 std::get<3>(values));
3298 }
3299 result.append("\n");
3300}
3301
3302
Mathias Agopian74d211a2013-04-22 16:55:35 +02003303void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3304 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003305{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003306 bool colorize = false;
3307 if (index < args.size()
3308 && (args[index] == String16("--color"))) {
3309 colorize = true;
3310 index++;
3311 }
3312
3313 Colorizer colorizer(colorize);
3314
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003315 // figure out if we're stuck somewhere
3316 const nsecs_t now = systemTime();
3317 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3318 const nsecs_t inTransaction(mDebugInTransaction);
3319 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3320 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3321
3322 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003323 * Dump library configuration.
3324 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003325
3326 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003327 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003328 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003329 appendSfConfigString(result);
3330 appendUiConfigString(result);
3331 appendGuiConfigString(result);
3332 result.append("\n");
3333
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003334 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003335 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003336 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003337 result.append(SyncFeatures::getInstance().toString());
3338 result.append("\n");
3339
Dan Stoza9e56aa02015-11-02 13:00:03 -08003340 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3341
Andy McFadden41d67d72014-04-25 16:58:34 -07003342 colorizer.bold(result);
3343 result.append("DispSync configuration: ");
3344 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003345 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3346 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003347 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3348 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003349 result.append("\n");
3350
Dan Stozab90cf072015-03-05 11:05:59 -08003351 // Dump static screen stats
3352 result.append("\n");
3353 dumpStaticScreenStats(result);
3354 result.append("\n");
3355
Dan Stozae77c7662016-05-13 11:37:28 -07003356 dumpBufferingStats(result);
3357
Andy McFadden4803b742012-09-24 19:07:20 -07003358 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003359 * Dump the visible layer list
3360 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003361 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003362 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003363 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003364 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003365 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003366 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003367
3368 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003369 * Dump Display state
3370 */
3371
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003372 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003373 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003374 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003375 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3376 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003377 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003378 }
3379
3380 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003381 * Dump SurfaceFlinger global state
3382 */
3383
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003384 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003385 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003386 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003387
Mathias Agopian888c8222012-08-04 21:10:38 -07003388 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003389 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003390
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003391 colorizer.bold(result);
3392 result.appendFormat("EGL implementation : %s\n",
3393 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3394 colorizer.reset(result);
3395 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003396 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003397
Mathias Agopian875d8e12013-06-07 15:35:48 -07003398 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003399
Mathias Agopian42977342012-08-05 00:40:46 -07003400 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003401 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3402 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003403 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003404 " last eglSwapBuffers() time: %f us\n"
3405 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003406 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003407 " refresh-rate : %f fps\n"
3408 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003409 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003410 " gpu_to_cpu_unsupported : %d\n"
3411 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412 mLastSwapBufferTime/1000.0,
3413 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003414 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003415 1e9 / activeConfig->getVsyncPeriod(),
3416 activeConfig->getDpiX(),
3417 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003418 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003419
Mathias Agopian74d211a2013-04-22 16:55:35 +02003420 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003422
Mathias Agopian74d211a2013-04-22 16:55:35 +02003423 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425
3426 /*
3427 * VSYNC state
3428 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003429 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003430 result.append("\n");
3431
3432 /*
3433 * HWC layer minidump
3434 */
3435 for (size_t d = 0; d < mDisplays.size(); d++) {
3436 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3437 int32_t hwcId = displayDevice->getHwcDisplayId();
3438 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3439 continue;
3440 }
3441
3442 result.appendFormat("Display %d HWC layers:\n", hwcId);
3443 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003444 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003445 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003446 });
Dan Stozae22aec72016-08-01 13:20:59 -07003447 result.append("\n");
3448 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003449
3450 /*
3451 * Dump HWComposer state
3452 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003453 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003454 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003455 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003456 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003457 result.appendFormat(" h/w composer %s\n",
3458 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003459 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003460
3461 /*
3462 * Dump gralloc state
3463 */
3464 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3465 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003466}
3467
Mathias Agopian13127d82013-03-05 17:47:11 -08003468const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003469SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003470 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003471 wp<IBinder> dpy;
3472 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3473 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3474 dpy = mDisplays.keyAt(i);
3475 break;
3476 }
3477 }
3478 if (dpy == NULL) {
3479 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3480 // Just use the primary display so we have something to return
3481 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3482 }
3483 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003484}
3485
Keun young Park63f165f2012-08-31 10:53:36 -07003486bool SurfaceFlinger::startDdmConnection()
3487{
3488 void* libddmconnection_dso =
3489 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3490 if (!libddmconnection_dso) {
3491 return false;
3492 }
3493 void (*DdmConnection_start)(const char* name);
3494 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003495 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003496 if (!DdmConnection_start) {
3497 dlclose(libddmconnection_dso);
3498 return false;
3499 }
3500 (*DdmConnection_start)(getServiceName());
3501 return true;
3502}
3503
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003504status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 switch (code) {
3506 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003507 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003509 case CLEAR_ANIMATION_FRAME_STATS:
3510 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003511 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003512 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 {
3514 // codes that require permission check
3515 IPCThreadState* ipc = IPCThreadState::self();
3516 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003517 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003518 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003519 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003520 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003521 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003523 break;
3524 }
Robert Carr1db73f62016-12-21 12:58:51 -08003525 /*
3526 * Calling setTransactionState is safe, because you need to have been
3527 * granted a reference to Client* and Handle* to do anything with it.
3528 *
3529 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3530 */
3531 case SET_TRANSACTION_STATE:
3532 case CREATE_SCOPED_CONNECTION:
3533 {
3534 return OK;
3535 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003536 case CAPTURE_SCREEN:
3537 {
3538 // codes that require permission check
3539 IPCThreadState* ipc = IPCThreadState::self();
3540 const int pid = ipc->getCallingPid();
3541 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003542 if ((uid != AID_GRAPHICS) &&
3543 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003544 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003545 return PERMISSION_DENIED;
3546 }
3547 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 }
3549 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003550 return OK;
3551}
3552
3553status_t SurfaceFlinger::onTransact(
3554 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3555{
3556 status_t credentialCheck = CheckTransactCodeCredentials(code);
3557 if (credentialCheck != OK) {
3558 return credentialCheck;
3559 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003560
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3562 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003563 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003564 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003565 IPCThreadState* ipc = IPCThreadState::self();
3566 const int pid = ipc->getCallingPid();
3567 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003568 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003569 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 return PERMISSION_DENIED;
3571 }
3572 int n;
3573 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003574 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003575 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 return NO_ERROR;
3577 case 1002: // SHOW_UPDATES
3578 n = data.readInt32();
3579 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003580 invalidateHwcGeometry();
3581 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003584 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003585 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003587 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003588 setTransactionFlags(
3589 eTransactionNeeded|
3590 eDisplayTransactionNeeded|
3591 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003592 return NO_ERROR;
3593 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003594 case 1006:{ // send empty update
3595 signalRefresh();
3596 return NO_ERROR;
3597 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003598 case 1008: // toggle use of hw composer
3599 n = data.readInt32();
3600 mDebugDisableHWC = n ? 1 : 0;
3601 invalidateHwcGeometry();
3602 repaintEverything();
3603 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003604 case 1009: // toggle use of transform hint
3605 n = data.readInt32();
3606 mDebugDisableTransformHint = n ? 1 : 0;
3607 invalidateHwcGeometry();
3608 repaintEverything();
3609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003611 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 reply->writeInt32(0);
3613 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003614 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003615 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616 return NO_ERROR;
3617 case 1013: {
3618 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003619 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3620 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003621 return NO_ERROR;
3622 }
3623 case 1014: {
3624 // daltonize
3625 n = data.readInt32();
3626 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003627 case 1:
3628 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3629 break;
3630 case 2:
3631 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3632 break;
3633 case 3:
3634 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3635 break;
3636 default:
3637 mDaltonizer.setType(ColorBlindnessType::None);
3638 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003639 }
3640 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003641 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003642 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003643 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003644 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003645 invalidateHwcGeometry();
3646 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003647 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003649 case 1015: {
3650 // apply a color matrix
3651 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003652 if (n) {
3653 // color matrix is sent as mat3 matrix followed by vec3
3654 // offset, then packed into a mat4 where the last row is
3655 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003656 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003657 for (size_t j = 0; j < 4; j++) {
3658 mColorMatrix[i][j] = data.readFloat();
3659 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003660 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003661 } else {
3662 mColorMatrix = mat4();
3663 }
3664 invalidateHwcGeometry();
3665 repaintEverything();
3666 return NO_ERROR;
3667 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003668 // This is an experimental interface
3669 // Needs to be shifted to proper binder interface when we productize
3670 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003671 n = data.readInt32();
3672 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003673 return NO_ERROR;
3674 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003675 case 1017: {
3676 n = data.readInt32();
3677 mForceFullDamage = static_cast<bool>(n);
3678 return NO_ERROR;
3679 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003680 case 1018: { // Modify Choreographer's phase offset
3681 n = data.readInt32();
3682 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3683 return NO_ERROR;
3684 }
3685 case 1019: { // Modify SurfaceFlinger's phase offset
3686 n = data.readInt32();
3687 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3688 return NO_ERROR;
3689 }
Irvel468051e2016-06-13 16:44:44 -07003690 case 1020: { // Layer updates interceptor
3691 n = data.readInt32();
3692 if (n) {
3693 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003694 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003695 }
3696 else{
3697 ALOGV("Interceptor disabled");
3698 mInterceptor.disable();
3699 }
3700 return NO_ERROR;
3701 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003702 case 1021: { // Disable HWC virtual displays
3703 n = data.readInt32();
3704 mUseHwcVirtualDisplays = !n;
3705 return NO_ERROR;
3706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 }
3708 }
3709 return err;
3710}
3711
Mathias Agopian53331da2011-08-22 21:44:41 -07003712void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003713 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003714 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003715}
3716
Mathias Agopian59119e62010-10-11 12:37:43 -07003717// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003718// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003719// ---------------------------------------------------------------------------
3720
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003721/* The code below is here to handle b/8734824
3722 *
3723 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003724 * from the surfaceflinger thread to the calling binder thread, where they
3725 * are executed. This allows the calling thread in the calling process to be
3726 * reused and not depend on having "enough" binder threads to handle the
3727 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003728 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003729class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003730 /* Parts of GraphicProducerWrapper are run on two different threads,
3731 * communicating by sending messages via Looper but also by shared member
3732 * data. Coherence maintenance is subtle and in places implicit (ugh).
3733 *
3734 * Don't rely on Looper's sendMessage/handleMessage providing
3735 * release/acquire semantics for any data not actually in the Message.
3736 * Data going from surfaceflinger to binder threads needs to be
3737 * synchronized explicitly.
3738 *
3739 * Barrier open/wait do provide release/acquire semantics. This provides
3740 * implicit synchronization for data coming back from binder to
3741 * surfaceflinger threads.
3742 */
3743
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003744 sp<IGraphicBufferProducer> impl;
3745 sp<Looper> looper;
3746 status_t result;
3747 bool exitPending;
3748 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003749 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003750 uint32_t code;
3751 Parcel const* data;
3752 Parcel* reply;
3753
3754 enum {
3755 MSG_API_CALL,
3756 MSG_EXIT
3757 };
3758
3759 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003760 * Called on surfaceflinger thread. This is called by our "fake"
3761 * BpGraphicBufferProducer. We package the data and reply Parcel and
3762 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003763 */
3764 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003765 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003766 this->code = code;
3767 this->data = &data;
3768 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003769 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003770 // if we've exited, we run the message synchronously right here.
3771 // note (JH): as far as I can tell from looking at the code, this
3772 // never actually happens. if it does, i'm not sure if it happens
3773 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003774 handleMessage(Message(MSG_API_CALL));
3775 } else {
3776 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003777 // Prevent stores to this->{code, data, reply} from being
3778 // reordered later than the construction of Message.
3779 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003780 looper->sendMessage(this, Message(MSG_API_CALL));
3781 barrier.wait();
3782 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003783 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003784 }
3785
3786 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003787 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003788 * call the real BpGraphicBufferProducer.
3789 */
3790 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003791 int what = message.what;
3792 // Prevent reads below from happening before the read from Message
3793 atomic_thread_fence(memory_order_acquire);
3794 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003795 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003796 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003797 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003798 exitRequested = true;
3799 }
3800 }
3801
3802public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003803 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003804 : impl(impl),
3805 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003806 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003807 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003808 exitRequested(false),
3809 code(0),
3810 data(NULL),
3811 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003812 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003813
Jesse Hallb154c422014-07-13 12:47:02 -07003814 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003815 status_t waitForResponse() {
3816 do {
3817 looper->pollOnce(-1);
3818 } while (!exitRequested);
3819 return result;
3820 }
3821
Jesse Hallb154c422014-07-13 12:47:02 -07003822 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003823 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003824 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003825 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003826 // Ensure this->result is visible to the binder thread before it
3827 // handles the message.
3828 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829 looper->sendMessage(this, Message(MSG_EXIT));
3830 }
3831};
3832
3833
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003834status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3835 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003836 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003837 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003838 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003839
3840 if (CC_UNLIKELY(display == 0))
3841 return BAD_VALUE;
3842
3843 if (CC_UNLIKELY(producer == 0))
3844 return BAD_VALUE;
3845
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003846 // if we have secure windows on this display, never allow the screen capture
3847 // unless the producer interface is local (i.e.: we can take a screenshot for
3848 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003849 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003850
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003851 // Convert to surfaceflinger's internal rotation type.
3852 Transform::orientation_flags rotationFlags;
3853 switch (rotation) {
3854 case ISurfaceComposer::eRotateNone:
3855 rotationFlags = Transform::ROT_0;
3856 break;
3857 case ISurfaceComposer::eRotate90:
3858 rotationFlags = Transform::ROT_90;
3859 break;
3860 case ISurfaceComposer::eRotate180:
3861 rotationFlags = Transform::ROT_180;
3862 break;
3863 case ISurfaceComposer::eRotate270:
3864 rotationFlags = Transform::ROT_270;
3865 break;
3866 default:
3867 rotationFlags = Transform::ROT_0;
3868 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3869 break;
3870 }
3871
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003872 class MessageCaptureScreen : public MessageBase {
3873 SurfaceFlinger* flinger;
3874 sp<IBinder> display;
3875 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003876 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003877 uint32_t reqWidth, reqHeight;
3878 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003879 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003880 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003881 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003882 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003883 public:
3884 MessageCaptureScreen(SurfaceFlinger* flinger,
3885 const sp<IBinder>& display,
3886 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003887 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003888 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003889 bool useIdentityTransform,
3890 Transform::orientation_flags rotation,
3891 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003892 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003893 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003894 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003895 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003896 rotation(rotation), result(PERMISSION_DENIED),
3897 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003898 {
3899 }
3900 status_t getResult() const {
3901 return result;
3902 }
3903 virtual bool handler() {
3904 Mutex::Autolock _l(flinger->mStateLock);
3905 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003906 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003907 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003908 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003909 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003910 return true;
3911 }
3912 };
3913
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003914 // this creates a "fake" BBinder which will serve as a "fake" remote
3915 // binder to receive the marshaled calls and forward them to the
3916 // real remote (a BpGraphicBufferProducer)
3917 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3918
3919 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3920 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003921 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003922 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003923 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003924 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003925
3926 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003927 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003928 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003929 }
3930 return res;
3931}
3932
Mathias Agopian180f10d2013-04-10 22:55:41 -07003933
3934void SurfaceFlinger::renderScreenImplLocked(
3935 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003936 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003937 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003938 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003939{
3940 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003941 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003942
3943 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003944 const int32_t hw_w = hw->getWidth();
3945 const int32_t hw_h = hw->getHeight();
3946 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003947 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003948
Dan Stozac1879002014-05-22 15:59:05 -07003949 // if a default or invalid sourceCrop is passed in, set reasonable values
3950 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3951 !sourceCrop.isValid()) {
3952 sourceCrop.setLeftTop(Point(0, 0));
3953 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3954 }
3955
3956 // ensure that sourceCrop is inside screen
3957 if (sourceCrop.left < 0) {
3958 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3959 }
Dan Stozabe31f442014-06-11 11:20:54 -07003960 if (sourceCrop.right > hw_w) {
3961 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003962 }
3963 if (sourceCrop.top < 0) {
3964 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3965 }
Dan Stozabe31f442014-06-11 11:20:54 -07003966 if (sourceCrop.bottom > hw_h) {
3967 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003968 }
3969
Mathias Agopian180f10d2013-04-10 22:55:41 -07003970 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003971 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003972
3973 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003974 engine.setViewportAndProjection(
3975 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003976 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003977
3978 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003979 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003980
Robert Carr1f0a16a2016-10-24 16:27:39 -07003981 // We loop through the first level of layers without traversing,
3982 // as we need to interpret min/max layer Z in the top level Z space.
3983 for (const auto& layer : mDrawingState.layersSortedByZ) {
3984 if (layer->getLayerStack() != hw->getLayerStack()) {
3985 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003986 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003987 const Layer::State& state(layer->getDrawingState());
3988 if (state.z < minLayerZ || state.z > maxLayerZ) {
3989 continue;
3990 }
3991 layer->traverseInZOrder([&](Layer* layer) {
3992 if (!layer->isVisible()) {
3993 return;
3994 }
3995 if (filtering) layer->setFiltering(true);
3996 layer->draw(hw, useIdentityTransform);
3997 if (filtering) layer->setFiltering(false);
3998 });
3999 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004000
Mathias Agopian931bda12013-08-28 18:11:46 -07004001 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004002}
4003
4004
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004005status_t SurfaceFlinger::captureScreenImplLocked(
4006 const sp<const DisplayDevice>& hw,
4007 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004008 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004009 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004010 bool useIdentityTransform, Transform::orientation_flags rotation,
4011 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004012{
4013 ATRACE_CALL();
4014
Mathias Agopian180f10d2013-04-10 22:55:41 -07004015 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004016 uint32_t hw_w = hw->getWidth();
4017 uint32_t hw_h = hw->getHeight();
4018
4019 if (rotation & Transform::ROT_90) {
4020 std::swap(hw_w, hw_h);
4021 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004022
Mathias Agopian180f10d2013-04-10 22:55:41 -07004023 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4024 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4025 reqWidth, reqHeight, hw_w, hw_h);
4026 return BAD_VALUE;
4027 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004028
Mathias Agopian180f10d2013-04-10 22:55:41 -07004029 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4030 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4031
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004032 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004033 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004034 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004035 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4036 (state.z < minLayerZ || state.z > maxLayerZ)) {
4037 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004038 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004039 layer->traverseInZOrder([&](Layer *layer) {
4040 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4041 layer->isSecure());
4042 });
4043 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004044
4045 if (!isLocalScreenshot && secureLayerIsVisible) {
4046 ALOGW("FB is protected: PERMISSION_DENIED");
4047 return PERMISSION_DENIED;
4048 }
4049
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004050 // create a surface (because we're a producer, and we need to
4051 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004052 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004053
4054 // Put the screenshot Surface into async mode so that
4055 // Layer::headFenceHasSignaled will always return true and we'll latch the
4056 // first buffer regardless of whether or not its acquire fence has
4057 // signaled. This is needed to avoid a race condition in the rotation
4058 // animation. See b/30209608
4059 sur->setAsyncMode(true);
4060
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004061 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004062
Michael Lentine5a16a622015-05-21 13:48:24 -07004063 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4064 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004065 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4066 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004067
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004068 int err = 0;
4069 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004070 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004071 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4072 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004073
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004074 if (err == NO_ERROR) {
4075 ANativeWindowBuffer* buffer;
4076 /* TODO: Once we have the sync framework everywhere this can use
4077 * server-side waits on the fence that dequeueBuffer returns.
4078 */
4079 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4080 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004081 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004082 // create an EGLImage from the buffer so we can later
4083 // turn it into a texture
4084 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4085 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4086 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004087 // this binds the given EGLImage as a framebuffer for the
4088 // duration of this scope.
4089 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4090 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004091 // this will in fact render into our dequeued buffer
4092 // via an FBO, which means we didn't have to create
4093 // an EGLSurface and therefore we're not
4094 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004095 renderScreenImplLocked(
4096 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4097 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004098
Riley Andrews86639902014-08-15 12:27:24 -07004099 // Attempt to create a sync khr object that can produce a sync point. If that
4100 // isn't available, create a non-dupable sync object in the fallback path and
4101 // wait on it directly.
4102 EGLSyncKHR sync;
4103 if (!DEBUG_SCREENSHOTS) {
4104 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004105 // native fence fd will not be populated until flush() is done.
4106 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004107 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004108 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004109 }
Riley Andrews86639902014-08-15 12:27:24 -07004110 if (sync != EGL_NO_SYNC_KHR) {
4111 // get the sync fd
4112 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4113 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4114 ALOGW("captureScreen: failed to dup sync khr object");
4115 syncFd = -1;
4116 }
4117 eglDestroySyncKHR(mEGLDisplay, sync);
4118 } else {
4119 // fallback path
4120 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4121 if (sync != EGL_NO_SYNC_KHR) {
4122 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4123 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4124 EGLint eglErr = eglGetError();
4125 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4126 ALOGW("captureScreen: fence wait timed out");
4127 } else {
4128 ALOGW_IF(eglErr != EGL_SUCCESS,
4129 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4130 }
4131 eglDestroySyncKHR(mEGLDisplay, sync);
4132 } else {
4133 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4134 }
4135 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004136 if (DEBUG_SCREENSHOTS) {
4137 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4138 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4139 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4140 hw, minLayerZ, maxLayerZ);
4141 delete [] pixels;
4142 }
4143
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004144 } else {
4145 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4146 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004147 window->cancelBuffer(window, buffer, syncFd);
4148 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004149 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004150 // destroy our image
4151 eglDestroyImageKHR(mEGLDisplay, image);
4152 } else {
4153 result = BAD_VALUE;
4154 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004155 if (buffer) {
4156 // queueBuffer takes ownership of syncFd
4157 result = window->queueBuffer(window, buffer, syncFd);
4158 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004159 }
4160 } else {
4161 result = BAD_VALUE;
4162 }
4163 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4164 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004165
Mathias Agopian74c40c02010-09-29 13:02:36 -07004166 return result;
4167}
4168
Mathias Agopiand5556842013-09-19 17:08:37 -07004169void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004170 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004171 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004172 for (size_t y=0 ; y<h ; y++) {
4173 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4174 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004175 if (p[x] != 0xFF000000) return;
4176 }
4177 }
4178 ALOGE("*** we just took a black screenshot ***\n"
4179 "requested minz=%d, maxz=%d, layerStack=%d",
4180 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004181
Robert Carr2047fae2016-11-28 14:09:09 -08004182 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004183 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004184 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004185 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4186 state.z <= maxLayerZ) {
4187 layer->traverseInZOrder([&](Layer* layer) {
4188 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4189 layer->isVisible() ? '+' : '-',
4190 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004191 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004192 i++;
4193 });
4194 }
4195 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004196 }
4197}
4198
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004199// ---------------------------------------------------------------------------
4200
Robert Carr2047fae2016-11-28 14:09:09 -08004201void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4202 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004203}
4204
Robert Carr2047fae2016-11-28 14:09:09 -08004205void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4206 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004207}
4208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004210
4211
4212#if defined(__gl_h_)
4213#error "don't include gl/gl.h in this file"
4214#endif
4215
4216#if defined(__gl2_h_)
4217#error "don't include gl2/gl2.h in this file"
4218#endif