blob: d2dddba27d9866b1fd5d0eb6185f252439e08039 [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: {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001269 updateVrMode();
1270
Dan Stoza50182882016-07-08 12:02:20 -07001271 bool frameMissed = !mHadClientComposition &&
1272 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001273 (mPreviousPresentFence->getSignalTime() ==
1274 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001275 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001276 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001277 signalLayerUpdate();
1278 break;
1279 }
1280
Dan Stoza6b9454d2014-11-07 16:00:59 -08001281 bool refreshNeeded = handleMessageTransaction();
1282 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001283 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001284 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001285 // Signal a refresh if a transaction modified the window state,
1286 // a new buffer was latched, or if HWC has requested a full
1287 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001288 signalRefresh();
1289 }
1290 break;
1291 }
1292 case MessageQueue::REFRESH: {
1293 handleMessageRefresh();
1294 break;
1295 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001296 }
1297}
1298
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001300 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001301 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001302 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001303 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001304 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001305 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001306}
1307
Dan Stoza6b9454d2014-11-07 16:00:59 -08001308bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001309 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001310 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001311}
1312
1313void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001314 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001315
Pablo Ceballos40845df2016-01-25 17:41:15 -08001316 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001317
Brian Andersond6927fb2016-07-23 23:37:30 -07001318 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001319 rebuildLayerStacks();
1320 setUpHWComposer();
1321 doDebugFlashRegions();
1322 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001323 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001324
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001325 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001326
1327 mHadClientComposition = false;
1328 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1329 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1330 mHadClientComposition = mHadClientComposition ||
1331 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1332 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001333
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001335}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001336
Mathias Agopiancd60f992012-08-16 16:28:27 -07001337void SurfaceFlinger::doDebugFlashRegions()
1338{
1339 // is debugging enabled
1340 if (CC_LIKELY(!mDebugRegion))
1341 return;
1342
1343 const bool repaintEverything = mRepaintEverything;
1344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1345 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001346 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001347 // transform the dirty region into this screen's coordinate space
1348 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1349 if (!dirtyRegion.isEmpty()) {
1350 // redraw the whole screen
1351 doComposeSurfaces(hw, Region(hw->bounds()));
1352
1353 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001354 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001355 RenderEngine& engine(getRenderEngine());
1356 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1357
Mathias Agopianda27af92012-09-13 18:17:13 -07001358 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001359 }
1360 }
1361 }
1362
1363 postFramebuffer();
1364
1365 if (mDebugRegion > 1) {
1366 usleep(mDebugRegion * 1000);
1367 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001368
Dan Stoza9e56aa02015-11-02 13:00:03 -08001369 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001370 auto& displayDevice = mDisplays[displayId];
1371 if (!displayDevice->isDisplayOn()) {
1372 continue;
1373 }
1374
1375 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1377 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001378 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001379}
1380
Brian Andersond6927fb2016-07-23 23:37:30 -07001381void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001382{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383 ATRACE_CALL();
1384 ALOGV("preComposition");
1385
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001387 mDrawingState.traverseInZOrder([&](Layer* layer) {
1388 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389 needExtraInvalidate = true;
1390 }
Robert Carr2047fae2016-11-28 14:09:09 -08001391 });
1392
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 if (needExtraInvalidate) {
1394 signalLayerUpdate();
1395 }
1396}
1397
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001398void SurfaceFlinger::updateCompositorTiming(
1399 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1400 std::shared_ptr<FenceTime>& presentFenceTime) {
1401 // Update queue of past composite+present times and determine the
1402 // most recently known composite to present latency.
1403 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1404 nsecs_t compositeToPresentLatency = -1;
1405 while (!mCompositePresentTimes.empty()) {
1406 CompositePresentTime& cpt = mCompositePresentTimes.front();
1407 // Cached values should have been updated before calling this method,
1408 // which helps avoid duplicate syscalls.
1409 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1410 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1411 break;
1412 }
1413 compositeToPresentLatency = displayTime - cpt.composite;
1414 mCompositePresentTimes.pop();
1415 }
1416
1417 // Don't let mCompositePresentTimes grow unbounded, just in case.
1418 while (mCompositePresentTimes.size() > 16) {
1419 mCompositePresentTimes.pop();
1420 }
1421
1422 // Integer division and modulo round toward 0 not -inf, so we need to
1423 // treat negative and positive offsets differently.
1424 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1425 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1426 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1427
1428 // Snap the latency to a value that removes scheduling jitter from the
1429 // composition and present times, which often have >1ms of jitter.
1430 // Reducing jitter is important if an app attempts to extrapolate
1431 // something (such as user input) to an accurate diasplay time.
1432 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1433 // with (presentLatency % interval).
1434 nsecs_t snappedCompositeToPresentLatency = -1;
1435 if (compositeToPresentLatency >= 0) {
1436 nsecs_t bias = vsyncInterval / 2;
1437 int64_t extraVsyncs =
1438 (compositeToPresentLatency - idealLatency + bias) /
1439 vsyncInterval;
1440 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1441 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1442 }
1443
1444 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1445 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1446 mCompositorTiming.interval = vsyncInterval;
1447 if (snappedCompositeToPresentLatency >= 0) {
1448 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1449 }
1450}
1451
1452void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001454 ATRACE_CALL();
1455 ALOGV("postComposition");
1456
Brian Anderson3546a3f2016-07-14 11:51:14 -07001457 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001458 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001459 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001460 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001461 }
1462
Brian Andersond6927fb2016-07-23 23:37:30 -07001463 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001464
1465 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1466 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1467 glCompositionDoneFenceTime =
1468 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1469 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1470 } else {
1471 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1472 }
1473 mGlCompositionDoneTimeline.updateSignalTimes();
1474
1475 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1476 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1477 mDisplayTimeline.push(displayFenceTime);
1478 mDisplayTimeline.updateSignalTimes();
1479
1480 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1481 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1482 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1483 presentFenceTime = &displayFenceTime;
1484 } else {
1485 retireFenceTime = &displayFenceTime;
1486 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487
1488 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1489 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1490
1491 // We use the refreshStartTime which might be sampled a little later than
1492 // when we started doing work for this frame, but that should be okay
1493 // since updateCompositorTiming has snapping logic.
1494 updateCompositorTiming(
1495 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1496
Robert Carr2047fae2016-11-28 14:09:09 -08001497 mDrawingState.traverseInZOrder([&](Layer* layer) {
1498 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001500 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001501 recordBufferingStats(layer->getName().string(),
1502 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001503 }
Robert Carr2047fae2016-11-28 14:09:09 -08001504 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001505
Brian Anderson3d4039d2016-09-23 16:31:30 -07001506 if (displayFence->isValid()) {
1507 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001508 enableHardwareVsync();
1509 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001510 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001511 }
1512 }
1513
Andy McFadden5167ec62014-05-22 13:08:43 -07001514 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001515 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001516 enableHardwareVsync();
1517 }
1518 }
1519
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001520 if (mAnimCompositionPending) {
1521 mAnimCompositionPending = false;
1522
Brian Anderson3d4039d2016-09-23 16:31:30 -07001523 if (displayFenceTime->isValid()) {
1524 mAnimFrameTracker.setActualPresentFence(
1525 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001526 } else {
1527 // The HWC doesn't support present fences, so use the refresh
1528 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 nsecs_t presentTime =
1530 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001531 mAnimFrameTracker.setActualPresentTime(presentTime);
1532 }
1533 mAnimFrameTracker.advanceFrame();
1534 }
Dan Stozab90cf072015-03-05 11:05:59 -08001535
1536 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1537 return;
1538 }
1539
1540 nsecs_t currentTime = systemTime();
1541 if (mHasPoweredOff) {
1542 mHasPoweredOff = false;
1543 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001544 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001545 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001546 if (numPeriods < NUM_BUCKETS - 1) {
1547 mFrameBuckets[numPeriods] += elapsedTime;
1548 } else {
1549 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1550 }
1551 mTotalTime += elapsedTime;
1552 }
1553 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554}
1555
1556void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 ATRACE_CALL();
1558 ALOGV("rebuildLayerStacks");
1559
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001561 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001563 mVisibleRegionsDirty = false;
1564 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001565
Mathias Agopian92a979a2012-08-02 18:32:23 -07001566 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001567 Region opaqueRegion;
1568 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001569 Vector<sp<Layer>> layersSortedByZ;
1570 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1571 const Transform& tr(displayDevice->getTransform());
1572 const Rect bounds(displayDevice->getBounds());
1573 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001574 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001575 displayDevice->getLayerStack(), dirtyRegion,
1576 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001577
Robert Carr2047fae2016-11-28 14:09:09 -08001578 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001579 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001580 Region drawRegion(tr.transform(
1581 layer->visibleNonTransparentRegion));
1582 drawRegion.andSelf(bounds);
1583 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001584 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001585 } else {
1586 // Clear out the HWC layer if this layer was
1587 // previously visible, but no longer is
1588 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1589 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001590 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001591 }
Robert Carr2047fae2016-11-28 14:09:09 -08001592 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001593 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001594 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1595 displayDevice->undefinedRegion.set(bounds);
1596 displayDevice->undefinedRegion.subtractSelf(
1597 tr.transform(opaqueRegion));
1598 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001599 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001600 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001602
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001604 ATRACE_CALL();
1605 ALOGV("setUpHWComposer");
1606
Jesse Hall028dc8f2013-08-20 16:35:32 -07001607 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001608 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1609 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1610 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1611
1612 // If nothing has changed (!dirty), don't recompose.
1613 // If something changed, but we don't currently have any visible layers,
1614 // and didn't when we last did a composition, then skip it this time.
1615 // The second rule does two things:
1616 // - When all layers are removed from a display, we'll emit one black
1617 // frame, then nothing more until we get new layers.
1618 // - When a display is created with a private layer stack, we won't
1619 // emit any black frames until a layer is added to the layer stack.
1620 bool mustRecompose = dirty && !(empty && wasEmpty);
1621
1622 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1623 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1624 mustRecompose ? "doing" : "skipping",
1625 dirty ? "+" : "-",
1626 empty ? "+" : "-",
1627 wasEmpty ? "+" : "-");
1628
Dan Stoza71433162014-02-04 16:22:36 -08001629 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001630
1631 if (mustRecompose) {
1632 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1633 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001634 }
1635
Dan Stoza9e56aa02015-11-02 13:00:03 -08001636 // build the h/w work list
1637 if (CC_UNLIKELY(mGeometryInvalid)) {
1638 mGeometryInvalid = false;
1639 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1640 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1641 const auto hwcId = displayDevice->getHwcDisplayId();
1642 if (hwcId >= 0) {
1643 const Vector<sp<Layer>>& currentLayers(
1644 displayDevice->getVisibleLayersSortedByZ());
1645 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001646 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001647 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001648 if (!layer->hasHwcLayer(hwcId)) {
1649 auto hwcLayer = mHwc->createLayer(hwcId);
1650 if (hwcLayer) {
1651 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1652 } else {
1653 layer->forceClientComposition(hwcId);
1654 foundLayerWithoutHwc = true;
1655 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001656 }
1657 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001658
Robert Carrae060832016-11-28 10:51:00 -08001659 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001660 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001661 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001662 }
1663 }
1664 }
1665 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666 }
Riley Andrews03414a12014-07-01 14:22:59 -07001667
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001668
1669 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1670
Dan Stoza9e56aa02015-11-02 13:00:03 -08001671 // Set the per-frame data
1672 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1673 auto& displayDevice = mDisplays[displayId];
1674 const auto hwcId = displayDevice->getHwcDisplayId();
1675 if (hwcId < 0) {
1676 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001677 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001678 if (colorMatrix != mPreviousColorMatrix) {
1679 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1680 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1681 "display %zd: %d", displayId, result);
1682 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1684 layer->setPerFrameData(displayDevice);
1685 }
1686 }
1687
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001688 mPreviousColorMatrix = colorMatrix;
1689
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001691 auto& displayDevice = mDisplays[displayId];
1692 if (!displayDevice->isDisplayOn()) {
1693 continue;
1694 }
1695
1696 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1698 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001699 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001701
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702void SurfaceFlinger::doComposition() {
1703 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 ALOGV("doComposition");
1705
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001706 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001707 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001708 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001709 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 // transform the dirty region into this screen's coordinate space
1711 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001712
1713 // repaint the framebuffer (if needed)
1714 doDisplayComposition(hw, dirtyRegion);
1715
Mathias Agopiancd60f992012-08-16 16:28:27 -07001716 hw->dirtyRegion.clear();
1717 hw->flip(hw->swapRegion);
1718 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001719 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001720 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001721 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001722}
1723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001724void SurfaceFlinger::postFramebuffer()
1725{
Mathias Agopian841cde52012-03-01 15:44:37 -08001726 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001728
Mathias Agopiana44b0412011-10-16 18:46:35 -07001729 const nsecs_t now = systemTime();
1730 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001731
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1733 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001734 if (!displayDevice->isDisplayOn()) {
1735 continue;
1736 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 const auto hwcId = displayDevice->getHwcDisplayId();
1738 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001739 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001740 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001741 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001742 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1744 sp<Fence> releaseFence = Fence::NO_FENCE;
1745 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1746 releaseFence = displayDevice->getClientTargetAcquireFence();
1747 } else {
1748 auto hwcLayer = layer->getHwcLayer(hwcId);
1749 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001750 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 layer->onLayerDisplayed(releaseFence);
1752 }
1753 if (hwcId >= 0) {
1754 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001755 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001756 }
1757
Mathias Agopiana44b0412011-10-16 18:46:35 -07001758 mLastSwapBufferTime = systemTime() - now;
1759 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001760
1761 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1762 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1763 logFrameStats();
1764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765}
1766
Mathias Agopian87baae12012-07-31 12:38:26 -07001767void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001768{
Mathias Agopian841cde52012-03-01 15:44:37 -08001769 ATRACE_CALL();
1770
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001771 // here we keep a copy of the drawing state (that is the state that's
1772 // going to be overwritten by handleTransactionLocked()) outside of
1773 // mStateLock so that the side-effects of the State assignment
1774 // don't happen with mStateLock held (which can cause deadlocks).
1775 State drawingState(mDrawingState);
1776
Mathias Agopianca4d3602011-05-19 15:38:14 -07001777 Mutex::Autolock _l(mStateLock);
1778 const nsecs_t now = systemTime();
1779 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001780
Mathias Agopianca4d3602011-05-19 15:38:14 -07001781 // Here we're guaranteed that some transaction flags are set
1782 // so we can call handleTransactionLocked() unconditionally.
1783 // We call getTransactionFlags(), which will also clear the flags,
1784 // with mStateLock held to guarantee that mCurrentState won't change
1785 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001786
Mathias Agopiane57f2922012-08-09 16:29:12 -07001787 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001788 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001789
Mathias Agopianca4d3602011-05-19 15:38:14 -07001790 mLastTransactionTime = systemTime() - now;
1791 mDebugInTransaction = 0;
1792 invalidateHwcGeometry();
1793 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001794}
1795
Mathias Agopian87baae12012-07-31 12:38:26 -07001796void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001797{
Dan Stoza7dde5992015-05-22 09:51:44 -07001798 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001799 mCurrentState.traverseInZOrder([](Layer* layer) {
1800 layer->notifyAvailableFrames();
1801 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001803 /*
1804 * Traversal of the children
1805 * (perform the transaction for each of them if needed)
1806 */
1807
Mathias Agopian3559b072012-08-15 13:46:03 -07001808 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001809 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001811 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812
1813 const uint32_t flags = layer->doTransaction(0);
1814 if (flags & Layer::eVisibleRegion)
1815 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001816 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001817 }
1818
1819 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001820 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 */
1822
Mathias Agopiane57f2922012-08-09 16:29:12 -07001823 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001824 // here we take advantage of Vector's copy-on-write semantics to
1825 // improve performance by skipping the transaction entirely when
1826 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001827 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1828 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001829 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001830 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001831 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001832 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001833
1834 // find the displays that were removed
1835 // (ie: in drawing state but not in current state)
1836 // also handle displays that changed
1837 // (ie: displays that are in both lists)
1838 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001839 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1840 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001841 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001842 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001843 // Call makeCurrent() on the primary display so we can
1844 // be sure that nothing associated with this display
1845 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001846 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001847 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001848 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1849 if (hw != NULL)
1850 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001851 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001852 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001853 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001854 } else {
1855 ALOGW("trying to remove the main display");
1856 }
1857 } else {
1858 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001859 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001860 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001861 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1862 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001863 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001864 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001865 // recreating the DisplayDevice, so we just remove it
1866 // from the drawing state, so that it get re-added
1867 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001868 sp<DisplayDevice> hw(getDisplayDevice(display));
1869 if (hw != NULL)
1870 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001871 mDisplays.removeItem(display);
1872 mDrawingState.displays.removeItemsAt(i);
1873 dc--; i--;
1874 // at this point we must loop to the next item
1875 continue;
1876 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001877
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001878 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001879 if (disp != NULL) {
1880 if (state.layerStack != draw[i].layerStack) {
1881 disp->setLayerStack(state.layerStack);
1882 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001883 if ((state.orientation != draw[i].orientation)
1884 || (state.viewport != draw[i].viewport)
1885 || (state.frame != draw[i].frame))
1886 {
1887 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001888 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001889 }
Michael Lentine47e45402014-07-18 15:34:25 -07001890 if (state.width != draw[i].width || state.height != draw[i].height) {
1891 disp->setDisplaySize(state.width, state.height);
1892 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001893 }
1894 }
1895 }
1896
1897 // find displays that were added
1898 // (ie: in current state but not in drawing state)
1899 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001900 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001901 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001902
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001903 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001904 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001905 sp<IGraphicBufferProducer> bqProducer;
1906 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001907 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1908 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001909
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001911 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001912 // Virtual displays without a surface are dormant:
1913 // they have external state (layer stack, projection,
1914 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001915 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001916
Dan Stoza8cf150a2016-08-02 10:27:31 -07001917 if (mUseHwcVirtualDisplays) {
1918 int width = 0;
1919 int status = state.surface->query(
1920 NATIVE_WINDOW_WIDTH, &width);
1921 ALOGE_IF(status != NO_ERROR,
1922 "Unable to query width (%d)", status);
1923 int height = 0;
1924 status = state.surface->query(
1925 NATIVE_WINDOW_HEIGHT, &height);
1926 ALOGE_IF(status != NO_ERROR,
1927 "Unable to query height (%d)", status);
1928 int intFormat = 0;
1929 status = state.surface->query(
1930 NATIVE_WINDOW_FORMAT, &intFormat);
1931 ALOGE_IF(status != NO_ERROR,
1932 "Unable to query format (%d)", status);
1933 auto format = static_cast<android_pixel_format_t>(
1934 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001935
Dan Stoza8cf150a2016-08-02 10:27:31 -07001936 mHwc->allocateVirtualDisplay(width, height, &format,
1937 &hwcId);
1938 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939
Dan Stoza5cf424b2016-05-20 14:02:39 -07001940 // TODO: Plumb requested format back up to consumer
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 sp<VirtualDisplaySurface> vds =
1943 new VirtualDisplaySurface(*mHwc,
1944 hwcId, state.surface, bqProducer,
1945 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001946
1947 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001948 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001949 }
1950 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001951 ALOGE_IF(state.surface!=NULL,
1952 "adding a supported display, but rendering "
1953 "surface is provided (%p), ignoring it",
1954 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001955
1956 hwcId = state.type;
1957 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1958 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001959 }
1960
1961 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001962 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001963 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 state.type, hwcId, state.isSecure, display,
1965 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001966 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001967 hw->setLayerStack(state.layerStack);
1968 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001969 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001970 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001971 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001973 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001974 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001975 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001976 }
1977 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001978 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980
Mathias Agopian84300952012-11-21 16:02:13 -08001981 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1982 // The transform hint might have changed for some layers
1983 // (either because a display has changed, or because a layer
1984 // as changed).
1985 //
1986 // Walk through all the layers in currentLayers,
1987 // and update their transform hint.
1988 //
1989 // If a layer is visible only on a single display, then that
1990 // display is used to calculate the hint, otherwise we use the
1991 // default display.
1992 //
1993 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1994 // the hint is set before we acquire a buffer from the surface texture.
1995 //
1996 // NOTE: layer transactions have taken place already, so we use their
1997 // drawing state. However, SurfaceFlinger's own transaction has not
1998 // happened yet, so we must use the current state layer list
1999 // (soon to become the drawing state list).
2000 //
2001 sp<const DisplayDevice> disp;
2002 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002003 bool first = true;
2004 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002005 // NOTE: we rely on the fact that layers are sorted by
2006 // layerStack first (so we don't have to traverse the list
2007 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002008 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002009 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002010 currentlayerStack = layerStack;
2011 // figure out if this layerstack is mirrored
2012 // (more than one display) if so, pick the default display,
2013 // if not, pick the only display it's on.
2014 disp.clear();
2015 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2016 sp<const DisplayDevice> hw(mDisplays[dpy]);
2017 if (hw->getLayerStack() == currentlayerStack) {
2018 if (disp == NULL) {
2019 disp = hw;
2020 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002021 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002022 break;
2023 }
2024 }
2025 }
2026 }
Chet Haase91d25932013-04-11 15:24:55 -07002027 if (disp == NULL) {
2028 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2029 // redraw after transform hint changes. See bug 8508397.
2030
2031 // could be null when this layer is using a layerStack
2032 // that is not visible on any display. Also can occur at
2033 // screen off/on times.
2034 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002035 }
Chet Haase91d25932013-04-11 15:24:55 -07002036 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002037
2038 first = false;
2039 });
Mathias Agopian84300952012-11-21 16:02:13 -08002040 }
2041
2042
Mathias Agopian3559b072012-08-15 13:46:03 -07002043 /*
2044 * Perform our own transaction if needed
2045 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002046
2047 if (mLayersAdded) {
2048 mLayersAdded = false;
2049 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002050 mVisibleRegionsDirty = true;
2051 }
2052
2053 // some layers might have been removed, so
2054 // we need to update the regions they're exposing.
2055 if (mLayersRemoved) {
2056 mLayersRemoved = false;
2057 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002058 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002059 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002060 // this layer is not visible anymore
2061 // TODO: we could traverse the tree from front to back and
2062 // compute the actual visible region
2063 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002064 Region visibleReg;
2065 visibleReg.set(layer->computeScreenBounds());
2066 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002067 }
Robert Carr2047fae2016-11-28 14:09:09 -08002068 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069 }
2070
2071 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002072
2073 updateCursorAsync();
2074}
2075
2076void SurfaceFlinger::updateCursorAsync()
2077{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2079 auto& displayDevice = mDisplays[displayId];
2080 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002081 continue;
2082 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083
2084 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2085 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002086 }
2087 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002088}
2089
2090void SurfaceFlinger::commitTransaction()
2091{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002092 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002093 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002094 for (const auto& l : mLayersPendingRemoval) {
2095 recordBufferingStats(l->getName().string(),
2096 l->getOccupancyHistory(true));
2097 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 }
2099 mLayersPendingRemoval.clear();
2100 }
2101
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 // If this transaction is part of a window animation then the next frame
2103 // we composite should be considered an animation as well.
2104 mAnimCompositionPending = mAnimTransactionPending;
2105
Mathias Agopian4fec8732012-06-29 14:12:52 -07002106 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002107 mDrawingState.traverseInZOrder([](Layer* layer) {
2108 layer->commitChildList();
2109 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002110 mTransactionPending = false;
2111 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002112 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113}
2114
Robert Carr2047fae2016-11-28 14:09:09 -08002115void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117{
Mathias Agopian841cde52012-03-01 15:44:37 -08002118 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 Region aboveOpaqueLayers;
2122 Region aboveCoveredLayers;
2123 Region dirty;
2124
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126
Robert Carr2047fae2016-11-28 14:09:09 -08002127 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002129 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130
Jesse Hall01e29052013-02-19 16:13:35 -08002131 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002132 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002133 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002134
Mathias Agopianab028732010-03-16 16:41:46 -07002135 /*
2136 * opaqueRegion: area of a surface that is fully opaque.
2137 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002139
2140 /*
2141 * visibleRegion: area of a surface that is visible on screen
2142 * and not fully transparent. This is essentially the layer's
2143 * footprint minus the opaque regions above it.
2144 * Areas covered by a translucent surface are considered visible.
2145 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002147
2148 /*
2149 * coveredRegion: area of a surface that is covered by all
2150 * visible regions above it (which includes the translucent areas).
2151 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002153
Jesse Halla8026d22012-09-25 13:25:04 -07002154 /*
2155 * transparentRegion: area of a surface that is hinted to be completely
2156 * transparent. This is only used to tell when the layer has no visible
2157 * non-transparent regions and can be removed from the layer list. It
2158 * does not affect the visibleRegion of this layer or any layers
2159 * beneath it. The hint may not be correct if apps don't respect the
2160 * SurfaceView restrictions (which, sadly, some don't).
2161 */
2162 Region transparentRegion;
2163
Mathias Agopianab028732010-03-16 16:41:46 -07002164
2165 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002166 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002167 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002168 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002170 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002171 if (!visibleRegion.isEmpty()) {
2172 // Remove the transparent area from the visible region
2173 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002174 if (tr.preserveRects()) {
2175 // transform the transparent region
2176 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002177 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002178 // transformation too complex, can't do the
2179 // transparent region optimization.
2180 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002181 }
Mathias Agopianab028732010-03-16 16:41:46 -07002182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183
Mathias Agopianab028732010-03-16 16:41:46 -07002184 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002185 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002187 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2188 // the opaque region is the layer's footprint
2189 opaqueRegion = visibleRegion;
2190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191 }
2192 }
2193
Mathias Agopianab028732010-03-16 16:41:46 -07002194 // Clip the covered region to the visible region
2195 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2196
2197 // Update aboveCoveredLayers for next (lower) layer
2198 aboveCoveredLayers.orSelf(visibleRegion);
2199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 // subtract the opaque region covered by the layers above us
2201 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202
2203 // compute this layer's dirty region
2204 if (layer->contentDirty) {
2205 // we need to invalidate the whole region
2206 dirty = visibleRegion;
2207 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002208 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209 layer->contentDirty = false;
2210 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002211 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002212 * the exposed region consists of two components:
2213 * 1) what's VISIBLE now and was COVERED before
2214 * 2) what's EXPOSED now less what was EXPOSED before
2215 *
2216 * note that (1) is conservative, we start with the whole
2217 * visible region but only keep what used to be covered by
2218 * something -- which mean it may have been exposed.
2219 *
2220 * (2) handles areas that were not covered by anything but got
2221 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002222 */
Mathias Agopianab028732010-03-16 16:41:46 -07002223 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 const Region oldVisibleRegion = layer->visibleRegion;
2225 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002226 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2227 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 }
2229 dirty.subtractSelf(aboveOpaqueLayers);
2230
2231 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002232 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233
Mathias Agopianab028732010-03-16 16:41:46 -07002234 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002236
Jesse Halla8026d22012-09-25 13:25:04 -07002237 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 layer->setVisibleRegion(visibleRegion);
2239 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002240 layer->setVisibleNonTransparentRegion(
2241 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002242 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Mathias Agopian87baae12012-07-31 12:38:26 -07002244 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245}
2246
Mathias Agopian87baae12012-07-31 12:38:26 -07002247void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2248 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002249 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002250 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2251 if (hw->getLayerStack() == layerStack) {
2252 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002253 }
2254 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002255}
2256
Dan Stoza6b9454d2014-11-07 16:00:59 -08002257bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 ALOGV("handlePageFlip");
2260
Brian Andersond6927fb2016-07-23 23:37:30 -07002261 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262
Mathias Agopian4fec8732012-06-29 14:12:52 -07002263 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002264 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002265
2266 // Store the set of layers that need updates. This set must not change as
2267 // buffers are being latched, as this could result in a deadlock.
2268 // Example: Two producers share the same command stream and:
2269 // 1.) Layer 0 is latched
2270 // 2.) Layer 0 gets a new frame
2271 // 2.) Layer 1 gets a new frame
2272 // 3.) Layer 1 is latched.
2273 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2274 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002275 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002276 if (layer->hasQueuedFrame()) {
2277 frameQueued = true;
2278 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002279 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002280 } else {
2281 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002282 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002283 } else {
2284 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 }
Robert Carr2047fae2016-11-28 14:09:09 -08002286 });
2287
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002289 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002290 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002292 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002293
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002294 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002295
2296 // If we will need to wake up at some time in the future to deal with a
2297 // queued frame that shouldn't be displayed during this vsync period, wake
2298 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002299 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002300 signalLayerUpdate();
2301 }
2302
2303 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305}
2306
Mathias Agopianad456f92011-01-13 17:53:01 -08002307void SurfaceFlinger::invalidateHwcGeometry()
2308{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002310}
2311
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002312
Fabien Sanglard830b8472016-11-30 16:35:58 -08002313void SurfaceFlinger::doDisplayComposition(
2314 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002315 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316{
Dan Stoza71433162014-02-04 16:22:36 -08002317 // We only need to actually compose the display if:
2318 // 1) It is being handled by hardware composer, which may need this to
2319 // keep its virtual display state machine in sync, or
2320 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002321 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002322 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002323 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002324 return;
2325 }
2326
Dan Stoza9e56aa02015-11-02 13:00:03 -08002327 ALOGV("doDisplayComposition");
2328
Mathias Agopian87baae12012-07-31 12:38:26 -07002329 Region dirtyRegion(inDirtyRegion);
2330
Mathias Agopianb8a55602009-06-26 19:06:36 -07002331 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002332 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333
Fabien Sanglard830b8472016-11-30 16:35:58 -08002334 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002335 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002336 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2337 // takes a rectangle, we must make sure to update that whole
2338 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002339 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002340 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002341 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002342 // We need to redraw the rectangle that will be updated
2343 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002344 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002345 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002346 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002347 } else {
2348 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002349 dirtyRegion.set(displayDevice->bounds());
2350 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 }
2352 }
2353
Fabien Sanglard830b8472016-11-30 16:35:58 -08002354 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002356 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002357 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002358
2359 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002360 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361}
2362
Dan Stoza9e56aa02015-11-02 13:00:03 -08002363bool SurfaceFlinger::doComposeSurfaces(
2364 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002365{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002367
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002369
2370 mat4 oldColorMatrix;
2371 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2372 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2373 if (applyColorMatrix) {
2374 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2375 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2376 }
2377
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2379 if (hasClientComposition) {
2380 ALOGV("hasClientComposition");
2381
2382 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002383 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002384 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002385 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2386 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2387 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2388 }
2389 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002390 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002391
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002392 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2394 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002395 // when using overlays, we assume a fully transparent framebuffer
2396 // NOTE: we could reduce how much we need to clear, for instance
2397 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002398 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002399 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002400 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002401 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002402 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002403 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002404
2405 // we remove the scissor part
2406 // we're left with the letterbox region
2407 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002409
2410 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002412
2413 // but limit it to the dirty region
2414 region.andSelf(dirty);
2415
Mathias Agopianb9494d52012-04-18 02:28:45 -07002416 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002417 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002418 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002420 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002421 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002422
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002424 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002425 // scissor on the main display. It should never be needed
2426 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 const Rect& bounds(displayDevice->getBounds());
2428 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002429 if (scissor != bounds) {
2430 // scissor doesn't match the screen's dimensions, so we
2431 // need to clear everything outside of it and enable
2432 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002433
Mathias Agopianf45c5102012-10-24 16:29:17 -07002434 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002435 const uint32_t height = displayDevice->getHeight();
2436 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002437 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002438 }
2439 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002440 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002441
Mathias Agopian85d751c2012-08-29 16:59:24 -07002442 /*
2443 * and then, render the layers targeted at the framebuffer
2444 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002445
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 ALOGV("Rendering client layers");
2447 const Transform& displayTransform = displayDevice->getTransform();
2448 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002449 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 bool firstLayer = true;
2451 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2452 const Region clip(dirty.intersect(
2453 displayTransform.transform(layer->visibleRegion)));
2454 ALOGV("Layer: %s", layer->getName().string());
2455 ALOGV(" Composition type: %s",
2456 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002457 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 switch (layer->getCompositionType(hwcId)) {
2459 case HWC2::Composition::Cursor:
2460 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002461 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002463 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2465 layer->isOpaque(state) && (state.alpha == 1.0f)
2466 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002467 // never clear the very first layer since we're
2468 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002469 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002470 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002471 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002472 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 case HWC2::Composition::Client: {
2474 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002475 break;
2476 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002478 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002479 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 } else {
2481 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002482 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002484 }
2485 } else {
2486 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002488 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002490 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002492 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002493 }
2494 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002495
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002496 if (applyColorMatrix) {
2497 getRenderEngine().setupColorTransform(oldColorMatrix);
2498 }
2499
Mathias Agopianf45c5102012-10-24 16:29:17 -07002500 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002502 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503}
2504
Fabien Sanglard830b8472016-11-30 16:35:58 -08002505void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2506 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002507 RenderEngine& engine(getRenderEngine());
2508 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509}
2510
Dan Stoza7d89d062015-04-30 13:29:25 -07002511status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002512 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002513 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002514 const sp<Layer>& lbc,
2515 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002516{
Dan Stoza7d89d062015-04-30 13:29:25 -07002517 // add this layer to the current state list
2518 {
2519 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002520 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002521 return NO_MEMORY;
2522 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002523 if (parent == nullptr) {
2524 mCurrentState.layersSortedByZ.add(lbc);
2525 } else {
2526 parent->addChild(lbc);
2527 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002528 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 mLayersAdded = true;
2530 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002531 }
2532
Mathias Agopian96f08192010-06-02 23:28:45 -07002533 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002534 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002535
Dan Stoza7d89d062015-04-30 13:29:25 -07002536 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002537}
2538
Dan Stoza22851c32016-08-09 13:21:03 -07002539status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002541 sp<Layer> layer = weakLayer.promote();
2542 if (layer == nullptr) {
2543 // The layer has already been removed, carry on
2544 return NO_ERROR;
2545 }
2546
Robert Carr1f0a16a2016-10-24 16:27:39 -07002547 const auto& p = layer->getParent();
2548 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2549 mCurrentState.layersSortedByZ.remove(layer);
2550
2551 if (index < 0) {
2552 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2553 layer->getName().string(),
2554 (p != nullptr) ? p->getName().string() : "no-parent");
2555 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002556 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557
2558 mLayersPendingRemoval.add(layer);
2559 mLayersRemoved = true;
2560 mNumLayers--;
2561 setTransactionFlags(eTransactionNeeded);
2562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563}
2564
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002565uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002566 return android_atomic_release_load(&mTransactionFlags);
2567}
2568
Mathias Agopian3f844832013-08-07 21:24:32 -07002569uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2571}
2572
Mathias Agopian3f844832013-08-07 21:24:32 -07002573uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2575 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002576 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 }
2578 return old;
2579}
2580
Mathias Agopian8b33f032012-07-24 20:43:54 -07002581void SurfaceFlinger::setTransactionState(
2582 const Vector<ComposerState>& state,
2583 const Vector<DisplayState>& displays,
2584 uint32_t flags)
2585{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002586 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002587 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002588 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002589
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002590 if (flags & eAnimation) {
2591 // For window updates that are part of an animation we must wait for
2592 // previous animation "frames" to be handled.
2593 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002594 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002595 if (CC_UNLIKELY(err != NO_ERROR)) {
2596 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002597 // caller after a few seconds.
2598 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2599 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002600 mAnimTransactionPending = false;
2601 break;
2602 }
2603 }
2604 }
2605
Mathias Agopiane57f2922012-08-09 16:29:12 -07002606 size_t count = displays.size();
2607 for (size_t i=0 ; i<count ; i++) {
2608 const DisplayState& s(displays[i]);
2609 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002610 }
2611
Mathias Agopiane57f2922012-08-09 16:29:12 -07002612 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002613 for (size_t i=0 ; i<count ; i++) {
2614 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002615 // Here we need to check that the interface we're given is indeed
2616 // one of our own. A malicious client could give us a NULL
2617 // IInterface, or one of its own or even one of our own but a
2618 // different type. All these situations would cause us to crash.
2619 //
2620 // NOTE: it would be better to use RTTI as we could directly check
2621 // that we have a Client*. however, RTTI is disabled in Android.
2622 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002623 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002624 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002625 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002626 sp<Client> client( static_cast<Client *>(s.client.get()) );
2627 transactionFlags |= setClientStateLocked(client, s.state);
2628 }
2629 }
2630 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002631 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002632
Robert Carr2a7dbb42016-05-24 11:41:28 -07002633 // If a synchronous transaction is explicitly requested without any changes,
2634 // force a transaction anyway. This can be used as a flush mechanism for
2635 // previous async transactions.
2636 if (transactionFlags == 0 && (flags & eSynchronous)) {
2637 transactionFlags = eTransactionNeeded;
2638 }
2639
Mathias Agopian386aa982011-11-07 21:58:03 -08002640 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002641 if (mInterceptor.isEnabled()) {
2642 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2643 }
Irvel468051e2016-06-13 16:44:44 -07002644
Mathias Agopian386aa982011-11-07 21:58:03 -08002645 // this triggers the transaction
2646 setTransactionFlags(transactionFlags);
2647
2648 // if this is a synchronous transaction, wait for it to take effect
2649 // before returning.
2650 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002651 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002652 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002653 if (flags & eAnimation) {
2654 mAnimTransactionPending = true;
2655 }
2656 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002657 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2658 if (CC_UNLIKELY(err != NO_ERROR)) {
2659 // just in case something goes wrong in SF, return to the
2660 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002661 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2662 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002663 break;
2664 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667}
2668
Mathias Agopiane57f2922012-08-09 16:29:12 -07002669uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2670{
Jesse Hall9a143922012-10-04 16:29:19 -07002671 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2672 if (dpyIdx < 0)
2673 return 0;
2674
Mathias Agopiane57f2922012-08-09 16:29:12 -07002675 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002676 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002677 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002678 const uint32_t what = s.what;
2679 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002680 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681 disp.surface = s.surface;
2682 flags |= eDisplayTransactionNeeded;
2683 }
2684 }
2685 if (what & DisplayState::eLayerStackChanged) {
2686 if (disp.layerStack != s.layerStack) {
2687 disp.layerStack = s.layerStack;
2688 flags |= eDisplayTransactionNeeded;
2689 }
2690 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002691 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002692 if (disp.orientation != s.orientation) {
2693 disp.orientation = s.orientation;
2694 flags |= eDisplayTransactionNeeded;
2695 }
2696 if (disp.frame != s.frame) {
2697 disp.frame = s.frame;
2698 flags |= eDisplayTransactionNeeded;
2699 }
2700 if (disp.viewport != s.viewport) {
2701 disp.viewport = s.viewport;
2702 flags |= eDisplayTransactionNeeded;
2703 }
2704 }
Michael Lentine47e45402014-07-18 15:34:25 -07002705 if (what & DisplayState::eDisplaySizeChanged) {
2706 if (disp.width != s.width) {
2707 disp.width = s.width;
2708 flags |= eDisplayTransactionNeeded;
2709 }
2710 if (disp.height != s.height) {
2711 disp.height = s.height;
2712 flags |= eDisplayTransactionNeeded;
2713 }
2714 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 }
2716 return flags;
2717}
2718
2719uint32_t SurfaceFlinger::setClientStateLocked(
2720 const sp<Client>& client,
2721 const layer_state_t& s)
2722{
2723 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002724 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002725 if (layer != 0) {
2726 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002727 bool geometryAppliesWithResize =
2728 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002730 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002732 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002733 }
2734 if (what & layer_state_t::eLayerChanged) {
2735 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 const auto& p = layer->getParent();
2737 if (p == nullptr) {
2738 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2739 if (layer->setLayer(s.z) && idx >= 0) {
2740 mCurrentState.layersSortedByZ.removeAt(idx);
2741 mCurrentState.layersSortedByZ.add(layer);
2742 // we need traversal (state changed)
2743 // AND transaction (list changed)
2744 flags |= eTransactionNeeded|eTraversalNeeded;
2745 }
2746 } else {
2747 if (p->setChildLayer(layer, s.z)) {
2748 flags |= eTransactionNeeded|eTraversalNeeded;
2749 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002750 }
2751 }
2752 if (what & layer_state_t::eSizeChanged) {
2753 if (layer->setSize(s.w, s.h)) {
2754 flags |= eTraversalNeeded;
2755 }
2756 }
2757 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759 flags |= eTraversalNeeded;
2760 }
2761 if (what & layer_state_t::eMatrixChanged) {
2762 if (layer->setMatrix(s.matrix))
2763 flags |= eTraversalNeeded;
2764 }
2765 if (what & layer_state_t::eTransparentRegionChanged) {
2766 if (layer->setTransparentRegionHint(s.transparentRegion))
2767 flags |= eTraversalNeeded;
2768 }
Dan Stoza23116082015-06-18 14:58:39 -07002769 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002770 if (layer->setFlags(s.flags, s.mask))
2771 flags |= eTraversalNeeded;
2772 }
2773 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002774 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 flags |= eTraversalNeeded;
2776 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002777 if (what & layer_state_t::eFinalCropChanged) {
2778 if (layer->setFinalCrop(s.finalCrop))
2779 flags |= eTraversalNeeded;
2780 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002781 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002782 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 // We only allow setting layer stacks for top level layers,
2784 // everything else inherits layer stack from its parent.
2785 if (layer->hasParent()) {
2786 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2787 layer->getName().string());
2788 } else if (idx < 0) {
2789 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2790 "that also does not appear in the top level layer list. Something"
2791 " has gone wrong.", layer->getName().string());
2792 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793 mCurrentState.layersSortedByZ.removeAt(idx);
2794 mCurrentState.layersSortedByZ.add(layer);
2795 // we need traversal (state changed)
2796 // AND transaction (list changed)
2797 flags |= eTransactionNeeded|eTraversalNeeded;
2798 }
2799 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002800 if (what & layer_state_t::eDeferTransaction) {
2801 layer->deferTransactionUntil(s.handle, s.frameNumber);
2802 // We don't trigger a traversal here because if no other state is
2803 // changed, we don't want this to cause any more work
2804 }
Robert Carr1db73f62016-12-21 12:58:51 -08002805 if (what & layer_state_t::eReparentChildren) {
2806 if (layer->reparentChildren(s.reparentHandle)) {
2807 flags |= eTransactionNeeded|eTraversalNeeded;
2808 }
2809 }
Robert Carrc3574f72016-03-24 12:19:32 -07002810 if (what & layer_state_t::eOverrideScalingModeChanged) {
2811 layer->setOverrideScalingMode(s.overrideScalingMode);
2812 // We don't trigger a traversal here because if no other state is
2813 // changed, we don't want this to cause any more work
2814 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002815 }
2816 return flags;
2817}
2818
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002819status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002820 const String8& name,
2821 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002822 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002823 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2824 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002826 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002827 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002828 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002829 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002830 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002831
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002832 status_t result = NO_ERROR;
2833
2834 sp<Layer> layer;
2835
Mathias Agopian3165cc22012-08-08 19:42:09 -07002836 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2837 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002838 result = createNormalLayer(client,
2839 name, w, h, flags, format,
2840 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002842 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002843 result = createDimLayer(client,
2844 name, w, h, flags,
2845 handle, gbp, &layer);
2846 break;
2847 default:
2848 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 break;
2850 }
2851
Dan Stoza7d89d062015-04-30 13:29:25 -07002852 if (result != NO_ERROR) {
2853 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002855
Albert Chaulk479c60c2017-01-27 14:21:34 -05002856 layer->setInfo(windowType, ownerUid);
2857
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002859 if (result != NO_ERROR) {
2860 return result;
2861 }
Irvelffc9efc2016-07-27 15:16:37 -07002862 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002863
2864 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002865 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866}
2867
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002868status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2869 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2870 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871{
2872 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002873 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 case PIXEL_FORMAT_TRANSPARENT:
2875 case PIXEL_FORMAT_TRANSLUCENT:
2876 format = PIXEL_FORMAT_RGBA_8888;
2877 break;
2878 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002879 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 break;
2881 }
2882
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002883 *outLayer = new Layer(this, client, name, w, h, flags);
2884 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2885 if (err == NO_ERROR) {
2886 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002887 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002889
2890 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2891 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002894status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2895 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2896 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002898 *outLayer = new LayerDim(this, client, name, w, h, flags);
2899 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002900 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002901 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002902}
2903
Mathias Agopianac9fa422013-02-11 16:40:36 -08002904status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905{
Mathias Agopian67106042013-03-14 19:18:13 -07002906 // called by the window manager when it wants to remove a Layer
2907 status_t err = NO_ERROR;
2908 sp<Layer> l(client->getLayerUser(handle));
2909 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002910 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002911 err = removeLayer(l);
2912 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2913 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002914 }
2915 return err;
2916}
2917
Mathias Agopian13127d82013-03-05 17:47:11 -08002918status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002919{
Mathias Agopian67106042013-03-14 19:18:13 -07002920 // called by ~LayerCleaner() when all references to the IBinder (handle)
2921 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002922 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923}
2924
Mathias Agopianb60314a2012-04-10 22:09:54 -07002925// ---------------------------------------------------------------------------
2926
Andy McFadden13a082e2012-08-24 10:16:42 -07002927void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002928 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002929 Vector<ComposerState> state;
2930 Vector<DisplayState> displays;
2931 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002932 d.what = DisplayState::eDisplayProjectionChanged |
2933 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002934 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002935 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002936 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002937 d.frame.makeInvalid();
2938 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002939 d.width = 0;
2940 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002941 displays.add(d);
2942 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002943 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2946 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002947 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002948
2949 {
2950 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2951 mCompositorTiming.interval = period;
2952 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002953}
2954
2955void SurfaceFlinger::initializeDisplays() {
2956 class MessageScreenInitialized : public MessageBase {
2957 SurfaceFlinger* flinger;
2958 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002959 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002960 virtual bool handler() {
2961 flinger->onInitializeDisplays();
2962 return true;
2963 }
2964 };
2965 sp<MessageBase> msg = new MessageScreenInitialized(this);
2966 postMessageAsync(msg); // we may be called from main thread, use async message
2967}
2968
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002969void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2970 int mode) {
2971 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2972 this);
2973 int32_t type = hw->getDisplayType();
2974 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002975
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002976 if (mode == currentMode) {
2977 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002978 return;
2979 }
2980
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002981 hw->setPowerMode(mode);
2982 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2983 ALOGW("Trying to set power mode for virtual display");
2984 return;
2985 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002986
Irvelffc9efc2016-07-27 15:16:37 -07002987 if (mInterceptor.isEnabled()) {
2988 Mutex::Autolock _l(mStateLock);
2989 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2990 if (idx < 0) {
2991 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2992 return;
2993 }
2994 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2995 }
2996
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002997 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002998 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002999 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003000 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3001 // FIXME: eventthread only knows about the main display right now
3002 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003003 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003004 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003006 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003007 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003008 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003009
3010 struct sched_param param = {0};
3011 param.sched_priority = 1;
3012 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3013 ALOGW("Couldn't set SCHED_FIFO on display on");
3014 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003016 // Turn off the display
3017 struct sched_param param = {0};
3018 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3019 ALOGW("Couldn't set SCHED_OTHER on display off");
3020 }
3021
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003022 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003023 disableHardwareVsync(true); // also cancels any in-progress resync
3024
Mathias Agopiancde87a32012-09-13 14:09:01 -07003025 // FIXME: eventthread only knows about the main display right now
3026 mEventThread->onScreenReleased();
3027 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003028
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 getHwComposer().setPowerMode(type, mode);
3030 mVisibleRegionsDirty = true;
3031 // from this point on, SF will stop drawing on this display
3032 } else {
3033 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003034 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003035}
3036
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003037void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3038 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003039 SurfaceFlinger& mFlinger;
3040 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003041 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003042 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003043 MessageSetPowerMode(SurfaceFlinger& flinger,
3044 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3045 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003046 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003047 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003048 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003049 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003050 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003051 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003052 ALOGW("Attempt to set power mode = %d for virtual display",
3053 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003054 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003055 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003056 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003057 return true;
3058 }
3059 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003060 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003061 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003062}
3063
3064// ---------------------------------------------------------------------------
3065
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3067{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003069
Mathias Agopianbd115332013-04-18 16:41:04 -07003070 IPCThreadState* ipc = IPCThreadState::self();
3071 const int pid = ipc->getCallingPid();
3072 const int uid = ipc->getCallingUid();
3073 if ((uid != AID_SHELL) &&
3074 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003075 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003076 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003078 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003079 // (this would indicate SF is stuck, but we want to be able to
3080 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003081 status_t err = mStateLock.timedLock(s2ns(1));
3082 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003083 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003084 result.appendFormat(
3085 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3086 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003087 }
3088
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003089 bool dumpAll = true;
3090 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003091 size_t numArgs = args.size();
3092 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003093 if ((index < numArgs) &&
3094 (args[index] == String16("--list"))) {
3095 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003096 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003097 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003098 }
3099
3100 if ((index < numArgs) &&
3101 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003102 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003104 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003105 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003106
3107 if ((index < numArgs) &&
3108 (args[index] == String16("--latency-clear"))) {
3109 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003110 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003111 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003112 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003113
3114 if ((index < numArgs) &&
3115 (args[index] == String16("--dispsync"))) {
3116 index++;
3117 mPrimaryDispSync.dump(result);
3118 dumpAll = false;
3119 }
Dan Stozab90cf072015-03-05 11:05:59 -08003120
3121 if ((index < numArgs) &&
3122 (args[index] == String16("--static-screen"))) {
3123 index++;
3124 dumpStaticScreenStats(result);
3125 dumpAll = false;
3126 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003127
3128 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003129 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003130 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003131 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003132 dumpAll = false;
3133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003135
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003136 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003137 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003138 }
3139
Mathias Agopian9795c422009-08-26 16:36:26 -07003140 if (locked) {
3141 mStateLock.unlock();
3142 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 }
3144 write(fd, result.string(), result.size());
3145 return NO_ERROR;
3146}
3147
Dan Stozac7014012014-02-14 15:03:43 -08003148void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3149 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003150{
Robert Carr2047fae2016-11-28 14:09:09 -08003151 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003152 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003153 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003154}
3155
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003156void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003157 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003158{
3159 String8 name;
3160 if (index < args.size()) {
3161 name = String8(args[index]);
3162 index++;
3163 }
3164
Dan Stoza9e56aa02015-11-02 13:00:03 -08003165 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3166 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003167 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003168
3169 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003170 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003171 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003172 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003173 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003174 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003175 }
Robert Carr2047fae2016-11-28 14:09:09 -08003176 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003177 }
3178}
3179
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003180void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003181 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003182{
3183 String8 name;
3184 if (index < args.size()) {
3185 name = String8(args[index]);
3186 index++;
3187 }
3188
Robert Carr2047fae2016-11-28 14:09:09 -08003189 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003190 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003191 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003192 }
Robert Carr2047fae2016-11-28 14:09:09 -08003193 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003194
Svetoslavd85084b2014-03-20 10:28:31 -07003195 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003196}
3197
Jamie Gennis6547ff42013-07-16 20:12:42 -07003198// This should only be called from the main thread. Otherwise it would need
3199// the lock and should use mCurrentState rather than mDrawingState.
3200void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003202 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003203 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003204
3205 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3206}
3207
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003208void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003209{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003210 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003211#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003212 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003213#endif
3214#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003215 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003216#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003217 if (isLayerTripleBufferingDisabled())
3218 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003219 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003220}
3221
Dan Stozab90cf072015-03-05 11:05:59 -08003222void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3223{
3224 result.appendFormat("Static screen stats:\n");
3225 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3226 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3227 float percent = 100.0f *
3228 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3229 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3230 b + 1, bucketTimeSec, percent);
3231 }
3232 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3233 float percent = 100.0f *
3234 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3235 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3236 NUM_BUCKETS - 1, bucketTimeSec, percent);
3237}
3238
Dan Stozae77c7662016-05-13 11:37:28 -07003239void SurfaceFlinger::recordBufferingStats(const char* layerName,
3240 std::vector<OccupancyTracker::Segment>&& history) {
3241 Mutex::Autolock lock(mBufferingStatsMutex);
3242 auto& stats = mBufferingStats[layerName];
3243 for (const auto& segment : history) {
3244 if (!segment.usedThirdBuffer) {
3245 stats.twoBufferTime += segment.totalTime;
3246 }
3247 if (segment.occupancyAverage < 1.0f) {
3248 stats.doubleBufferedTime += segment.totalTime;
3249 } else if (segment.occupancyAverage < 2.0f) {
3250 stats.tripleBufferedTime += segment.totalTime;
3251 }
3252 ++stats.numSegments;
3253 stats.totalTime += segment.totalTime;
3254 }
3255}
3256
Brian Andersond6927fb2016-07-23 23:37:30 -07003257void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3258 result.appendFormat("Layer frame timestamps:\n");
3259
3260 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3261 const size_t count = currentLayers.size();
3262 for (size_t i=0 ; i<count ; i++) {
3263 currentLayers[i]->dumpFrameEvents(result);
3264 }
3265}
3266
Dan Stozae77c7662016-05-13 11:37:28 -07003267void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3268 result.append("Buffering stats:\n");
3269 result.append(" [Layer name] <Active time> <Two buffer> "
3270 "<Double buffered> <Triple buffered>\n");
3271 Mutex::Autolock lock(mBufferingStatsMutex);
3272 typedef std::tuple<std::string, float, float, float> BufferTuple;
3273 std::map<float, BufferTuple, std::greater<float>> sorted;
3274 for (const auto& statsPair : mBufferingStats) {
3275 const char* name = statsPair.first.c_str();
3276 const BufferingStats& stats = statsPair.second;
3277 if (stats.numSegments == 0) {
3278 continue;
3279 }
3280 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3281 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3282 stats.totalTime;
3283 float doubleBufferRatio = static_cast<float>(
3284 stats.doubleBufferedTime) / stats.totalTime;
3285 float tripleBufferRatio = static_cast<float>(
3286 stats.tripleBufferedTime) / stats.totalTime;
3287 sorted.insert({activeTime, {name, twoBufferRatio,
3288 doubleBufferRatio, tripleBufferRatio}});
3289 }
3290 for (const auto& sortedPair : sorted) {
3291 float activeTime = sortedPair.first;
3292 const BufferTuple& values = sortedPair.second;
3293 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3294 std::get<0>(values).c_str(), activeTime,
3295 std::get<1>(values), std::get<2>(values),
3296 std::get<3>(values));
3297 }
3298 result.append("\n");
3299}
3300
3301
Mathias Agopian74d211a2013-04-22 16:55:35 +02003302void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3303 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003304{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003305 bool colorize = false;
3306 if (index < args.size()
3307 && (args[index] == String16("--color"))) {
3308 colorize = true;
3309 index++;
3310 }
3311
3312 Colorizer colorizer(colorize);
3313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314 // figure out if we're stuck somewhere
3315 const nsecs_t now = systemTime();
3316 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3317 const nsecs_t inTransaction(mDebugInTransaction);
3318 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3319 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3320
3321 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003322 * Dump library configuration.
3323 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003324
3325 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003326 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003327 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003328 appendSfConfigString(result);
3329 appendUiConfigString(result);
3330 appendGuiConfigString(result);
3331 result.append("\n");
3332
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003333 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003334 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003335 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003336 result.append(SyncFeatures::getInstance().toString());
3337 result.append("\n");
3338
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3340
Andy McFadden41d67d72014-04-25 16:58:34 -07003341 colorizer.bold(result);
3342 result.append("DispSync configuration: ");
3343 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003344 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3345 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3347 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003348 result.append("\n");
3349
Dan Stozab90cf072015-03-05 11:05:59 -08003350 // Dump static screen stats
3351 result.append("\n");
3352 dumpStaticScreenStats(result);
3353 result.append("\n");
3354
Dan Stozae77c7662016-05-13 11:37:28 -07003355 dumpBufferingStats(result);
3356
Andy McFadden4803b742012-09-24 19:07:20 -07003357 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003358 * Dump the visible layer list
3359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003360 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003362 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003363 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003364 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003365 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003366
3367 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003368 * Dump Display state
3369 */
3370
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003371 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003372 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003373 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003374 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3375 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003376 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003377 }
3378
3379 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003380 * Dump SurfaceFlinger global state
3381 */
3382
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003383 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003385 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003386
Mathias Agopian888c8222012-08-04 21:10:38 -07003387 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003388 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003389
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003390 colorizer.bold(result);
3391 result.appendFormat("EGL implementation : %s\n",
3392 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3393 colorizer.reset(result);
3394 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003395 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003396
Mathias Agopian875d8e12013-06-07 15:35:48 -07003397 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003398
Mathias Agopian42977342012-08-05 00:40:46 -07003399 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3401 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003402 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003403 " last eglSwapBuffers() time: %f us\n"
3404 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003405 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003406 " refresh-rate : %f fps\n"
3407 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003408 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003409 " gpu_to_cpu_unsupported : %d\n"
3410 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411 mLastSwapBufferTime/1000.0,
3412 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003413 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 1e9 / activeConfig->getVsyncPeriod(),
3415 activeConfig->getDpiX(),
3416 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003417 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003420 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421
Mathias Agopian74d211a2013-04-22 16:55:35 +02003422 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003423 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424
3425 /*
3426 * VSYNC state
3427 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003428 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003429 result.append("\n");
3430
3431 /*
3432 * HWC layer minidump
3433 */
3434 for (size_t d = 0; d < mDisplays.size(); d++) {
3435 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3436 int32_t hwcId = displayDevice->getHwcDisplayId();
3437 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3438 continue;
3439 }
3440
3441 result.appendFormat("Display %d HWC layers:\n", hwcId);
3442 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003444 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003445 });
Dan Stozae22aec72016-08-01 13:20:59 -07003446 result.append("\n");
3447 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003448
3449 /*
3450 * Dump HWComposer state
3451 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003452 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003454 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003455 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003456 result.appendFormat(" h/w composer %s\n",
3457 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003458 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459
3460 /*
3461 * Dump gralloc state
3462 */
3463 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3464 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465}
3466
Mathias Agopian13127d82013-03-05 17:47:11 -08003467const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003468SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003469 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003470 wp<IBinder> dpy;
3471 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3472 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3473 dpy = mDisplays.keyAt(i);
3474 break;
3475 }
3476 }
3477 if (dpy == NULL) {
3478 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3479 // Just use the primary display so we have something to return
3480 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3481 }
3482 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003483}
3484
Keun young Park63f165f2012-08-31 10:53:36 -07003485bool SurfaceFlinger::startDdmConnection()
3486{
3487 void* libddmconnection_dso =
3488 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3489 if (!libddmconnection_dso) {
3490 return false;
3491 }
3492 void (*DdmConnection_start)(const char* name);
3493 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003494 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003495 if (!DdmConnection_start) {
3496 dlclose(libddmconnection_dso);
3497 return false;
3498 }
3499 (*DdmConnection_start)(getServiceName());
3500 return true;
3501}
3502
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003503status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 switch (code) {
3505 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003506 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003508 case CLEAR_ANIMATION_FRAME_STATS:
3509 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003511 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 {
3513 // codes that require permission check
3514 IPCThreadState* ipc = IPCThreadState::self();
3515 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003516 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003517 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003518 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003519 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003520 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003522 break;
3523 }
Robert Carr1db73f62016-12-21 12:58:51 -08003524 /*
3525 * Calling setTransactionState is safe, because you need to have been
3526 * granted a reference to Client* and Handle* to do anything with it.
3527 *
3528 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3529 */
3530 case SET_TRANSACTION_STATE:
3531 case CREATE_SCOPED_CONNECTION:
3532 {
3533 return OK;
3534 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003535 case CAPTURE_SCREEN:
3536 {
3537 // codes that require permission check
3538 IPCThreadState* ipc = IPCThreadState::self();
3539 const int pid = ipc->getCallingPid();
3540 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003541 if ((uid != AID_GRAPHICS) &&
3542 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003543 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003544 return PERMISSION_DENIED;
3545 }
3546 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547 }
3548 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003549 return OK;
3550}
3551
3552status_t SurfaceFlinger::onTransact(
3553 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3554{
3555 status_t credentialCheck = CheckTransactCodeCredentials(code);
3556 if (credentialCheck != OK) {
3557 return credentialCheck;
3558 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3561 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003562 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003563 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003564 IPCThreadState* ipc = IPCThreadState::self();
3565 const int pid = ipc->getCallingPid();
3566 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003567 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003568 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003569 return PERMISSION_DENIED;
3570 }
3571 int n;
3572 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003573 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003574 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575 return NO_ERROR;
3576 case 1002: // SHOW_UPDATES
3577 n = data.readInt32();
3578 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003579 invalidateHwcGeometry();
3580 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003583 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003584 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003586 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003587 setTransactionFlags(
3588 eTransactionNeeded|
3589 eDisplayTransactionNeeded|
3590 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003591 return NO_ERROR;
3592 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003593 case 1006:{ // send empty update
3594 signalRefresh();
3595 return NO_ERROR;
3596 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003597 case 1008: // toggle use of hw composer
3598 n = data.readInt32();
3599 mDebugDisableHWC = n ? 1 : 0;
3600 invalidateHwcGeometry();
3601 repaintEverything();
3602 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003603 case 1009: // toggle use of transform hint
3604 n = data.readInt32();
3605 mDebugDisableTransformHint = n ? 1 : 0;
3606 invalidateHwcGeometry();
3607 repaintEverything();
3608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003610 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611 reply->writeInt32(0);
3612 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003613 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003614 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 return NO_ERROR;
3616 case 1013: {
3617 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003618 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3619 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003620 return NO_ERROR;
3621 }
3622 case 1014: {
3623 // daltonize
3624 n = data.readInt32();
3625 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003626 case 1:
3627 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3628 break;
3629 case 2:
3630 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3631 break;
3632 case 3:
3633 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3634 break;
3635 default:
3636 mDaltonizer.setType(ColorBlindnessType::None);
3637 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003638 }
3639 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003640 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003641 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003642 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003643 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003644 invalidateHwcGeometry();
3645 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003646 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003648 case 1015: {
3649 // apply a color matrix
3650 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003651 if (n) {
3652 // color matrix is sent as mat3 matrix followed by vec3
3653 // offset, then packed into a mat4 where the last row is
3654 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003655 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003656 for (size_t j = 0; j < 4; j++) {
3657 mColorMatrix[i][j] = data.readFloat();
3658 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003659 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003660 } else {
3661 mColorMatrix = mat4();
3662 }
3663 invalidateHwcGeometry();
3664 repaintEverything();
3665 return NO_ERROR;
3666 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003667 // This is an experimental interface
3668 // Needs to be shifted to proper binder interface when we productize
3669 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003670 n = data.readInt32();
3671 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003672 return NO_ERROR;
3673 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003674 case 1017: {
3675 n = data.readInt32();
3676 mForceFullDamage = static_cast<bool>(n);
3677 return NO_ERROR;
3678 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003679 case 1018: { // Modify Choreographer's phase offset
3680 n = data.readInt32();
3681 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3682 return NO_ERROR;
3683 }
3684 case 1019: { // Modify SurfaceFlinger's phase offset
3685 n = data.readInt32();
3686 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3687 return NO_ERROR;
3688 }
Irvel468051e2016-06-13 16:44:44 -07003689 case 1020: { // Layer updates interceptor
3690 n = data.readInt32();
3691 if (n) {
3692 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003693 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003694 }
3695 else{
3696 ALOGV("Interceptor disabled");
3697 mInterceptor.disable();
3698 }
3699 return NO_ERROR;
3700 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003701 case 1021: { // Disable HWC virtual displays
3702 n = data.readInt32();
3703 mUseHwcVirtualDisplays = !n;
3704 return NO_ERROR;
3705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 }
3707 }
3708 return err;
3709}
3710
Mathias Agopian53331da2011-08-22 21:44:41 -07003711void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003712 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003713 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003714}
3715
Mathias Agopian59119e62010-10-11 12:37:43 -07003716// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003717// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003718// ---------------------------------------------------------------------------
3719
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003720/* The code below is here to handle b/8734824
3721 *
3722 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003723 * from the surfaceflinger thread to the calling binder thread, where they
3724 * are executed. This allows the calling thread in the calling process to be
3725 * reused and not depend on having "enough" binder threads to handle the
3726 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003727 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003728class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003729 /* Parts of GraphicProducerWrapper are run on two different threads,
3730 * communicating by sending messages via Looper but also by shared member
3731 * data. Coherence maintenance is subtle and in places implicit (ugh).
3732 *
3733 * Don't rely on Looper's sendMessage/handleMessage providing
3734 * release/acquire semantics for any data not actually in the Message.
3735 * Data going from surfaceflinger to binder threads needs to be
3736 * synchronized explicitly.
3737 *
3738 * Barrier open/wait do provide release/acquire semantics. This provides
3739 * implicit synchronization for data coming back from binder to
3740 * surfaceflinger threads.
3741 */
3742
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003743 sp<IGraphicBufferProducer> impl;
3744 sp<Looper> looper;
3745 status_t result;
3746 bool exitPending;
3747 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003748 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003749 uint32_t code;
3750 Parcel const* data;
3751 Parcel* reply;
3752
3753 enum {
3754 MSG_API_CALL,
3755 MSG_EXIT
3756 };
3757
3758 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003759 * Called on surfaceflinger thread. This is called by our "fake"
3760 * BpGraphicBufferProducer. We package the data and reply Parcel and
3761 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003762 */
3763 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003764 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003765 this->code = code;
3766 this->data = &data;
3767 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003768 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003769 // if we've exited, we run the message synchronously right here.
3770 // note (JH): as far as I can tell from looking at the code, this
3771 // never actually happens. if it does, i'm not sure if it happens
3772 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003773 handleMessage(Message(MSG_API_CALL));
3774 } else {
3775 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003776 // Prevent stores to this->{code, data, reply} from being
3777 // reordered later than the construction of Message.
3778 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003779 looper->sendMessage(this, Message(MSG_API_CALL));
3780 barrier.wait();
3781 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003782 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003783 }
3784
3785 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003786 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003787 * call the real BpGraphicBufferProducer.
3788 */
3789 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003790 int what = message.what;
3791 // Prevent reads below from happening before the read from Message
3792 atomic_thread_fence(memory_order_acquire);
3793 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003794 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003795 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003796 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 exitRequested = true;
3798 }
3799 }
3800
3801public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003802 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003803 : impl(impl),
3804 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003805 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003806 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003807 exitRequested(false),
3808 code(0),
3809 data(NULL),
3810 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003811 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003812
Jesse Hallb154c422014-07-13 12:47:02 -07003813 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003814 status_t waitForResponse() {
3815 do {
3816 looper->pollOnce(-1);
3817 } while (!exitRequested);
3818 return result;
3819 }
3820
Jesse Hallb154c422014-07-13 12:47:02 -07003821 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003822 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003823 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003824 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003825 // Ensure this->result is visible to the binder thread before it
3826 // handles the message.
3827 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003828 looper->sendMessage(this, Message(MSG_EXIT));
3829 }
3830};
3831
3832
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003833status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3834 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003835 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003836 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003837 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003838
3839 if (CC_UNLIKELY(display == 0))
3840 return BAD_VALUE;
3841
3842 if (CC_UNLIKELY(producer == 0))
3843 return BAD_VALUE;
3844
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003845 // if we have secure windows on this display, never allow the screen capture
3846 // unless the producer interface is local (i.e.: we can take a screenshot for
3847 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003848 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003849
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003850 // Convert to surfaceflinger's internal rotation type.
3851 Transform::orientation_flags rotationFlags;
3852 switch (rotation) {
3853 case ISurfaceComposer::eRotateNone:
3854 rotationFlags = Transform::ROT_0;
3855 break;
3856 case ISurfaceComposer::eRotate90:
3857 rotationFlags = Transform::ROT_90;
3858 break;
3859 case ISurfaceComposer::eRotate180:
3860 rotationFlags = Transform::ROT_180;
3861 break;
3862 case ISurfaceComposer::eRotate270:
3863 rotationFlags = Transform::ROT_270;
3864 break;
3865 default:
3866 rotationFlags = Transform::ROT_0;
3867 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3868 break;
3869 }
3870
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871 class MessageCaptureScreen : public MessageBase {
3872 SurfaceFlinger* flinger;
3873 sp<IBinder> display;
3874 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003875 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003876 uint32_t reqWidth, reqHeight;
3877 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003878 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003879 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003880 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003881 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003882 public:
3883 MessageCaptureScreen(SurfaceFlinger* flinger,
3884 const sp<IBinder>& display,
3885 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003886 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003887 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003888 bool useIdentityTransform,
3889 Transform::orientation_flags rotation,
3890 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003891 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003892 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003893 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003894 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003895 rotation(rotation), result(PERMISSION_DENIED),
3896 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003897 {
3898 }
3899 status_t getResult() const {
3900 return result;
3901 }
3902 virtual bool handler() {
3903 Mutex::Autolock _l(flinger->mStateLock);
3904 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003905 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003906 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003907 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003908 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003909 return true;
3910 }
3911 };
3912
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003913 // this creates a "fake" BBinder which will serve as a "fake" remote
3914 // binder to receive the marshaled calls and forward them to the
3915 // real remote (a BpGraphicBufferProducer)
3916 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3917
3918 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3919 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003920 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003921 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003922 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003923 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003924
3925 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003926 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928 }
3929 return res;
3930}
3931
Mathias Agopian180f10d2013-04-10 22:55:41 -07003932
3933void SurfaceFlinger::renderScreenImplLocked(
3934 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003935 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003936 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003937 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003938{
3939 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003940 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003941
3942 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003943 const int32_t hw_w = hw->getWidth();
3944 const int32_t hw_h = hw->getHeight();
3945 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003946 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003947
Dan Stozac1879002014-05-22 15:59:05 -07003948 // if a default or invalid sourceCrop is passed in, set reasonable values
3949 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3950 !sourceCrop.isValid()) {
3951 sourceCrop.setLeftTop(Point(0, 0));
3952 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3953 }
3954
3955 // ensure that sourceCrop is inside screen
3956 if (sourceCrop.left < 0) {
3957 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3958 }
Dan Stozabe31f442014-06-11 11:20:54 -07003959 if (sourceCrop.right > hw_w) {
3960 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003961 }
3962 if (sourceCrop.top < 0) {
3963 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3964 }
Dan Stozabe31f442014-06-11 11:20:54 -07003965 if (sourceCrop.bottom > hw_h) {
3966 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003967 }
3968
Mathias Agopian180f10d2013-04-10 22:55:41 -07003969 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003970 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003971
3972 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003973 engine.setViewportAndProjection(
3974 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003975 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003976
3977 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003978 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979
Robert Carr1f0a16a2016-10-24 16:27:39 -07003980 // We loop through the first level of layers without traversing,
3981 // as we need to interpret min/max layer Z in the top level Z space.
3982 for (const auto& layer : mDrawingState.layersSortedByZ) {
3983 if (layer->getLayerStack() != hw->getLayerStack()) {
3984 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003985 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003986 const Layer::State& state(layer->getDrawingState());
3987 if (state.z < minLayerZ || state.z > maxLayerZ) {
3988 continue;
3989 }
3990 layer->traverseInZOrder([&](Layer* layer) {
3991 if (!layer->isVisible()) {
3992 return;
3993 }
3994 if (filtering) layer->setFiltering(true);
3995 layer->draw(hw, useIdentityTransform);
3996 if (filtering) layer->setFiltering(false);
3997 });
3998 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003999
Mathias Agopian931bda12013-08-28 18:11:46 -07004000 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001}
4002
4003
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004004status_t SurfaceFlinger::captureScreenImplLocked(
4005 const sp<const DisplayDevice>& hw,
4006 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004007 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004008 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004009 bool useIdentityTransform, Transform::orientation_flags rotation,
4010 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004011{
4012 ATRACE_CALL();
4013
Mathias Agopian180f10d2013-04-10 22:55:41 -07004014 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004015 uint32_t hw_w = hw->getWidth();
4016 uint32_t hw_h = hw->getHeight();
4017
4018 if (rotation & Transform::ROT_90) {
4019 std::swap(hw_w, hw_h);
4020 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004021
Mathias Agopian180f10d2013-04-10 22:55:41 -07004022 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4023 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4024 reqWidth, reqHeight, hw_w, hw_h);
4025 return BAD_VALUE;
4026 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004027
Mathias Agopian180f10d2013-04-10 22:55:41 -07004028 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4029 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4030
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004031 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004032 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004033 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004034 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4035 (state.z < minLayerZ || state.z > maxLayerZ)) {
4036 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004037 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004038 layer->traverseInZOrder([&](Layer *layer) {
4039 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4040 layer->isSecure());
4041 });
4042 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004043
4044 if (!isLocalScreenshot && secureLayerIsVisible) {
4045 ALOGW("FB is protected: PERMISSION_DENIED");
4046 return PERMISSION_DENIED;
4047 }
4048
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004049 // create a surface (because we're a producer, and we need to
4050 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004051 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004052
4053 // Put the screenshot Surface into async mode so that
4054 // Layer::headFenceHasSignaled will always return true and we'll latch the
4055 // first buffer regardless of whether or not its acquire fence has
4056 // signaled. This is needed to avoid a race condition in the rotation
4057 // animation. See b/30209608
4058 sur->setAsyncMode(true);
4059
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004060 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004061
Michael Lentine5a16a622015-05-21 13:48:24 -07004062 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4063 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004064 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4065 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004066
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004067 int err = 0;
4068 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004069 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004070 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4071 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004072
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004073 if (err == NO_ERROR) {
4074 ANativeWindowBuffer* buffer;
4075 /* TODO: Once we have the sync framework everywhere this can use
4076 * server-side waits on the fence that dequeueBuffer returns.
4077 */
4078 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4079 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004080 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 // create an EGLImage from the buffer so we can later
4082 // turn it into a texture
4083 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4084 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4085 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004086 // this binds the given EGLImage as a framebuffer for the
4087 // duration of this scope.
4088 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4089 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004090 // this will in fact render into our dequeued buffer
4091 // via an FBO, which means we didn't have to create
4092 // an EGLSurface and therefore we're not
4093 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004094 renderScreenImplLocked(
4095 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4096 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004097
Riley Andrews86639902014-08-15 12:27:24 -07004098 // Attempt to create a sync khr object that can produce a sync point. If that
4099 // isn't available, create a non-dupable sync object in the fallback path and
4100 // wait on it directly.
4101 EGLSyncKHR sync;
4102 if (!DEBUG_SCREENSHOTS) {
4103 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004104 // native fence fd will not be populated until flush() is done.
4105 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004106 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004107 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004108 }
Riley Andrews86639902014-08-15 12:27:24 -07004109 if (sync != EGL_NO_SYNC_KHR) {
4110 // get the sync fd
4111 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4112 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4113 ALOGW("captureScreen: failed to dup sync khr object");
4114 syncFd = -1;
4115 }
4116 eglDestroySyncKHR(mEGLDisplay, sync);
4117 } else {
4118 // fallback path
4119 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4120 if (sync != EGL_NO_SYNC_KHR) {
4121 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4122 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4123 EGLint eglErr = eglGetError();
4124 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4125 ALOGW("captureScreen: fence wait timed out");
4126 } else {
4127 ALOGW_IF(eglErr != EGL_SUCCESS,
4128 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4129 }
4130 eglDestroySyncKHR(mEGLDisplay, sync);
4131 } else {
4132 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4133 }
4134 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004135 if (DEBUG_SCREENSHOTS) {
4136 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4137 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4138 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4139 hw, minLayerZ, maxLayerZ);
4140 delete [] pixels;
4141 }
4142
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004143 } else {
4144 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4145 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004146 window->cancelBuffer(window, buffer, syncFd);
4147 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004148 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004149 // destroy our image
4150 eglDestroyImageKHR(mEGLDisplay, image);
4151 } else {
4152 result = BAD_VALUE;
4153 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004154 if (buffer) {
4155 // queueBuffer takes ownership of syncFd
4156 result = window->queueBuffer(window, buffer, syncFd);
4157 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004158 }
4159 } else {
4160 result = BAD_VALUE;
4161 }
4162 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4163 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004164
Mathias Agopian74c40c02010-09-29 13:02:36 -07004165 return result;
4166}
4167
Mathias Agopiand5556842013-09-19 17:08:37 -07004168void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004169 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004170 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004171 for (size_t y=0 ; y<h ; y++) {
4172 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4173 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004174 if (p[x] != 0xFF000000) return;
4175 }
4176 }
4177 ALOGE("*** we just took a black screenshot ***\n"
4178 "requested minz=%d, maxz=%d, layerStack=%d",
4179 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004180
Robert Carr2047fae2016-11-28 14:09:09 -08004181 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004182 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004183 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004184 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4185 state.z <= maxLayerZ) {
4186 layer->traverseInZOrder([&](Layer* layer) {
4187 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4188 layer->isVisible() ? '+' : '-',
4189 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004190 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 i++;
4192 });
4193 }
4194 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004195 }
4196}
4197
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004198// ---------------------------------------------------------------------------
4199
Robert Carr2047fae2016-11-28 14:09:09 -08004200void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4201 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004202}
4203
Robert Carr2047fae2016-11-28 14:09:09 -08004204void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4205 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004206}
4207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004209
4210
4211#if defined(__gl_h_)
4212#error "don't include gl/gl.h in this file"
4213#endif
4214
4215#if defined(__gl2_h_)
4216#error "don't include gl2/gl2.h in this file"
4217#endif