blob: e4e1ee8bb28fc39e07820b9d86f086318965fe9a [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
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
Jiyong Park4b20c2e2017-01-14 19:45:11 +090084#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
85
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#define DISPLAY_COUNT 1
87
Mathias Agopianfee2b462013-07-03 12:34:01 -070088/*
89 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
90 * black pixels.
91 */
92#define DEBUG_SCREENSHOTS false
93
Mathias Agopianca088332013-03-28 17:44:13 -070094EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070097
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098using namespace android::hardware::configstore::V1_0;
99
100static sp<ISurfaceFlingerConfigs> getConfigs() {
101 static sp<ISurfaceFlingerConfigs> configs
102 = ISurfaceFlingerConfigs::getService();
103 return configs;
104}
105
106static int64_t getVsyncEventPhaseOffsetNs() {
107 int64_t ret = 1000000; // default value
108 getConfigs()->vsyncEventPhaseOffsetNs([&](OptionalInt64 value) {
109 if (value.specified) ret = value.value;
110 });
111 return ret;
112}
113
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700114// This is the phase offset in nanoseconds of the software vsync event
115// relative to the vsync event reported by HWComposer. The software vsync
116// event is when SurfaceFlinger and Choreographer-based applications run each
117// frame.
118//
119// This phase offset allows adjustment of the minimum latency from application
120// wake-up (by Choregographer) time to the time at which the resulting window
121// image is displayed. This value may be either positive (after the HW vsync)
122// or negative (before the HW vsync). Setting it to 0 will result in a
123// minimum latency of two vsync periods because the app and SurfaceFlinger
124// will run just after the HW vsync. Setting it to a positive number will
125// result in the minimum latency being:
126//
127// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
128//
129// Note that reducing this latency makes it more likely for the applications
130// to not have their window content image ready in time. When this happens
131// the latency will end up being an additional vsync period, and animations
132// will hiccup. Therefore, this latency should be tuned somewhat
133// conservatively (or at least with awareness of the trade-off being made).
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900134static int64_t vsyncPhaseOffsetNs = getVsyncEventPhaseOffsetNs();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700135
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700136// This is the phase offset at which SurfaceFlinger's composition runs.
137static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139// ---------------------------------------------------------------------------
140
Mathias Agopian99b49842011-06-27 16:05:52 -0700141const String16 sHardwareTest("android.permission.HARDWARE_TEST");
142const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
143const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
144const String16 sDump("android.permission.DUMP");
145
146// ---------------------------------------------------------------------------
147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800148SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700149 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700151 mTransactionPending(false),
152 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700153 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700154 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700155 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800157 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800159 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800160 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700162 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700163 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700164 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700165 mDebugInSwapBuffers(0),
166 mLastSwapBufferTime(0),
167 mDebugInTransaction(0),
168 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700169 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700170 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700171 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000172 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700173 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700174 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800175 mHasColorMatrix(false),
176 mHasPoweredOff(false),
177 mFrameBuckets(),
178 mTotalTime(0),
179 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180{
Steve Blocka19954a2012-01-04 20:05:49 +0000181 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182
183 // debugging stuff...
184 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700185
Mathias Agopianb4b17302013-03-20 18:36:41 -0700186 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700187 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 property_get("debug.sf.showupdates", value, "0");
190 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700191
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700192 property_get("debug.sf.ddms", value, "0");
193 mDebugDDMS = atoi(value);
194 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700195 if (!startDdmConnection()) {
196 // start failed, and DDMS debugging not enabled
197 mDebugDDMS = 0;
198 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700200 ALOGI_IF(mDebugRegion, "showupdates enabled");
201 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700202
203 property_get("debug.sf.disable_backpressure", value, "0");
204 mPropagateBackpressure = !atoi(value);
205 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700206
207 property_get("debug.sf.disable_hwc_vds", value, "0");
208 mUseHwcVirtualDisplays = !atoi(value);
209 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800210
211 property_get("ro.sf.disable_triple_buffer", value, "0");
212 mLayerTripleBufferingDisabled = !atoi(value);
213 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214}
215
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800216void SurfaceFlinger::onFirstRef()
217{
218 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219}
220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221SurfaceFlinger::~SurfaceFlinger()
222{
Mathias Agopiana4912602012-07-12 14:25:33 -0700223 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
224 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
225 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226}
227
Dan Stozac7014012014-02-14 15:03:43 -0800228void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229{
230 // the window manager died on us. prepare its eulogy.
231
Andy McFadden13a082e2012-08-24 10:16:42 -0700232 // restore initial conditions (default device unblank, etc)
233 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800234
235 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700236 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800237}
238
Mathias Agopian7e27f052010-05-28 14:22:23 -0700239sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240{
Mathias Agopian96f08192010-06-02 23:28:45 -0700241 sp<ISurfaceComposerClient> bclient;
242 sp<Client> client(new Client(this));
243 status_t err = client->initCheck();
244 if (err == NO_ERROR) {
245 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 return bclient;
248}
249
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700250sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
251 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700252{
253 class DisplayToken : public BBinder {
254 sp<SurfaceFlinger> flinger;
255 virtual ~DisplayToken() {
256 // no more references, this display must be terminated
257 Mutex::Autolock _l(flinger->mStateLock);
258 flinger->mCurrentState.displays.removeItem(this);
259 flinger->setTransactionFlags(eDisplayTransactionNeeded);
260 }
261 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700262 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700263 : flinger(flinger) {
264 }
265 };
266
267 sp<BBinder> token = new DisplayToken(this);
268
269 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700270 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700271 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700272 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700273 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700274 return token;
275}
276
Jesse Hall6c913be2013-08-08 12:15:49 -0700277void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
278 Mutex::Autolock _l(mStateLock);
279
280 ssize_t idx = mCurrentState.displays.indexOfKey(display);
281 if (idx < 0) {
282 ALOGW("destroyDisplay: invalid display token");
283 return;
284 }
285
286 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
287 if (!info.isVirtualDisplay()) {
288 ALOGE("destroyDisplay called for non-virtual display");
289 return;
290 }
Irvelffc9efc2016-07-27 15:16:37 -0700291 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700292 mCurrentState.displays.removeItemsAt(idx);
293 setTransactionFlags(eDisplayTransactionNeeded);
294}
295
Jesse Hall692c7232012-11-08 15:41:56 -0800296void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800297 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800298 ALOGW_IF(mBuiltinDisplays[type],
299 "Overwriting display token for display type %d", type);
300 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800301 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700302 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800303 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700304 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800305}
306
Mathias Agopiane57f2922012-08-09 16:29:12 -0700307sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700308 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700309 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
310 return NULL;
311 }
Jesse Hall692c7232012-11-08 15:41:56 -0800312 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700313}
314
Jamie Gennis9a78c902011-01-12 18:30:40 -0800315sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
316{
317 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
318 return gba;
319}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321void SurfaceFlinger::bootFinished()
322{
323 const nsecs_t now = systemTime();
324 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000325 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700326 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700327
328 // wait patiently for the window manager death
329 const String16 name("window");
330 sp<IBinder> window(defaultServiceManager()->getService(name));
331 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700332 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700333 }
334
335 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700336 // formerly we would just kill the process, but we now ask it to exit so it
337 // can choose where to stop the animation.
338 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700339
340 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
341 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
342 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian3f844832013-08-07 21:24:32 -0700345void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700346 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700347 RenderEngine& engine;
348 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700349 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700350 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
351 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700352 }
353 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700354 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700355 return true;
356 }
357 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700358 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700359}
360
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361class DispSyncSource : public VSyncSource, private DispSync::Callback {
362public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700363 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000364 const char* name) :
365 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700366 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700367 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000368 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
369 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700370 mDispSync(dispSync),
371 mCallbackMutex(),
372 mCallback(),
373 mVsyncMutex(),
374 mPhaseOffset(phaseOffset),
375 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700376
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 virtual ~DispSyncSource() {}
378
379 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000382 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700383 static_cast<DispSync::Callback*>(this));
384 if (err != NO_ERROR) {
385 ALOGE("error registering vsync callback: %s (%d)",
386 strerror(-err), err);
387 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700388 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389 } else {
390 status_t err = mDispSync->removeEventListener(
391 static_cast<DispSync::Callback*>(this));
392 if (err != NO_ERROR) {
393 ALOGE("error unregistering vsync callback: %s (%d)",
394 strerror(-err), err);
395 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700397 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700399 }
400
401 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700402 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700403 mCallback = callback;
404 }
405
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700406 virtual void setPhaseOffset(nsecs_t phaseOffset) {
407 Mutex::Autolock lock(mVsyncMutex);
408
409 // Normalize phaseOffset to [0, period)
410 auto period = mDispSync->getPeriod();
411 phaseOffset %= period;
412 if (phaseOffset < 0) {
413 // If we're here, then phaseOffset is in (-period, 0). After this
414 // operation, it will be in (0, period)
415 phaseOffset += period;
416 }
417 mPhaseOffset = phaseOffset;
418
419 // If we're not enabled, we don't need to mess with the listeners
420 if (!mEnabled) {
421 return;
422 }
423
424 // Remove the listener with the old offset
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
431
432 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error registering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
439 }
440
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441private:
442 virtual void onDispSyncEvent(nsecs_t when) {
443 sp<VSyncSource::Callback> callback;
444 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 callback = mCallback;
447
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 if (mTraceVsync) {
449 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700450 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700451 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 }
453
454 if (callback != NULL) {
455 callback->onVSyncEvent(when);
456 }
457 }
458
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 const char* const mName;
460
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 int mValue;
462
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700463 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700464 const String8 mVsyncOnLabel;
465 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468
469 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471
472 Mutex mVsyncMutex; // Protects the following
473 nsecs_t mPhaseOffset;
474 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700475};
476
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700477class InjectVSyncSource : public VSyncSource {
478public:
479 InjectVSyncSource() {}
480
481 virtual ~InjectVSyncSource() {}
482
483 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
484 std::lock_guard<std::mutex> lock(mCallbackMutex);
485 mCallback = callback;
486 }
487
488 virtual void onInjectSyncEvent(nsecs_t when) {
489 std::lock_guard<std::mutex> lock(mCallbackMutex);
490 mCallback->onVSyncEvent(when);
491 }
492
493 virtual void setVSyncEnabled(bool) {}
494 virtual void setPhaseOffset(nsecs_t) {}
495
496private:
497 std::mutex mCallbackMutex; // Protects the following
498 sp<VSyncSource::Callback> mCallback;
499};
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700502 ALOGI( "SurfaceFlinger's main thread ready to run. "
503 "Initializing graphics H/W...");
504
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900505 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
506
Dan Stoza9e56aa02015-11-02 13:00:03 -0800507 { // Autolock scope
508 Mutex::Autolock _l(mStateLock);
509
510 // initialize EGL for the default display
511 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
512 eglInitialize(mEGLDisplay, NULL, NULL);
513
514 // start the EventThread
515 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
516 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700517 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800518 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
519 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700520 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800521 mEventQueue.setEventThread(mSFEventThread);
522
Tim Murrayacff43d2016-07-29 13:57:24 -0700523 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700524 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700525 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700526 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
527 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
528 }
529
Dan Stoza9e56aa02015-11-02 13:00:03 -0800530 // Get a RenderEngine for the given display / config (can't fail)
531 mRenderEngine = RenderEngine::create(mEGLDisplay,
532 HAL_PIXEL_FORMAT_RGBA_8888);
533 }
534
535 // Drop the state lock while we initialize the hardware composer. We drop
536 // the lock because on creation, it will call back into SurfaceFlinger to
537 // initialize the primary display.
538 mHwc = new HWComposer(this);
539 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
540
Jesse Hall692c7232012-11-08 15:41:56 -0800541 Mutex::Autolock _l(mStateLock);
542
Mathias Agopian875d8e12013-06-07 15:35:48 -0700543 // retrieve the EGL context that was selected/created
544 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700545
Mathias Agopianda27af92012-09-13 18:17:13 -0700546 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
547 "couldn't create EGLContext");
548
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 // make the GLContext current so that we can create textures when creating
550 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700551 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
552
Jamie Gennisd1700752013-10-14 12:22:52 -0700553 mEventControlThread = new EventControlThread(this);
554 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
555
Mathias Agopian92a979a2012-08-02 18:32:23 -0700556 // initialize our drawing state
557 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700558
Andy McFadden13a082e2012-08-24 10:16:42 -0700559 // set initial conditions (e.g. unblank default device)
560 initializeDisplays();
561
Dan Stoza4e637772016-07-28 13:31:51 -0700562 mRenderEngine->primeCache();
563
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700564 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700565 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800566
Dan Stoza9e56aa02015-11-02 13:00:03 -0800567 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700568}
569
Mathias Agopiana67e4182012-06-19 17:26:12 -0700570void SurfaceFlinger::startBootAnim() {
571 // start boot animation
572 property_set("service.bootanim.exit", "0");
573 property_set("ctl.start", "bootanim");
574}
575
Mathias Agopian875d8e12013-06-07 15:35:48 -0700576size_t SurfaceFlinger::getMaxTextureSize() const {
577 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700578}
579
Mathias Agopian875d8e12013-06-07 15:35:48 -0700580size_t SurfaceFlinger::getMaxViewportDims() const {
581 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700582}
583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800585
Jamie Gennis582270d2011-08-17 18:19:00 -0700586bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800587 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800588 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800589 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700590 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800591}
592
Brian Anderson069b3652016-07-22 10:32:47 -0700593status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700594 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700595 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700596 FrameEvent::REQUESTED_PRESENT,
597 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700598 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700599 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700600 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700601 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700602 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700603 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700604 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700605 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700606 };
607 return NO_ERROR;
608}
609
Dan Stoza7f7da322014-05-02 15:26:25 -0700610status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
611 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700612 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700613 return BAD_VALUE;
614 }
615
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500616 if (!display.get())
617 return NAME_NOT_FOUND;
618
Jesse Hall692c7232012-11-08 15:41:56 -0800619 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700620 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800621 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700622 type = i;
623 break;
624 }
625 }
626
627 if (type < 0) {
628 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700629 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700630
Mathias Agopian8b736f12012-08-13 17:54:26 -0700631 // TODO: Not sure if display density should handled by SF any longer
632 class Density {
633 static int getDensityFromProperty(char const* propName) {
634 char property[PROPERTY_VALUE_MAX];
635 int density = 0;
636 if (property_get(propName, property, NULL) > 0) {
637 density = atoi(property);
638 }
639 return density;
640 }
641 public:
642 static int getEmuDensity() {
643 return getDensityFromProperty("qemu.sf.lcd_density"); }
644 static int getBuildDensity() {
645 return getDensityFromProperty("ro.sf.lcd_density"); }
646 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700647
Dan Stoza7f7da322014-05-02 15:26:25 -0700648 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700649
Dan Stoza9e56aa02015-11-02 13:00:03 -0800650 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700651 DisplayInfo info = DisplayInfo();
652
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653 float xdpi = hwConfig->getDpiX();
654 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700655
656 if (type == DisplayDevice::DISPLAY_PRIMARY) {
657 // The density of the device is provided by a build property
658 float density = Density::getBuildDensity() / 160.0f;
659 if (density == 0) {
660 // the build doesn't provide a density -- this is wrong!
661 // use xdpi instead
662 ALOGE("ro.sf.lcd_density must be defined as a build property");
663 density = xdpi / 160.0f;
664 }
665 if (Density::getEmuDensity()) {
666 // if "qemu.sf.lcd_density" is specified, it overrides everything
667 xdpi = ydpi = density = Density::getEmuDensity();
668 density /= 160.0f;
669 }
670 info.density = density;
671
672 // TODO: this needs to go away (currently needed only by webkit)
673 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
674 info.orientation = hw->getOrientation();
675 } else {
676 // TODO: where should this value come from?
677 static const int TV_DENSITY = 213;
678 info.density = TV_DENSITY / 160.0f;
679 info.orientation = 0;
680 }
681
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682 info.w = hwConfig->getWidth();
683 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700684 info.xdpi = xdpi;
685 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900687 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688
Andy McFadden91b2ca82014-06-13 14:04:23 -0700689 // This is how far in advance a buffer must be queued for
690 // presentation at a given time. If you want a buffer to appear
691 // on the screen at time N, you must submit the buffer before
692 // (N - presentationDeadline).
693 //
694 // Normally it's one full refresh period (to give SF a chance to
695 // latch the buffer), but this can be reduced by configuring a
696 // DispSync offset. Any additional delays introduced by the hardware
697 // composer or panel must be accounted for here.
698 //
699 // We add an additional 1ms to allow for processing time and
700 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 info.presentationDeadline = hwConfig->getVsyncPeriod() -
702 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700703
704 // All non-virtual displays are currently considered secure.
705 info.secure = true;
706
Michael Wright28f24d02016-07-12 13:30:53 -0700707 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700708 }
709
Dan Stoza7f7da322014-05-02 15:26:25 -0700710 return NO_ERROR;
711}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700712
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800713status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700714 DisplayStatInfo* stats) {
715 if (stats == NULL) {
716 return BAD_VALUE;
717 }
718
719 // FIXME for now we always return stats for the primary display
720 memset(stats, 0, sizeof(*stats));
721 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
722 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
723 return NO_ERROR;
724}
725
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700726int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800727 if (display == NULL) {
728 ALOGE("%s : display is NULL", __func__);
729 return BAD_VALUE;
730 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700731 sp<DisplayDevice> device(getDisplayDevice(display));
732 if (device != NULL) {
733 return device->getActiveConfig();
734 }
735 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700736}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700737
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700738void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
739 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
740 this);
741 int32_t type = hw->getDisplayType();
742 int currentMode = hw->getActiveConfig();
743
744 if (mode == currentMode) {
745 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
746 return;
747 }
748
749 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
750 ALOGW("Trying to set config for virtual display");
751 return;
752 }
753
754 hw->setActiveConfig(mode);
755 getHwComposer().setActiveConfig(type, mode);
756}
757
758status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
759 class MessageSetActiveConfig: public MessageBase {
760 SurfaceFlinger& mFlinger;
761 sp<IBinder> mDisplay;
762 int mMode;
763 public:
764 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
765 int mode) :
766 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
767 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700768 Vector<DisplayInfo> configs;
769 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700770 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700771 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700772 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700773 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700774 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700775 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
776 if (hw == NULL) {
777 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700778 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700779 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
780 ALOGW("Attempt to set active config = %d for virtual display",
781 mMode);
782 } else {
783 mFlinger.setActiveConfigInternal(hw, mMode);
784 }
785 return true;
786 }
787 };
788 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
789 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700790 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700791}
Michael Wright28f24d02016-07-12 13:30:53 -0700792status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
793 Vector<android_color_mode_t>* outColorModes) {
794 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
795 return BAD_VALUE;
796 }
797
798 if (!display.get()) {
799 return NAME_NOT_FOUND;
800 }
801
802 int32_t type = NAME_NOT_FOUND;
803 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
804 if (display == mBuiltinDisplays[i]) {
805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
812 }
813
814 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
815 outColorModes->clear();
816 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
817
818 return NO_ERROR;
819}
820
821android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
822 sp<DisplayDevice> device(getDisplayDevice(display));
823 if (device != nullptr) {
824 return device->getActiveColorMode();
825 }
826 return static_cast<android_color_mode_t>(BAD_VALUE);
827}
828
829void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
830 android_color_mode_t mode) {
831 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
832 this);
833 int32_t type = hw->getDisplayType();
834 android_color_mode_t currentMode = hw->getActiveColorMode();
835
836 if (mode == currentMode) {
837 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
838 return;
839 }
840
841 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
842 ALOGW("Trying to set config for virtual display");
843 return;
844 }
845
846 hw->setActiveColorMode(mode);
847 getHwComposer().setActiveColorMode(type, mode);
848}
849
850
851status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
852 android_color_mode_t colorMode) {
853 class MessageSetActiveColorMode: public MessageBase {
854 SurfaceFlinger& mFlinger;
855 sp<IBinder> mDisplay;
856 android_color_mode_t mMode;
857 public:
858 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
859 android_color_mode_t mode) :
860 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
861 virtual bool handler() {
862 Vector<android_color_mode_t> modes;
863 mFlinger.getDisplayColorModes(mDisplay, &modes);
864 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
865 if (mMode < 0 || !exists) {
866 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
867 mDisplay.get());
868 return true;
869 }
870 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
871 if (hw == nullptr) {
872 ALOGE("Attempt to set active color mode = %d for null display %p",
873 mMode, mDisplay.get());
874 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
875 ALOGW("Attempt to set active color mode= %d for virtual display",
876 mMode);
877 } else {
878 mFlinger.setActiveColorModeInternal(hw, mMode);
879 }
880 return true;
881 }
882 };
883 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
884 postMessageSync(msg);
885 return NO_ERROR;
886}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700887
Svetoslavd85084b2014-03-20 10:28:31 -0700888status_t SurfaceFlinger::clearAnimationFrameStats() {
889 Mutex::Autolock _l(mStateLock);
890 mAnimFrameTracker.clearStats();
891 return NO_ERROR;
892}
893
894status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
895 Mutex::Autolock _l(mStateLock);
896 mAnimFrameTracker.getStats(outStats);
897 return NO_ERROR;
898}
899
Dan Stozac4f471e2016-03-24 09:31:08 -0700900status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
901 HdrCapabilities* outCapabilities) const {
902 Mutex::Autolock _l(mStateLock);
903
904 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
905 if (displayDevice == nullptr) {
906 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
907 return BAD_VALUE;
908 }
909
910 std::unique_ptr<HdrCapabilities> capabilities =
911 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
912 if (capabilities) {
913 std::swap(*outCapabilities, *capabilities);
914 } else {
915 return BAD_VALUE;
916 }
917
918 return NO_ERROR;
919}
920
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700921status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
922 if (enable == mInjectVSyncs) {
923 return NO_ERROR;
924 }
925
926 if (enable) {
927 mInjectVSyncs = enable;
928 ALOGV("VSync Injections enabled");
929 if (mVSyncInjector.get() == nullptr) {
930 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700931 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700932 }
933 mEventQueue.setEventThread(mInjectorEventThread);
934 } else {
935 mInjectVSyncs = enable;
936 ALOGV("VSync Injections disabled");
937 mEventQueue.setEventThread(mSFEventThread);
938 mVSyncInjector.clear();
939 }
940 return NO_ERROR;
941}
942
943status_t SurfaceFlinger::injectVSync(nsecs_t when) {
944 if (!mInjectVSyncs) {
945 ALOGE("VSync Injections not enabled");
946 return BAD_VALUE;
947 }
948 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
949 ALOGV("Injecting VSync inside SurfaceFlinger");
950 mVSyncInjector->onInjectSyncEvent(when);
951 }
952 return NO_ERROR;
953}
954
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800955// ----------------------------------------------------------------------------
956
957sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800958 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700959}
960
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800962
963void SurfaceFlinger::waitForEvent() {
964 mEventQueue.waitMessage();
965}
966
967void SurfaceFlinger::signalTransaction() {
968 mEventQueue.invalidate();
969}
970
971void SurfaceFlinger::signalLayerUpdate() {
972 mEventQueue.invalidate();
973}
974
975void SurfaceFlinger::signalRefresh() {
976 mEventQueue.refresh();
977}
978
979status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800980 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800981 return mEventQueue.postMessage(msg, reltime);
982}
983
984status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800985 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800986 status_t res = mEventQueue.postMessage(msg, reltime);
987 if (res == NO_ERROR) {
988 msg->wait();
989 }
990 return res;
991}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800992
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700993void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700994 do {
995 waitForEvent();
996 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800997}
998
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700999void SurfaceFlinger::enableHardwareVsync() {
1000 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001001 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001002 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001003 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1004 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001005 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001006 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001007}
1008
Jesse Hall948fe0c2013-10-14 12:56:09 -07001009void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001010 Mutex::Autolock _l(mHWVsyncLock);
1011
Jesse Hall948fe0c2013-10-14 12:56:09 -07001012 if (makeAvailable) {
1013 mHWVsyncAvailable = true;
1014 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001015 // Hardware vsync is not currently available, so abort the resync
1016 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001017 return;
1018 }
1019
Dan Stoza9e56aa02015-11-02 13:00:03 -08001020 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1021 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001022
1023 mPrimaryDispSync.reset();
1024 mPrimaryDispSync.setPeriod(period);
1025
1026 if (!mPrimaryHWVsyncEnabled) {
1027 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001028 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1029 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001030 mPrimaryHWVsyncEnabled = true;
1031 }
1032}
1033
Jesse Hall948fe0c2013-10-14 12:56:09 -07001034void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001035 Mutex::Autolock _l(mHWVsyncLock);
1036 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001037 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1038 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001039 mPrimaryDispSync.endResync();
1040 mPrimaryHWVsyncEnabled = false;
1041 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001042 if (makeUnavailable) {
1043 mHWVsyncAvailable = false;
1044 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001045}
1046
Tim Murray4a4e4a22016-04-19 16:29:23 +00001047void SurfaceFlinger::resyncWithRateLimit() {
1048 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1049 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001050 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001051 }
1052}
1053
Dan Stoza9e56aa02015-11-02 13:00:03 -08001054void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001056
Jamie Gennisd1700752013-10-14 12:22:52 -07001057 { // Scope for the lock
1058 Mutex::Autolock _l(mHWVsyncLock);
1059 if (type == 0 && mPrimaryHWVsyncEnabled) {
1060 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001062 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001063
1064 if (needsHwVsync) {
1065 enableHardwareVsync();
1066 } else {
1067 disableHardwareVsync(false);
1068 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001069}
1070
Dan Stoza9e56aa02015-11-02 13:00:03 -08001071void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1072 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1073 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1074 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001075
Dan Stoza9e56aa02015-11-02 13:00:03 -08001076 // All non-virtual displays are currently considered secure.
1077 bool isSecure = true;
1078
1079 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1080 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1081 wp<IBinder> token = mBuiltinDisplays[type];
1082
1083 sp<IGraphicBufferProducer> producer;
1084 sp<IGraphicBufferConsumer> consumer;
1085 BufferQueue::createBufferQueue(&producer, &consumer,
1086 new GraphicBufferAlloc());
1087
1088 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1089 DisplayDevice::DISPLAY_PRIMARY, consumer);
1090 sp<DisplayDevice> hw = new DisplayDevice(this,
1091 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1092 producer, mRenderEngine->getEGLConfig());
1093 mDisplays.add(token, hw);
1094 } else {
1095 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001096 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001097 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001098 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001099 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001100 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1101 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001102 }
1103 setTransactionFlags(eDisplayTransactionNeeded);
1104
Andy McFadden9e9689c2012-10-10 18:17:51 -07001105 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001106 }
Mathias Agopian86303202012-07-24 22:46:10 -07001107}
1108
Dan Stoza9e56aa02015-11-02 13:00:03 -08001109void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001111 getHwComposer().setVsyncEnabled(disp,
1112 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001113}
1114
Mathias Agopian4fec8732012-06-29 14:12:52 -07001115void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001116 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001117 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001118 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001119 bool frameMissed = !mHadClientComposition &&
1120 mPreviousPresentFence != Fence::NO_FENCE &&
1121 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1122 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001123 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001124 signalLayerUpdate();
1125 break;
1126 }
1127
Dan Stoza6b9454d2014-11-07 16:00:59 -08001128 bool refreshNeeded = handleMessageTransaction();
1129 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001130 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001131 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001132 // Signal a refresh if a transaction modified the window state,
1133 // a new buffer was latched, or if HWC has requested a full
1134 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001135 signalRefresh();
1136 }
1137 break;
1138 }
1139 case MessageQueue::REFRESH: {
1140 handleMessageRefresh();
1141 break;
1142 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143 }
1144}
1145
Dan Stoza6b9454d2014-11-07 16:00:59 -08001146bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001147 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001148 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001149 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001150 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001151 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001152 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001153}
1154
Dan Stoza6b9454d2014-11-07 16:00:59 -08001155bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001156 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001157 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001158}
1159
1160void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001161 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001162
Pablo Ceballos40845df2016-01-25 17:41:15 -08001163 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001164
Brian Andersond6927fb2016-07-23 23:37:30 -07001165 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001166 rebuildLayerStacks();
1167 setUpHWComposer();
1168 doDebugFlashRegions();
1169 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001170 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001171
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001172 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001173
1174 mHadClientComposition = false;
1175 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1176 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1177 mHadClientComposition = mHadClientComposition ||
1178 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1179 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001180
Dan Stoza9e56aa02015-11-02 13:00:03 -08001181 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001182}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001183
Mathias Agopiancd60f992012-08-16 16:28:27 -07001184void SurfaceFlinger::doDebugFlashRegions()
1185{
1186 // is debugging enabled
1187 if (CC_LIKELY(!mDebugRegion))
1188 return;
1189
1190 const bool repaintEverything = mRepaintEverything;
1191 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1192 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001193 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001194 // transform the dirty region into this screen's coordinate space
1195 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1196 if (!dirtyRegion.isEmpty()) {
1197 // redraw the whole screen
1198 doComposeSurfaces(hw, Region(hw->bounds()));
1199
1200 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001201 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001202 RenderEngine& engine(getRenderEngine());
1203 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1204
Mathias Agopianda27af92012-09-13 18:17:13 -07001205 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001206 }
1207 }
1208 }
1209
1210 postFramebuffer();
1211
1212 if (mDebugRegion > 1) {
1213 usleep(mDebugRegion * 1000);
1214 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001215
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001217 auto& displayDevice = mDisplays[displayId];
1218 if (!displayDevice->isDisplayOn()) {
1219 continue;
1220 }
1221
1222 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001223 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1224 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001225 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001226}
1227
Brian Andersond6927fb2016-07-23 23:37:30 -07001228void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001229{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001230 ATRACE_CALL();
1231 ALOGV("preComposition");
1232
Mathias Agopiancd60f992012-08-16 16:28:27 -07001233 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001234 const LayerVector& layers(mDrawingState.layersSortedByZ);
1235 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001236 for (size_t i=0 ; i<count ; i++) {
Brian Andersond6927fb2016-07-23 23:37:30 -07001237 if (layers[i]->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001238 needExtraInvalidate = true;
1239 }
1240 }
1241 if (needExtraInvalidate) {
1242 signalLayerUpdate();
1243 }
1244}
1245
Brian Andersond6927fb2016-07-23 23:37:30 -07001246void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001247{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001248 ATRACE_CALL();
1249 ALOGV("postComposition");
1250
Brian Anderson3546a3f2016-07-14 11:51:14 -07001251 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001252 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001253 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001254 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001255 }
1256
Brian Andersond6927fb2016-07-23 23:37:30 -07001257 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001258
1259 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1260 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1261 glCompositionDoneFenceTime =
1262 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1263 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1264 } else {
1265 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1266 }
1267 mGlCompositionDoneTimeline.updateSignalTimes();
1268
1269 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1270 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1271 mDisplayTimeline.push(displayFenceTime);
1272 mDisplayTimeline.updateSignalTimes();
1273
1274 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1275 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1276 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1277 presentFenceTime = &displayFenceTime;
1278 } else {
1279 retireFenceTime = &displayFenceTime;
1280 }
1281
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001282 const LayerVector& layers(mDrawingState.layersSortedByZ);
1283 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001284 for (size_t i=0 ; i<count ; i++) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001285 bool frameLatched =
1286 layers[i]->onPostComposition(glCompositionDoneFenceTime,
1287 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001288 if (frameLatched) {
1289 recordBufferingStats(layers[i]->getName().string(),
1290 layers[i]->getOccupancyHistory(false));
1291 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001292 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001293
Brian Anderson3d4039d2016-09-23 16:31:30 -07001294 if (displayFence->isValid()) {
1295 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 enableHardwareVsync();
1297 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001298 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 }
1300 }
1301
Andy McFadden5167ec62014-05-22 13:08:43 -07001302 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001303 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 enableHardwareVsync();
1305 }
1306 }
1307
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001308 if (mAnimCompositionPending) {
1309 mAnimCompositionPending = false;
1310
Brian Anderson3d4039d2016-09-23 16:31:30 -07001311 if (displayFenceTime->isValid()) {
1312 mAnimFrameTracker.setActualPresentFence(
1313 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001314 } else {
1315 // The HWC doesn't support present fences, so use the refresh
1316 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 nsecs_t presentTime =
1318 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001319 mAnimFrameTracker.setActualPresentTime(presentTime);
1320 }
1321 mAnimFrameTracker.advanceFrame();
1322 }
Dan Stozab90cf072015-03-05 11:05:59 -08001323
1324 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1325 return;
1326 }
1327
1328 nsecs_t currentTime = systemTime();
1329 if (mHasPoweredOff) {
1330 mHasPoweredOff = false;
1331 } else {
1332 nsecs_t period = mPrimaryDispSync.getPeriod();
1333 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1334 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1335 if (numPeriods < NUM_BUCKETS - 1) {
1336 mFrameBuckets[numPeriods] += elapsedTime;
1337 } else {
1338 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1339 }
1340 mTotalTime += elapsedTime;
1341 }
1342 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001343}
1344
1345void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 ATRACE_CALL();
1347 ALOGV("rebuildLayerStacks");
1348
Mathias Agopiancd60f992012-08-16 16:28:27 -07001349 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001350 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001351 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001352 mVisibleRegionsDirty = false;
1353 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001354
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001355 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001356 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001357 Region opaqueRegion;
1358 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 Vector<sp<Layer>> layersSortedByZ;
1360 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1361 const Transform& tr(displayDevice->getTransform());
1362 const Rect bounds(displayDevice->getBounds());
1363 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001364 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365 displayDevice->getLayerStack(), dirtyRegion,
1366 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001367
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001368 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001369 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001370 const sp<Layer>& layer(layers[i]);
1371 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001373 Region drawRegion(tr.transform(
1374 layer->visibleNonTransparentRegion));
1375 drawRegion.andSelf(bounds);
1376 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001377 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001378 } else {
1379 // Clear out the HWC layer if this layer was
1380 // previously visible, but no longer is
1381 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1382 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001383 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001384 }
1385 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001386 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001387 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1388 displayDevice->undefinedRegion.set(bounds);
1389 displayDevice->undefinedRegion.subtractSelf(
1390 tr.transform(opaqueRegion));
1391 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001392 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001393 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001395
Mathias Agopiancd60f992012-08-16 16:28:27 -07001396void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001397 ATRACE_CALL();
1398 ALOGV("setUpHWComposer");
1399
Jesse Hall028dc8f2013-08-20 16:35:32 -07001400 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001401 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1402 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1403 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1404
1405 // If nothing has changed (!dirty), don't recompose.
1406 // If something changed, but we don't currently have any visible layers,
1407 // and didn't when we last did a composition, then skip it this time.
1408 // The second rule does two things:
1409 // - When all layers are removed from a display, we'll emit one black
1410 // frame, then nothing more until we get new layers.
1411 // - When a display is created with a private layer stack, we won't
1412 // emit any black frames until a layer is added to the layer stack.
1413 bool mustRecompose = dirty && !(empty && wasEmpty);
1414
1415 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1416 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1417 mustRecompose ? "doing" : "skipping",
1418 dirty ? "+" : "-",
1419 empty ? "+" : "-",
1420 wasEmpty ? "+" : "-");
1421
Dan Stoza71433162014-02-04 16:22:36 -08001422 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001423
1424 if (mustRecompose) {
1425 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1426 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001427 }
1428
Dan Stoza9e56aa02015-11-02 13:00:03 -08001429 // build the h/w work list
1430 if (CC_UNLIKELY(mGeometryInvalid)) {
1431 mGeometryInvalid = false;
1432 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1433 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1434 const auto hwcId = displayDevice->getHwcDisplayId();
1435 if (hwcId >= 0) {
1436 const Vector<sp<Layer>>& currentLayers(
1437 displayDevice->getVisibleLayersSortedByZ());
1438 bool foundLayerWithoutHwc = false;
1439 for (auto& layer : currentLayers) {
1440 if (!layer->hasHwcLayer(hwcId)) {
1441 auto hwcLayer = mHwc->createLayer(hwcId);
1442 if (hwcLayer) {
1443 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1444 } else {
1445 layer->forceClientComposition(hwcId);
1446 foundLayerWithoutHwc = true;
1447 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001448 }
1449 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001450
Dan Stoza9e56aa02015-11-02 13:00:03 -08001451 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001452 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001454 }
1455 }
1456 }
1457 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001458 }
Riley Andrews03414a12014-07-01 14:22:59 -07001459
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001460
1461 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1462
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 // Set the per-frame data
1464 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1465 auto& displayDevice = mDisplays[displayId];
1466 const auto hwcId = displayDevice->getHwcDisplayId();
1467 if (hwcId < 0) {
1468 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001469 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001470 if (colorMatrix != mPreviousColorMatrix) {
1471 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1472 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1473 "display %zd: %d", displayId, result);
1474 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001475 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1476 layer->setPerFrameData(displayDevice);
1477 }
1478 }
1479
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001480 mPreviousColorMatrix = colorMatrix;
1481
Dan Stoza9e56aa02015-11-02 13:00:03 -08001482 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001483 auto& displayDevice = mDisplays[displayId];
1484 if (!displayDevice->isDisplayOn()) {
1485 continue;
1486 }
1487
1488 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001489 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1490 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001491 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001493
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494void SurfaceFlinger::doComposition() {
1495 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 ALOGV("doComposition");
1497
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001498 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001499 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001500 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001501 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502 // transform the dirty region into this screen's coordinate space
1503 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001504
1505 // repaint the framebuffer (if needed)
1506 doDisplayComposition(hw, dirtyRegion);
1507
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508 hw->dirtyRegion.clear();
1509 hw->flip(hw->swapRegion);
1510 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001511 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001513 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516void SurfaceFlinger::postFramebuffer()
1517{
Mathias Agopian841cde52012-03-01 15:44:37 -08001518 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001519 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001520
Mathias Agopiana44b0412011-10-16 18:46:35 -07001521 const nsecs_t now = systemTime();
1522 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001523
Dan Stoza9e56aa02015-11-02 13:00:03 -08001524 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1525 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001526 if (!displayDevice->isDisplayOn()) {
1527 continue;
1528 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 const auto hwcId = displayDevice->getHwcDisplayId();
1530 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001531 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001532 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001533 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001534 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1536 sp<Fence> releaseFence = Fence::NO_FENCE;
1537 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1538 releaseFence = displayDevice->getClientTargetAcquireFence();
1539 } else {
1540 auto hwcLayer = layer->getHwcLayer(hwcId);
1541 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001542 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001543 layer->onLayerDisplayed(releaseFence);
1544 }
1545 if (hwcId >= 0) {
1546 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001547 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001548 }
1549
Mathias Agopiana44b0412011-10-16 18:46:35 -07001550 mLastSwapBufferTime = systemTime() - now;
1551 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001552
1553 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1554 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1555 logFrameStats();
1556 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557}
1558
Mathias Agopian87baae12012-07-31 12:38:26 -07001559void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560{
Mathias Agopian841cde52012-03-01 15:44:37 -08001561 ATRACE_CALL();
1562
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001563 // here we keep a copy of the drawing state (that is the state that's
1564 // going to be overwritten by handleTransactionLocked()) outside of
1565 // mStateLock so that the side-effects of the State assignment
1566 // don't happen with mStateLock held (which can cause deadlocks).
1567 State drawingState(mDrawingState);
1568
Mathias Agopianca4d3602011-05-19 15:38:14 -07001569 Mutex::Autolock _l(mStateLock);
1570 const nsecs_t now = systemTime();
1571 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001572
Mathias Agopianca4d3602011-05-19 15:38:14 -07001573 // Here we're guaranteed that some transaction flags are set
1574 // so we can call handleTransactionLocked() unconditionally.
1575 // We call getTransactionFlags(), which will also clear the flags,
1576 // with mStateLock held to guarantee that mCurrentState won't change
1577 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001578
Mathias Agopiane57f2922012-08-09 16:29:12 -07001579 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001580 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001581
Mathias Agopianca4d3602011-05-19 15:38:14 -07001582 mLastTransactionTime = systemTime() - now;
1583 mDebugInTransaction = 0;
1584 invalidateHwcGeometry();
1585 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001586}
1587
Mathias Agopian87baae12012-07-31 12:38:26 -07001588void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001589{
1590 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001591 const size_t count = currentLayers.size();
1592
Dan Stoza7dde5992015-05-22 09:51:44 -07001593 // Notify all layers of available frames
1594 for (size_t i = 0; i < count; ++i) {
1595 currentLayers[i]->notifyAvailableFrames();
1596 }
1597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001598 /*
1599 * Traversal of the children
1600 * (perform the transaction for each of them if needed)
1601 */
1602
Mathias Agopian3559b072012-08-15 13:46:03 -07001603 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001604 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001605 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001606 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1607 if (!trFlags) continue;
1608
1609 const uint32_t flags = layer->doTransaction(0);
1610 if (flags & Layer::eVisibleRegion)
1611 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001612 }
1613 }
1614
1615 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001616 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001617 */
1618
Mathias Agopiane57f2922012-08-09 16:29:12 -07001619 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001620 // here we take advantage of Vector's copy-on-write semantics to
1621 // improve performance by skipping the transaction entirely when
1622 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001623 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1624 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001625 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001626 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001627 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001628 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001629
1630 // find the displays that were removed
1631 // (ie: in drawing state but not in current state)
1632 // also handle displays that changed
1633 // (ie: displays that are in both lists)
1634 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001635 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1636 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001637 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001638 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001639 // Call makeCurrent() on the primary display so we can
1640 // be sure that nothing associated with this display
1641 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001642 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001643 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001644 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1645 if (hw != NULL)
1646 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001647 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001648 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001649 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001650 } else {
1651 ALOGW("trying to remove the main display");
1652 }
1653 } else {
1654 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001655 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001656 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001657 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1658 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001659 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001660 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001661 // recreating the DisplayDevice, so we just remove it
1662 // from the drawing state, so that it get re-added
1663 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001664 sp<DisplayDevice> hw(getDisplayDevice(display));
1665 if (hw != NULL)
1666 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001667 mDisplays.removeItem(display);
1668 mDrawingState.displays.removeItemsAt(i);
1669 dc--; i--;
1670 // at this point we must loop to the next item
1671 continue;
1672 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001673
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001674 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001675 if (disp != NULL) {
1676 if (state.layerStack != draw[i].layerStack) {
1677 disp->setLayerStack(state.layerStack);
1678 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001679 if ((state.orientation != draw[i].orientation)
1680 || (state.viewport != draw[i].viewport)
1681 || (state.frame != draw[i].frame))
1682 {
1683 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001684 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001685 }
Michael Lentine47e45402014-07-18 15:34:25 -07001686 if (state.width != draw[i].width || state.height != draw[i].height) {
1687 disp->setDisplaySize(state.width, state.height);
1688 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001689 }
1690 }
1691 }
1692
1693 // find displays that were added
1694 // (ie: in current state but not in drawing state)
1695 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001696 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001697 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001698
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001699 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001700 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001701 sp<IGraphicBufferProducer> bqProducer;
1702 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001703 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1704 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001705
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001707 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001708 // Virtual displays without a surface are dormant:
1709 // they have external state (layer stack, projection,
1710 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001711 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001712
Dan Stoza8cf150a2016-08-02 10:27:31 -07001713 if (mUseHwcVirtualDisplays) {
1714 int width = 0;
1715 int status = state.surface->query(
1716 NATIVE_WINDOW_WIDTH, &width);
1717 ALOGE_IF(status != NO_ERROR,
1718 "Unable to query width (%d)", status);
1719 int height = 0;
1720 status = state.surface->query(
1721 NATIVE_WINDOW_HEIGHT, &height);
1722 ALOGE_IF(status != NO_ERROR,
1723 "Unable to query height (%d)", status);
1724 int intFormat = 0;
1725 status = state.surface->query(
1726 NATIVE_WINDOW_FORMAT, &intFormat);
1727 ALOGE_IF(status != NO_ERROR,
1728 "Unable to query format (%d)", status);
1729 auto format = static_cast<android_pixel_format_t>(
1730 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001731
Dan Stoza8cf150a2016-08-02 10:27:31 -07001732 mHwc->allocateVirtualDisplay(width, height, &format,
1733 &hwcId);
1734 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735
Dan Stoza5cf424b2016-05-20 14:02:39 -07001736 // TODO: Plumb requested format back up to consumer
1737
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 sp<VirtualDisplaySurface> vds =
1739 new VirtualDisplaySurface(*mHwc,
1740 hwcId, state.surface, bqProducer,
1741 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001742
1743 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001744 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001745 }
1746 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001747 ALOGE_IF(state.surface!=NULL,
1748 "adding a supported display, but rendering "
1749 "surface is provided (%p), ignoring it",
1750 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1752 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1753 dispSurface = new FramebufferSurface(*mHwc,
1754 DisplayDevice::DISPLAY_EXTERNAL,
1755 bqConsumer);
1756 producer = bqProducer;
1757 } else {
1758 ALOGE("Attempted to add non-external non-virtual"
1759 " display");
1760 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001761 }
1762
1763 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001764 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001765 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766 state.type, hwcId, state.isSecure, display,
1767 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001768 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001769 hw->setLayerStack(state.layerStack);
1770 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001771 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001772 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001773 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001774 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001775 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001776 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001777 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001778 }
1779 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001780 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001781 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001782
Mathias Agopian84300952012-11-21 16:02:13 -08001783 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1784 // The transform hint might have changed for some layers
1785 // (either because a display has changed, or because a layer
1786 // as changed).
1787 //
1788 // Walk through all the layers in currentLayers,
1789 // and update their transform hint.
1790 //
1791 // If a layer is visible only on a single display, then that
1792 // display is used to calculate the hint, otherwise we use the
1793 // default display.
1794 //
1795 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1796 // the hint is set before we acquire a buffer from the surface texture.
1797 //
1798 // NOTE: layer transactions have taken place already, so we use their
1799 // drawing state. However, SurfaceFlinger's own transaction has not
1800 // happened yet, so we must use the current state layer list
1801 // (soon to become the drawing state list).
1802 //
1803 sp<const DisplayDevice> disp;
1804 uint32_t currentlayerStack = 0;
1805 for (size_t i=0; i<count; i++) {
1806 // NOTE: we rely on the fact that layers are sorted by
1807 // layerStack first (so we don't have to traverse the list
1808 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001809 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001810 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001811 if (i==0 || currentlayerStack != layerStack) {
1812 currentlayerStack = layerStack;
1813 // figure out if this layerstack is mirrored
1814 // (more than one display) if so, pick the default display,
1815 // if not, pick the only display it's on.
1816 disp.clear();
1817 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1818 sp<const DisplayDevice> hw(mDisplays[dpy]);
1819 if (hw->getLayerStack() == currentlayerStack) {
1820 if (disp == NULL) {
1821 disp = hw;
1822 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001823 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001824 break;
1825 }
1826 }
1827 }
1828 }
Chet Haase91d25932013-04-11 15:24:55 -07001829 if (disp == NULL) {
1830 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1831 // redraw after transform hint changes. See bug 8508397.
1832
1833 // could be null when this layer is using a layerStack
1834 // that is not visible on any display. Also can occur at
1835 // screen off/on times.
1836 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001837 }
Chet Haase91d25932013-04-11 15:24:55 -07001838 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001839 }
1840 }
1841
1842
Mathias Agopian3559b072012-08-15 13:46:03 -07001843 /*
1844 * Perform our own transaction if needed
1845 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001846
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001847 const LayerVector& layers(mDrawingState.layersSortedByZ);
1848 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001849 // layers have been added
1850 mVisibleRegionsDirty = true;
1851 }
1852
1853 // some layers might have been removed, so
1854 // we need to update the regions they're exposing.
1855 if (mLayersRemoved) {
1856 mLayersRemoved = false;
1857 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001858 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001859 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001860 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001861 if (currentLayers.indexOf(layer) < 0) {
1862 // this layer is not visible anymore
1863 // TODO: we could traverse the tree from front to back and
1864 // compute the actual visible region
1865 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001866 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001867 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001868 Region(Rect(s.active.w, s.active.h)));
1869 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001870 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001872 }
1873
1874 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001875
1876 updateCursorAsync();
1877}
1878
1879void SurfaceFlinger::updateCursorAsync()
1880{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001881 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1882 auto& displayDevice = mDisplays[displayId];
1883 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001884 continue;
1885 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886
1887 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1888 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001889 }
1890 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001891}
1892
1893void SurfaceFlinger::commitTransaction()
1894{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001895 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001896 // Notify removed layers now that they can't be drawn from
1897 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001898 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1899 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001900 mLayersPendingRemoval[i]->onRemoved();
1901 }
1902 mLayersPendingRemoval.clear();
1903 }
1904
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001905 // If this transaction is part of a window animation then the next frame
1906 // we composite should be considered an animation as well.
1907 mAnimCompositionPending = mAnimTransactionPending;
1908
Mathias Agopian4fec8732012-06-29 14:12:52 -07001909 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001910 mTransactionPending = false;
1911 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001912 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001913}
1914
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001915void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001916 const LayerVector& currentLayers, uint32_t layerStack,
1917 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918{
Mathias Agopian841cde52012-03-01 15:44:37 -08001919 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001921
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001922 Region aboveOpaqueLayers;
1923 Region aboveCoveredLayers;
1924 Region dirty;
1925
Mathias Agopian87baae12012-07-31 12:38:26 -07001926 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001927
1928 size_t i = currentLayers.size();
1929 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001930 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931
1932 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001933 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934
Jesse Hall01e29052013-02-19 16:13:35 -08001935 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001936 if (s.layerStack != layerStack)
1937 continue;
1938
Mathias Agopianab028732010-03-16 16:41:46 -07001939 /*
1940 * opaqueRegion: area of a surface that is fully opaque.
1941 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001942 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001943
1944 /*
1945 * visibleRegion: area of a surface that is visible on screen
1946 * and not fully transparent. This is essentially the layer's
1947 * footprint minus the opaque regions above it.
1948 * Areas covered by a translucent surface are considered visible.
1949 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001950 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001951
1952 /*
1953 * coveredRegion: area of a surface that is covered by all
1954 * visible regions above it (which includes the translucent areas).
1955 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001956 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001957
Jesse Halla8026d22012-09-25 13:25:04 -07001958 /*
1959 * transparentRegion: area of a surface that is hinted to be completely
1960 * transparent. This is only used to tell when the layer has no visible
1961 * non-transparent regions and can be removed from the layer list. It
1962 * does not affect the visibleRegion of this layer or any layers
1963 * beneath it. The hint may not be correct if apps don't respect the
1964 * SurfaceView restrictions (which, sadly, some don't).
1965 */
1966 Region transparentRegion;
1967
Mathias Agopianab028732010-03-16 16:41:46 -07001968
1969 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001970 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001971 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001972 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001974 if (!visibleRegion.isEmpty()) {
1975 // Remove the transparent area from the visible region
1976 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001977 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001978 if (tr.preserveRects()) {
1979 // transform the transparent region
1980 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001981 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001982 // transformation too complex, can't do the
1983 // transparent region optimization.
1984 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001985 }
Mathias Agopianab028732010-03-16 16:41:46 -07001986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987
Mathias Agopianab028732010-03-16 16:41:46 -07001988 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001989 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001991 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1992 // the opaque region is the layer's footprint
1993 opaqueRegion = visibleRegion;
1994 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001995 }
1996 }
1997
Mathias Agopianab028732010-03-16 16:41:46 -07001998 // Clip the covered region to the visible region
1999 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2000
2001 // Update aboveCoveredLayers for next (lower) layer
2002 aboveCoveredLayers.orSelf(visibleRegion);
2003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002004 // subtract the opaque region covered by the layers above us
2005 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006
2007 // compute this layer's dirty region
2008 if (layer->contentDirty) {
2009 // we need to invalidate the whole region
2010 dirty = visibleRegion;
2011 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002013 layer->contentDirty = false;
2014 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002015 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002016 * the exposed region consists of two components:
2017 * 1) what's VISIBLE now and was COVERED before
2018 * 2) what's EXPOSED now less what was EXPOSED before
2019 *
2020 * note that (1) is conservative, we start with the whole
2021 * visible region but only keep what used to be covered by
2022 * something -- which mean it may have been exposed.
2023 *
2024 * (2) handles areas that were not covered by anything but got
2025 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002026 */
Mathias Agopianab028732010-03-16 16:41:46 -07002027 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002028 const Region oldVisibleRegion = layer->visibleRegion;
2029 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002030 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2031 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002032 }
2033 dirty.subtractSelf(aboveOpaqueLayers);
2034
2035 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002036 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002037
Mathias Agopianab028732010-03-16 16:41:46 -07002038 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002040
Jesse Halla8026d22012-09-25 13:25:04 -07002041 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042 layer->setVisibleRegion(visibleRegion);
2043 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002044 layer->setVisibleNonTransparentRegion(
2045 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046 }
2047
Mathias Agopian87baae12012-07-31 12:38:26 -07002048 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049}
2050
Mathias Agopian87baae12012-07-31 12:38:26 -07002051void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2052 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002053 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002054 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2055 if (hw->getLayerStack() == layerStack) {
2056 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002057 }
2058 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002059}
2060
Dan Stoza6b9454d2014-11-07 16:00:59 -08002061bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 ALOGV("handlePageFlip");
2064
Brian Andersond6927fb2016-07-23 23:37:30 -07002065 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066
Mathias Agopian4fec8732012-06-29 14:12:52 -07002067 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002068 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002069 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002070
2071 // Store the set of layers that need updates. This set must not change as
2072 // buffers are being latched, as this could result in a deadlock.
2073 // Example: Two producers share the same command stream and:
2074 // 1.) Layer 0 is latched
2075 // 2.) Layer 0 gets a new frame
2076 // 2.) Layer 1 gets a new frame
2077 // 3.) Layer 1 is latched.
2078 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2079 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002080 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002081 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002082 if (layer->hasQueuedFrame()) {
2083 frameQueued = true;
2084 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002086 } else {
2087 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002088 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002089 } else {
2090 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002091 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002092 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002094 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002095 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002096 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002097 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002099
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002100 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002101
2102 // If we will need to wake up at some time in the future to deal with a
2103 // queued frame that shouldn't be displayed during this vsync period, wake
2104 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002106 signalLayerUpdate();
2107 }
2108
2109 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111}
2112
Mathias Agopianad456f92011-01-13 17:53:01 -08002113void SurfaceFlinger::invalidateHwcGeometry()
2114{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002116}
2117
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002118
Fabien Sanglard830b8472016-11-30 16:35:58 -08002119void SurfaceFlinger::doDisplayComposition(
2120 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002121 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122{
Dan Stoza71433162014-02-04 16:22:36 -08002123 // We only need to actually compose the display if:
2124 // 1) It is being handled by hardware composer, which may need this to
2125 // keep its virtual display state machine in sync, or
2126 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002127 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002128 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002130 return;
2131 }
2132
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 ALOGV("doDisplayComposition");
2134
Mathias Agopian87baae12012-07-31 12:38:26 -07002135 Region dirtyRegion(inDirtyRegion);
2136
Mathias Agopianb8a55602009-06-26 19:06:36 -07002137 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002138 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139
Fabien Sanglard830b8472016-11-30 16:35:58 -08002140 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002141 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002142 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2143 // takes a rectangle, we must make sure to update that whole
2144 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002145 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002146 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002147 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002148 // We need to redraw the rectangle that will be updated
2149 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002150 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002151 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002152 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002153 } else {
2154 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002155 dirtyRegion.set(displayDevice->bounds());
2156 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157 }
2158 }
2159
Fabien Sanglard830b8472016-11-30 16:35:58 -08002160 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002161
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002162 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002163 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002164
2165 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002166 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167}
2168
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169bool SurfaceFlinger::doComposeSurfaces(
2170 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002171{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002173
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002175
2176 mat4 oldColorMatrix;
2177 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2178 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2179 if (applyColorMatrix) {
2180 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2181 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2182 }
2183
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2185 if (hasClientComposition) {
2186 ALOGV("hasClientComposition");
2187
2188 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002189 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002191 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2192 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2193 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2194 }
2195 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002196 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002197
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002198 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2200 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002201 // when using overlays, we assume a fully transparent framebuffer
2202 // NOTE: we could reduce how much we need to clear, for instance
2203 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002204 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002205 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002207 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002208 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002210
2211 // we remove the scissor part
2212 // we're left with the letterbox region
2213 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002215
2216 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002218
2219 // but limit it to the dirty region
2220 region.andSelf(dirty);
2221
Mathias Agopianb9494d52012-04-18 02:28:45 -07002222 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002223 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002224 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002226 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002227 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002228
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002230 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002231 // scissor on the main display. It should never be needed
2232 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 const Rect& bounds(displayDevice->getBounds());
2234 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002235 if (scissor != bounds) {
2236 // scissor doesn't match the screen's dimensions, so we
2237 // need to clear everything outside of it and enable
2238 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002239
Mathias Agopianf45c5102012-10-24 16:29:17 -07002240 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 const uint32_t height = displayDevice->getHeight();
2242 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002243 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002244 }
2245 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002246 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002247
Mathias Agopian85d751c2012-08-29 16:59:24 -07002248 /*
2249 * and then, render the layers targeted at the framebuffer
2250 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002251
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 ALOGV("Rendering client layers");
2253 const Transform& displayTransform = displayDevice->getTransform();
2254 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002255 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002256 bool firstLayer = true;
2257 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2258 const Region clip(dirty.intersect(
2259 displayTransform.transform(layer->visibleRegion)));
2260 ALOGV("Layer: %s", layer->getName().string());
2261 ALOGV(" Composition type: %s",
2262 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002263 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264 switch (layer->getCompositionType(hwcId)) {
2265 case HWC2::Composition::Cursor:
2266 case HWC2::Composition::Device:
2267 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002268 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2270 layer->isOpaque(state) && (state.alpha == 1.0f)
2271 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002272 // never clear the very first layer since we're
2273 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002274 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002275 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002276 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 case HWC2::Composition::Client: {
2279 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002280 break;
2281 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002282 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002283 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002284 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002285 } else {
2286 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002287 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002289 }
2290 } else {
2291 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002292 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002293 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002295 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002297 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002298 }
2299 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002300
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002301 if (applyColorMatrix) {
2302 getRenderEngine().setupColorTransform(oldColorMatrix);
2303 }
2304
Mathias Agopianf45c5102012-10-24 16:29:17 -07002305 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002306 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002307 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308}
2309
Fabien Sanglard830b8472016-11-30 16:35:58 -08002310void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2311 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002312 RenderEngine& engine(getRenderEngine());
2313 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314}
2315
Dan Stoza7d89d062015-04-30 13:29:25 -07002316status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002317 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002318 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002319 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002320{
Dan Stoza7d89d062015-04-30 13:29:25 -07002321 // add this layer to the current state list
2322 {
2323 Mutex::Autolock _l(mStateLock);
2324 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2325 return NO_MEMORY;
2326 }
2327 mCurrentState.layersSortedByZ.add(lbc);
2328 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2329 }
2330
Mathias Agopian96f08192010-06-02 23:28:45 -07002331 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002332 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002333
Dan Stoza7d89d062015-04-30 13:29:25 -07002334 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002335}
2336
Dan Stoza22851c32016-08-09 13:21:03 -07002337status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002339 sp<Layer> layer = weakLayer.promote();
2340 if (layer == nullptr) {
2341 // The layer has already been removed, carry on
2342 return NO_ERROR;
2343 }
2344
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002345 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2346 if (index >= 0) {
2347 mLayersPendingRemoval.push(layer);
2348 mLayersRemoved = true;
2349 setTransactionFlags(eTransactionNeeded);
2350 return NO_ERROR;
2351 }
2352 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353}
2354
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002355uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002356 return android_atomic_release_load(&mTransactionFlags);
2357}
2358
Mathias Agopian3f844832013-08-07 21:24:32 -07002359uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2361}
2362
Mathias Agopian3f844832013-08-07 21:24:32 -07002363uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2365 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002366 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367 }
2368 return old;
2369}
2370
Mathias Agopian8b33f032012-07-24 20:43:54 -07002371void SurfaceFlinger::setTransactionState(
2372 const Vector<ComposerState>& state,
2373 const Vector<DisplayState>& displays,
2374 uint32_t flags)
2375{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002376 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002377 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002378 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002379
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002380 if (flags & eAnimation) {
2381 // For window updates that are part of an animation we must wait for
2382 // previous animation "frames" to be handled.
2383 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002384 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002385 if (CC_UNLIKELY(err != NO_ERROR)) {
2386 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002387 // caller after a few seconds.
2388 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2389 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002390 mAnimTransactionPending = false;
2391 break;
2392 }
2393 }
2394 }
2395
Mathias Agopiane57f2922012-08-09 16:29:12 -07002396 size_t count = displays.size();
2397 for (size_t i=0 ; i<count ; i++) {
2398 const DisplayState& s(displays[i]);
2399 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002400 }
2401
Mathias Agopiane57f2922012-08-09 16:29:12 -07002402 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002403 for (size_t i=0 ; i<count ; i++) {
2404 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002405 // Here we need to check that the interface we're given is indeed
2406 // one of our own. A malicious client could give us a NULL
2407 // IInterface, or one of its own or even one of our own but a
2408 // different type. All these situations would cause us to crash.
2409 //
2410 // NOTE: it would be better to use RTTI as we could directly check
2411 // that we have a Client*. however, RTTI is disabled in Android.
2412 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002413 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002414 if (binder != NULL) {
2415 String16 desc(binder->getInterfaceDescriptor());
2416 if (desc == ISurfaceComposerClient::descriptor) {
2417 sp<Client> client( static_cast<Client *>(s.client.get()) );
2418 transactionFlags |= setClientStateLocked(client, s.state);
2419 }
2420 }
2421 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002422 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002423
Robert Carr2a7dbb42016-05-24 11:41:28 -07002424 // If a synchronous transaction is explicitly requested without any changes,
2425 // force a transaction anyway. This can be used as a flush mechanism for
2426 // previous async transactions.
2427 if (transactionFlags == 0 && (flags & eSynchronous)) {
2428 transactionFlags = eTransactionNeeded;
2429 }
2430
Mathias Agopian386aa982011-11-07 21:58:03 -08002431 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002432 if (mInterceptor.isEnabled()) {
2433 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2434 }
Irvel468051e2016-06-13 16:44:44 -07002435
Mathias Agopian386aa982011-11-07 21:58:03 -08002436 // this triggers the transaction
2437 setTransactionFlags(transactionFlags);
2438
2439 // if this is a synchronous transaction, wait for it to take effect
2440 // before returning.
2441 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002442 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002443 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002444 if (flags & eAnimation) {
2445 mAnimTransactionPending = true;
2446 }
2447 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002448 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2449 if (CC_UNLIKELY(err != NO_ERROR)) {
2450 // just in case something goes wrong in SF, return to the
2451 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002452 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2453 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002454 break;
2455 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 }
2458}
2459
Mathias Agopiane57f2922012-08-09 16:29:12 -07002460uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2461{
Jesse Hall9a143922012-10-04 16:29:19 -07002462 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2463 if (dpyIdx < 0)
2464 return 0;
2465
Mathias Agopiane57f2922012-08-09 16:29:12 -07002466 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002467 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002468 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 const uint32_t what = s.what;
2470 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002471 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002472 disp.surface = s.surface;
2473 flags |= eDisplayTransactionNeeded;
2474 }
2475 }
2476 if (what & DisplayState::eLayerStackChanged) {
2477 if (disp.layerStack != s.layerStack) {
2478 disp.layerStack = s.layerStack;
2479 flags |= eDisplayTransactionNeeded;
2480 }
2481 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002482 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002483 if (disp.orientation != s.orientation) {
2484 disp.orientation = s.orientation;
2485 flags |= eDisplayTransactionNeeded;
2486 }
2487 if (disp.frame != s.frame) {
2488 disp.frame = s.frame;
2489 flags |= eDisplayTransactionNeeded;
2490 }
2491 if (disp.viewport != s.viewport) {
2492 disp.viewport = s.viewport;
2493 flags |= eDisplayTransactionNeeded;
2494 }
2495 }
Michael Lentine47e45402014-07-18 15:34:25 -07002496 if (what & DisplayState::eDisplaySizeChanged) {
2497 if (disp.width != s.width) {
2498 disp.width = s.width;
2499 flags |= eDisplayTransactionNeeded;
2500 }
2501 if (disp.height != s.height) {
2502 disp.height = s.height;
2503 flags |= eDisplayTransactionNeeded;
2504 }
2505 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002506 }
2507 return flags;
2508}
2509
2510uint32_t SurfaceFlinger::setClientStateLocked(
2511 const sp<Client>& client,
2512 const layer_state_t& s)
2513{
2514 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002515 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002516 if (layer != 0) {
2517 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002518 bool geometryAppliesWithResize =
2519 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002520 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002521 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002523 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002524 }
2525 if (what & layer_state_t::eLayerChanged) {
2526 // NOTE: index needs to be calculated before we update the state
2527 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002528 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002529 mCurrentState.layersSortedByZ.removeAt(idx);
2530 mCurrentState.layersSortedByZ.add(layer);
2531 // we need traversal (state changed)
2532 // AND transaction (list changed)
2533 flags |= eTransactionNeeded|eTraversalNeeded;
2534 }
2535 }
2536 if (what & layer_state_t::eSizeChanged) {
2537 if (layer->setSize(s.w, s.h)) {
2538 flags |= eTraversalNeeded;
2539 }
2540 }
2541 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002543 flags |= eTraversalNeeded;
2544 }
2545 if (what & layer_state_t::eMatrixChanged) {
2546 if (layer->setMatrix(s.matrix))
2547 flags |= eTraversalNeeded;
2548 }
2549 if (what & layer_state_t::eTransparentRegionChanged) {
2550 if (layer->setTransparentRegionHint(s.transparentRegion))
2551 flags |= eTraversalNeeded;
2552 }
Dan Stoza23116082015-06-18 14:58:39 -07002553 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002554 if (layer->setFlags(s.flags, s.mask))
2555 flags |= eTraversalNeeded;
2556 }
2557 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002558 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002559 flags |= eTraversalNeeded;
2560 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002561 if (what & layer_state_t::eFinalCropChanged) {
2562 if (layer->setFinalCrop(s.finalCrop))
2563 flags |= eTraversalNeeded;
2564 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002565 if (what & layer_state_t::eLayerStackChanged) {
2566 // NOTE: index needs to be calculated before we update the state
2567 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002568 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002569 mCurrentState.layersSortedByZ.removeAt(idx);
2570 mCurrentState.layersSortedByZ.add(layer);
2571 // we need traversal (state changed)
2572 // AND transaction (list changed)
2573 flags |= eTransactionNeeded|eTraversalNeeded;
2574 }
2575 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002576 if (what & layer_state_t::eDeferTransaction) {
2577 layer->deferTransactionUntil(s.handle, s.frameNumber);
2578 // We don't trigger a traversal here because if no other state is
2579 // changed, we don't want this to cause any more work
2580 }
Robert Carrc3574f72016-03-24 12:19:32 -07002581 if (what & layer_state_t::eOverrideScalingModeChanged) {
2582 layer->setOverrideScalingMode(s.overrideScalingMode);
2583 // We don't trigger a traversal here because if no other state is
2584 // changed, we don't want this to cause any more work
2585 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002586 }
2587 return flags;
2588}
2589
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002590status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002591 const String8& name,
2592 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002593 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002596 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002597 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002598 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002599 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002600 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002601
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002602 status_t result = NO_ERROR;
2603
2604 sp<Layer> layer;
2605
Mathias Agopian3165cc22012-08-08 19:42:09 -07002606 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2607 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002608 result = createNormalLayer(client,
2609 name, w, h, flags, format,
2610 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002612 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002613 result = createDimLayer(client,
2614 name, w, h, flags,
2615 handle, gbp, &layer);
2616 break;
2617 default:
2618 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 break;
2620 }
2621
Dan Stoza7d89d062015-04-30 13:29:25 -07002622 if (result != NO_ERROR) {
2623 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002625
2626 result = addClientLayer(client, *handle, *gbp, layer);
2627 if (result != NO_ERROR) {
2628 return result;
2629 }
Irvelffc9efc2016-07-27 15:16:37 -07002630 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002631
2632 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002633 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634}
2635
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002636status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2637 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2638 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639{
2640 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002641 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 case PIXEL_FORMAT_TRANSPARENT:
2643 case PIXEL_FORMAT_TRANSLUCENT:
2644 format = PIXEL_FORMAT_RGBA_8888;
2645 break;
2646 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002647 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 break;
2649 }
2650
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002651 *outLayer = new Layer(this, client, name, w, h, flags);
2652 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2653 if (err == NO_ERROR) {
2654 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002655 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002657
2658 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2659 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660}
2661
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002662status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2663 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2664 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002666 *outLayer = new LayerDim(this, client, name, w, h, flags);
2667 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002668 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002669 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002670}
2671
Mathias Agopianac9fa422013-02-11 16:40:36 -08002672status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673{
Mathias Agopian67106042013-03-14 19:18:13 -07002674 // called by the window manager when it wants to remove a Layer
2675 status_t err = NO_ERROR;
2676 sp<Layer> l(client->getLayerUser(handle));
2677 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002678 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002679 err = removeLayer(l);
2680 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2681 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002682 }
2683 return err;
2684}
2685
Mathias Agopian13127d82013-03-05 17:47:11 -08002686status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002687{
Mathias Agopian67106042013-03-14 19:18:13 -07002688 // called by ~LayerCleaner() when all references to the IBinder (handle)
2689 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002690 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691}
2692
Mathias Agopianb60314a2012-04-10 22:09:54 -07002693// ---------------------------------------------------------------------------
2694
Andy McFadden13a082e2012-08-24 10:16:42 -07002695void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002696 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002697 Vector<ComposerState> state;
2698 Vector<DisplayState> displays;
2699 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002700 d.what = DisplayState::eDisplayProjectionChanged |
2701 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002702 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002703 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002704 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002705 d.frame.makeInvalid();
2706 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002707 d.width = 0;
2708 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002709 displays.add(d);
2710 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002711 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002712
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2714 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002715 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002716}
2717
2718void SurfaceFlinger::initializeDisplays() {
2719 class MessageScreenInitialized : public MessageBase {
2720 SurfaceFlinger* flinger;
2721 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002722 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002723 virtual bool handler() {
2724 flinger->onInitializeDisplays();
2725 return true;
2726 }
2727 };
2728 sp<MessageBase> msg = new MessageScreenInitialized(this);
2729 postMessageAsync(msg); // we may be called from main thread, use async message
2730}
2731
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002732void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2733 int mode) {
2734 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2735 this);
2736 int32_t type = hw->getDisplayType();
2737 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002738
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002739 if (mode == currentMode) {
2740 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002741 return;
2742 }
2743
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002744 hw->setPowerMode(mode);
2745 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2746 ALOGW("Trying to set power mode for virtual display");
2747 return;
2748 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002749
Irvelffc9efc2016-07-27 15:16:37 -07002750 if (mInterceptor.isEnabled()) {
2751 Mutex::Autolock _l(mStateLock);
2752 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2753 if (idx < 0) {
2754 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2755 return;
2756 }
2757 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2758 }
2759
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002760 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002761 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002762 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002763 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2764 // FIXME: eventthread only knows about the main display right now
2765 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002766 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002767 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002769 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002770 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002771 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002772
2773 struct sched_param param = {0};
2774 param.sched_priority = 1;
2775 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2776 ALOGW("Couldn't set SCHED_FIFO on display on");
2777 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002778 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002779 // Turn off the display
2780 struct sched_param param = {0};
2781 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2782 ALOGW("Couldn't set SCHED_OTHER on display off");
2783 }
2784
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002785 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002786 disableHardwareVsync(true); // also cancels any in-progress resync
2787
Mathias Agopiancde87a32012-09-13 14:09:01 -07002788 // FIXME: eventthread only knows about the main display right now
2789 mEventThread->onScreenReleased();
2790 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002791
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002792 getHwComposer().setPowerMode(type, mode);
2793 mVisibleRegionsDirty = true;
2794 // from this point on, SF will stop drawing on this display
2795 } else {
2796 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002797 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002798}
2799
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002800void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2801 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002802 SurfaceFlinger& mFlinger;
2803 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002804 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002805 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002806 MessageSetPowerMode(SurfaceFlinger& flinger,
2807 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2808 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002809 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002810 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002811 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002812 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002813 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002814 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002815 ALOGW("Attempt to set power mode = %d for virtual display",
2816 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002817 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002818 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002819 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002820 return true;
2821 }
2822 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002823 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002824 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002825}
2826
2827// ---------------------------------------------------------------------------
2828
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2830{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002832
Mathias Agopianbd115332013-04-18 16:41:04 -07002833 IPCThreadState* ipc = IPCThreadState::self();
2834 const int pid = ipc->getCallingPid();
2835 const int uid = ipc->getCallingUid();
2836 if ((uid != AID_SHELL) &&
2837 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002838 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002839 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002841 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002842 // (this would indicate SF is stuck, but we want to be able to
2843 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002844 status_t err = mStateLock.timedLock(s2ns(1));
2845 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002846 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002847 result.appendFormat(
2848 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2849 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002850 }
2851
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002852 bool dumpAll = true;
2853 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002854 size_t numArgs = args.size();
2855 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002856 if ((index < numArgs) &&
2857 (args[index] == String16("--list"))) {
2858 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002859 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002860 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002861 }
2862
2863 if ((index < numArgs) &&
2864 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002865 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002866 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002867 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002868 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002869
2870 if ((index < numArgs) &&
2871 (args[index] == String16("--latency-clear"))) {
2872 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002873 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002874 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002875 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002876
2877 if ((index < numArgs) &&
2878 (args[index] == String16("--dispsync"))) {
2879 index++;
2880 mPrimaryDispSync.dump(result);
2881 dumpAll = false;
2882 }
Dan Stozab90cf072015-03-05 11:05:59 -08002883
2884 if ((index < numArgs) &&
2885 (args[index] == String16("--static-screen"))) {
2886 index++;
2887 dumpStaticScreenStats(result);
2888 dumpAll = false;
2889 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002890
2891 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002892 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002893 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002894 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002895 dumpAll = false;
2896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002898
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002899 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002900 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002901 }
2902
Mathias Agopian9795c422009-08-26 16:36:26 -07002903 if (locked) {
2904 mStateLock.unlock();
2905 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 }
2907 write(fd, result.string(), result.size());
2908 return NO_ERROR;
2909}
2910
Dan Stozac7014012014-02-14 15:03:43 -08002911void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2912 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002913{
2914 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2915 const size_t count = currentLayers.size();
2916 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002917 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002918 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002919 }
2920}
2921
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002922void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002923 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002924{
2925 String8 name;
2926 if (index < args.size()) {
2927 name = String8(args[index]);
2928 index++;
2929 }
2930
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2932 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002933 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002934
2935 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002936 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002937 } else {
2938 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2939 const size_t count = currentLayers.size();
2940 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002941 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002942 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002943 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002944 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002945 }
2946 }
2947}
2948
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002949void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002950 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002951{
2952 String8 name;
2953 if (index < args.size()) {
2954 name = String8(args[index]);
2955 index++;
2956 }
2957
2958 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2959 const size_t count = currentLayers.size();
2960 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002961 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002962 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002963 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002964 }
2965 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002966
Svetoslavd85084b2014-03-20 10:28:31 -07002967 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002968}
2969
Jamie Gennis6547ff42013-07-16 20:12:42 -07002970// This should only be called from the main thread. Otherwise it would need
2971// the lock and should use mCurrentState rather than mDrawingState.
2972void SurfaceFlinger::logFrameStats() {
2973 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2974 const size_t count = drawingLayers.size();
2975 for (size_t i=0 ; i<count ; i++) {
2976 const sp<Layer>& layer(drawingLayers[i]);
2977 layer->logFrameStats();
2978 }
2979
2980 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2981}
2982
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002983void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07002984{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002985 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07002986#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002987 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07002988#endif
2989#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002990 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07002991#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002992 if (isLayerTripleBufferingDisabled())
2993 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002994 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07002995}
2996
Dan Stozab90cf072015-03-05 11:05:59 -08002997void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2998{
2999 result.appendFormat("Static screen stats:\n");
3000 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3001 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3002 float percent = 100.0f *
3003 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3004 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3005 b + 1, bucketTimeSec, percent);
3006 }
3007 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3008 float percent = 100.0f *
3009 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3010 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3011 NUM_BUCKETS - 1, bucketTimeSec, percent);
3012}
3013
Dan Stozae77c7662016-05-13 11:37:28 -07003014void SurfaceFlinger::recordBufferingStats(const char* layerName,
3015 std::vector<OccupancyTracker::Segment>&& history) {
3016 Mutex::Autolock lock(mBufferingStatsMutex);
3017 auto& stats = mBufferingStats[layerName];
3018 for (const auto& segment : history) {
3019 if (!segment.usedThirdBuffer) {
3020 stats.twoBufferTime += segment.totalTime;
3021 }
3022 if (segment.occupancyAverage < 1.0f) {
3023 stats.doubleBufferedTime += segment.totalTime;
3024 } else if (segment.occupancyAverage < 2.0f) {
3025 stats.tripleBufferedTime += segment.totalTime;
3026 }
3027 ++stats.numSegments;
3028 stats.totalTime += segment.totalTime;
3029 }
3030}
3031
Brian Andersond6927fb2016-07-23 23:37:30 -07003032void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3033 result.appendFormat("Layer frame timestamps:\n");
3034
3035 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3036 const size_t count = currentLayers.size();
3037 for (size_t i=0 ; i<count ; i++) {
3038 currentLayers[i]->dumpFrameEvents(result);
3039 }
3040}
3041
Dan Stozae77c7662016-05-13 11:37:28 -07003042void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3043 result.append("Buffering stats:\n");
3044 result.append(" [Layer name] <Active time> <Two buffer> "
3045 "<Double buffered> <Triple buffered>\n");
3046 Mutex::Autolock lock(mBufferingStatsMutex);
3047 typedef std::tuple<std::string, float, float, float> BufferTuple;
3048 std::map<float, BufferTuple, std::greater<float>> sorted;
3049 for (const auto& statsPair : mBufferingStats) {
3050 const char* name = statsPair.first.c_str();
3051 const BufferingStats& stats = statsPair.second;
3052 if (stats.numSegments == 0) {
3053 continue;
3054 }
3055 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3056 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3057 stats.totalTime;
3058 float doubleBufferRatio = static_cast<float>(
3059 stats.doubleBufferedTime) / stats.totalTime;
3060 float tripleBufferRatio = static_cast<float>(
3061 stats.tripleBufferedTime) / stats.totalTime;
3062 sorted.insert({activeTime, {name, twoBufferRatio,
3063 doubleBufferRatio, tripleBufferRatio}});
3064 }
3065 for (const auto& sortedPair : sorted) {
3066 float activeTime = sortedPair.first;
3067 const BufferTuple& values = sortedPair.second;
3068 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3069 std::get<0>(values).c_str(), activeTime,
3070 std::get<1>(values), std::get<2>(values),
3071 std::get<3>(values));
3072 }
3073 result.append("\n");
3074}
3075
3076
Mathias Agopian74d211a2013-04-22 16:55:35 +02003077void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3078 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003079{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003080 bool colorize = false;
3081 if (index < args.size()
3082 && (args[index] == String16("--color"))) {
3083 colorize = true;
3084 index++;
3085 }
3086
3087 Colorizer colorizer(colorize);
3088
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003089 // figure out if we're stuck somewhere
3090 const nsecs_t now = systemTime();
3091 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3092 const nsecs_t inTransaction(mDebugInTransaction);
3093 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3094 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3095
3096 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003097 * Dump library configuration.
3098 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003099
3100 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003101 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003102 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003103 appendSfConfigString(result);
3104 appendUiConfigString(result);
3105 appendGuiConfigString(result);
3106 result.append("\n");
3107
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003108 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003109 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003110 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003111 result.append(SyncFeatures::getInstance().toString());
3112 result.append("\n");
3113
Dan Stoza9e56aa02015-11-02 13:00:03 -08003114 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3115
Andy McFadden41d67d72014-04-25 16:58:34 -07003116 colorizer.bold(result);
3117 result.append("DispSync configuration: ");
3118 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003119 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3120 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003121 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3122 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003123 result.append("\n");
3124
Dan Stozab90cf072015-03-05 11:05:59 -08003125 // Dump static screen stats
3126 result.append("\n");
3127 dumpStaticScreenStats(result);
3128 result.append("\n");
3129
Dan Stozae77c7662016-05-13 11:37:28 -07003130 dumpBufferingStats(result);
3131
Andy McFadden4803b742012-09-24 19:07:20 -07003132 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003133 * Dump the visible layer list
3134 */
3135 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3136 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003137 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003138 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003139 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003140 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003141 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003142 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003143 }
3144
3145 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003146 * Dump Display state
3147 */
3148
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003149 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003150 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003151 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003152 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3153 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003154 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003155 }
3156
3157 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003158 * Dump SurfaceFlinger global state
3159 */
3160
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003161 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003162 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003163 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003164
Mathias Agopian888c8222012-08-04 21:10:38 -07003165 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003166 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003167
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003168 colorizer.bold(result);
3169 result.appendFormat("EGL implementation : %s\n",
3170 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3171 colorizer.reset(result);
3172 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003173 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003174
Mathias Agopian875d8e12013-06-07 15:35:48 -07003175 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003176
Mathias Agopian42977342012-08-05 00:40:46 -07003177 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003178 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3179 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003180 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003181 " last eglSwapBuffers() time: %f us\n"
3182 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003183 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003184 " refresh-rate : %f fps\n"
3185 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003186 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003187 " gpu_to_cpu_unsupported : %d\n"
3188 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003189 mLastSwapBufferTime/1000.0,
3190 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003191 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003192 1e9 / activeConfig->getVsyncPeriod(),
3193 activeConfig->getDpiX(),
3194 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003195 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003196
Mathias Agopian74d211a2013-04-22 16:55:35 +02003197 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003198 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003199
Mathias Agopian74d211a2013-04-22 16:55:35 +02003200 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003201 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003202
3203 /*
3204 * VSYNC state
3205 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003206 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003207 result.append("\n");
3208
3209 /*
3210 * HWC layer minidump
3211 */
3212 for (size_t d = 0; d < mDisplays.size(); d++) {
3213 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3214 int32_t hwcId = displayDevice->getHwcDisplayId();
3215 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3216 continue;
3217 }
3218
3219 result.appendFormat("Display %d HWC layers:\n", hwcId);
3220 Layer::miniDumpHeader(result);
3221 for (size_t l = 0; l < count; l++) {
3222 const sp<Layer>& layer(currentLayers[l]);
3223 layer->miniDump(result, hwcId);
3224 }
3225 result.append("\n");
3226 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003227
3228 /*
3229 * Dump HWComposer state
3230 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003231 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003232 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003233 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003234 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003235 result.appendFormat(" h/w composer %s\n",
3236 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003237 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003238
3239 /*
3240 * Dump gralloc state
3241 */
3242 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3243 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003244}
3245
Mathias Agopian13127d82013-03-05 17:47:11 -08003246const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003247SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003248 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003249 wp<IBinder> dpy;
3250 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3251 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3252 dpy = mDisplays.keyAt(i);
3253 break;
3254 }
3255 }
3256 if (dpy == NULL) {
3257 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3258 // Just use the primary display so we have something to return
3259 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3260 }
3261 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003262}
3263
Keun young Park63f165f2012-08-31 10:53:36 -07003264bool SurfaceFlinger::startDdmConnection()
3265{
3266 void* libddmconnection_dso =
3267 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3268 if (!libddmconnection_dso) {
3269 return false;
3270 }
3271 void (*DdmConnection_start)(const char* name);
3272 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003273 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003274 if (!DdmConnection_start) {
3275 dlclose(libddmconnection_dso);
3276 return false;
3277 }
3278 (*DdmConnection_start)(getServiceName());
3279 return true;
3280}
3281
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003282status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 switch (code) {
3284 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003285 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003286 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003288 case CLEAR_ANIMATION_FRAME_STATS:
3289 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003290 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003291 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292 {
3293 // codes that require permission check
3294 IPCThreadState* ipc = IPCThreadState::self();
3295 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003296 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003297 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003298 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003299 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003300 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003302 break;
3303 }
3304 case CAPTURE_SCREEN:
3305 {
3306 // codes that require permission check
3307 IPCThreadState* ipc = IPCThreadState::self();
3308 const int pid = ipc->getCallingPid();
3309 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003310 if ((uid != AID_GRAPHICS) &&
3311 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003312 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003313 return PERMISSION_DENIED;
3314 }
3315 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 }
3317 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003318 return OK;
3319}
3320
3321status_t SurfaceFlinger::onTransact(
3322 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3323{
3324 status_t credentialCheck = CheckTransactCodeCredentials(code);
3325 if (credentialCheck != OK) {
3326 return credentialCheck;
3327 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3330 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003331 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003332 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003333 IPCThreadState* ipc = IPCThreadState::self();
3334 const int pid = ipc->getCallingPid();
3335 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003336 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003337 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338 return PERMISSION_DENIED;
3339 }
3340 int n;
3341 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003342 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003343 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 return NO_ERROR;
3345 case 1002: // SHOW_UPDATES
3346 n = data.readInt32();
3347 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003348 invalidateHwcGeometry();
3349 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003352 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003353 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003355 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356 setTransactionFlags(
3357 eTransactionNeeded|
3358 eDisplayTransactionNeeded|
3359 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003360 return NO_ERROR;
3361 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003362 case 1006:{ // send empty update
3363 signalRefresh();
3364 return NO_ERROR;
3365 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003366 case 1008: // toggle use of hw composer
3367 n = data.readInt32();
3368 mDebugDisableHWC = n ? 1 : 0;
3369 invalidateHwcGeometry();
3370 repaintEverything();
3371 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003372 case 1009: // toggle use of transform hint
3373 n = data.readInt32();
3374 mDebugDisableTransformHint = n ? 1 : 0;
3375 invalidateHwcGeometry();
3376 repaintEverything();
3377 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003378 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003379 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380 reply->writeInt32(0);
3381 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003382 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003383 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 return NO_ERROR;
3385 case 1013: {
3386 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003387 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3388 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003389 return NO_ERROR;
3390 }
3391 case 1014: {
3392 // daltonize
3393 n = data.readInt32();
3394 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003395 case 1:
3396 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3397 break;
3398 case 2:
3399 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3400 break;
3401 case 3:
3402 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3403 break;
3404 default:
3405 mDaltonizer.setType(ColorBlindnessType::None);
3406 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003407 }
3408 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003409 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003410 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003411 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003412 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003413 invalidateHwcGeometry();
3414 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003415 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003416 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003417 case 1015: {
3418 // apply a color matrix
3419 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003420 if (n) {
3421 // color matrix is sent as mat3 matrix followed by vec3
3422 // offset, then packed into a mat4 where the last row is
3423 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003424 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003425 for (size_t j = 0; j < 4; j++) {
3426 mColorMatrix[i][j] = data.readFloat();
3427 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003428 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003429 } else {
3430 mColorMatrix = mat4();
3431 }
3432 invalidateHwcGeometry();
3433 repaintEverything();
3434 return NO_ERROR;
3435 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003436 // This is an experimental interface
3437 // Needs to be shifted to proper binder interface when we productize
3438 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003439 n = data.readInt32();
3440 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003441 return NO_ERROR;
3442 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003443 case 1017: {
3444 n = data.readInt32();
3445 mForceFullDamage = static_cast<bool>(n);
3446 return NO_ERROR;
3447 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003448 case 1018: { // Modify Choreographer's phase offset
3449 n = data.readInt32();
3450 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3451 return NO_ERROR;
3452 }
3453 case 1019: { // Modify SurfaceFlinger's phase offset
3454 n = data.readInt32();
3455 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3456 return NO_ERROR;
3457 }
Irvel468051e2016-06-13 16:44:44 -07003458 case 1020: { // Layer updates interceptor
3459 n = data.readInt32();
3460 if (n) {
3461 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003462 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003463 }
3464 else{
3465 ALOGV("Interceptor disabled");
3466 mInterceptor.disable();
3467 }
3468 return NO_ERROR;
3469 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003470 case 1021: { // Disable HWC virtual displays
3471 n = data.readInt32();
3472 mUseHwcVirtualDisplays = !n;
3473 return NO_ERROR;
3474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475 }
3476 }
3477 return err;
3478}
3479
Mathias Agopian53331da2011-08-22 21:44:41 -07003480void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003481 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003482 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003483}
3484
Mathias Agopian59119e62010-10-11 12:37:43 -07003485// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003486// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003487// ---------------------------------------------------------------------------
3488
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003489/* The code below is here to handle b/8734824
3490 *
3491 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003492 * from the surfaceflinger thread to the calling binder thread, where they
3493 * are executed. This allows the calling thread in the calling process to be
3494 * reused and not depend on having "enough" binder threads to handle the
3495 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003496 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003497class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003498 /* Parts of GraphicProducerWrapper are run on two different threads,
3499 * communicating by sending messages via Looper but also by shared member
3500 * data. Coherence maintenance is subtle and in places implicit (ugh).
3501 *
3502 * Don't rely on Looper's sendMessage/handleMessage providing
3503 * release/acquire semantics for any data not actually in the Message.
3504 * Data going from surfaceflinger to binder threads needs to be
3505 * synchronized explicitly.
3506 *
3507 * Barrier open/wait do provide release/acquire semantics. This provides
3508 * implicit synchronization for data coming back from binder to
3509 * surfaceflinger threads.
3510 */
3511
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003512 sp<IGraphicBufferProducer> impl;
3513 sp<Looper> looper;
3514 status_t result;
3515 bool exitPending;
3516 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003517 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003518 uint32_t code;
3519 Parcel const* data;
3520 Parcel* reply;
3521
3522 enum {
3523 MSG_API_CALL,
3524 MSG_EXIT
3525 };
3526
3527 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003528 * Called on surfaceflinger thread. This is called by our "fake"
3529 * BpGraphicBufferProducer. We package the data and reply Parcel and
3530 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003531 */
3532 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003533 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003534 this->code = code;
3535 this->data = &data;
3536 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003537 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003538 // if we've exited, we run the message synchronously right here.
3539 // note (JH): as far as I can tell from looking at the code, this
3540 // never actually happens. if it does, i'm not sure if it happens
3541 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003542 handleMessage(Message(MSG_API_CALL));
3543 } else {
3544 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003545 // Prevent stores to this->{code, data, reply} from being
3546 // reordered later than the construction of Message.
3547 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003548 looper->sendMessage(this, Message(MSG_API_CALL));
3549 barrier.wait();
3550 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003551 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003552 }
3553
3554 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003555 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003556 * call the real BpGraphicBufferProducer.
3557 */
3558 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003559 int what = message.what;
3560 // Prevent reads below from happening before the read from Message
3561 atomic_thread_fence(memory_order_acquire);
3562 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003563 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003564 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003565 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003566 exitRequested = true;
3567 }
3568 }
3569
3570public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003571 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003572 : impl(impl),
3573 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003574 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003575 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003576 exitRequested(false),
3577 code(0),
3578 data(NULL),
3579 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003580 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003581
Jesse Hallb154c422014-07-13 12:47:02 -07003582 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003583 status_t waitForResponse() {
3584 do {
3585 looper->pollOnce(-1);
3586 } while (!exitRequested);
3587 return result;
3588 }
3589
Jesse Hallb154c422014-07-13 12:47:02 -07003590 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003591 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003592 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003593 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003594 // Ensure this->result is visible to the binder thread before it
3595 // handles the message.
3596 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003597 looper->sendMessage(this, Message(MSG_EXIT));
3598 }
3599};
3600
3601
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003602status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3603 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003604 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003605 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003606 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003607
3608 if (CC_UNLIKELY(display == 0))
3609 return BAD_VALUE;
3610
3611 if (CC_UNLIKELY(producer == 0))
3612 return BAD_VALUE;
3613
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003614 // if we have secure windows on this display, never allow the screen capture
3615 // unless the producer interface is local (i.e.: we can take a screenshot for
3616 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003617 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003618
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003619 // Convert to surfaceflinger's internal rotation type.
3620 Transform::orientation_flags rotationFlags;
3621 switch (rotation) {
3622 case ISurfaceComposer::eRotateNone:
3623 rotationFlags = Transform::ROT_0;
3624 break;
3625 case ISurfaceComposer::eRotate90:
3626 rotationFlags = Transform::ROT_90;
3627 break;
3628 case ISurfaceComposer::eRotate180:
3629 rotationFlags = Transform::ROT_180;
3630 break;
3631 case ISurfaceComposer::eRotate270:
3632 rotationFlags = Transform::ROT_270;
3633 break;
3634 default:
3635 rotationFlags = Transform::ROT_0;
3636 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3637 break;
3638 }
3639
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003640 class MessageCaptureScreen : public MessageBase {
3641 SurfaceFlinger* flinger;
3642 sp<IBinder> display;
3643 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003644 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003645 uint32_t reqWidth, reqHeight;
3646 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003647 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003648 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003649 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003650 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003651 public:
3652 MessageCaptureScreen(SurfaceFlinger* flinger,
3653 const sp<IBinder>& display,
3654 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003655 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003656 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003657 bool useIdentityTransform,
3658 Transform::orientation_flags rotation,
3659 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003660 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003661 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003662 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003663 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003664 rotation(rotation), result(PERMISSION_DENIED),
3665 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003666 {
3667 }
3668 status_t getResult() const {
3669 return result;
3670 }
3671 virtual bool handler() {
3672 Mutex::Autolock _l(flinger->mStateLock);
3673 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003674 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003675 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003676 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003677 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003678 return true;
3679 }
3680 };
3681
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003682 // this creates a "fake" BBinder which will serve as a "fake" remote
3683 // binder to receive the marshaled calls and forward them to the
3684 // real remote (a BpGraphicBufferProducer)
3685 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3686
3687 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3688 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003689 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003690 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003691 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003692 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003693
3694 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003695 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003696 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003697 }
3698 return res;
3699}
3700
Mathias Agopian180f10d2013-04-10 22:55:41 -07003701
3702void SurfaceFlinger::renderScreenImplLocked(
3703 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003704 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003705 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003706 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003707{
3708 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003709 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003710
3711 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003712 const int32_t hw_w = hw->getWidth();
3713 const int32_t hw_h = hw->getHeight();
3714 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003715 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003716
Dan Stozac1879002014-05-22 15:59:05 -07003717 // if a default or invalid sourceCrop is passed in, set reasonable values
3718 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3719 !sourceCrop.isValid()) {
3720 sourceCrop.setLeftTop(Point(0, 0));
3721 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3722 }
3723
3724 // ensure that sourceCrop is inside screen
3725 if (sourceCrop.left < 0) {
3726 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3727 }
Dan Stozabe31f442014-06-11 11:20:54 -07003728 if (sourceCrop.right > hw_w) {
3729 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003730 }
3731 if (sourceCrop.top < 0) {
3732 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3733 }
Dan Stozabe31f442014-06-11 11:20:54 -07003734 if (sourceCrop.bottom > hw_h) {
3735 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003736 }
3737
Mathias Agopian180f10d2013-04-10 22:55:41 -07003738 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003739 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003740
3741 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003742 engine.setViewportAndProjection(
3743 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003744 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003745
3746 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003747 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003748
3749 const LayerVector& layers( mDrawingState.layersSortedByZ );
3750 const size_t count = layers.size();
3751 for (size_t i=0 ; i<count ; ++i) {
3752 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003753 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003754 if (state.layerStack == hw->getLayerStack()) {
3755 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3756 if (layer->isVisible()) {
3757 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003758 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003759 if (filtering) layer->setFiltering(false);
3760 }
3761 }
3762 }
3763 }
3764
Mathias Agopian931bda12013-08-28 18:11:46 -07003765 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003766}
3767
3768
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003769status_t SurfaceFlinger::captureScreenImplLocked(
3770 const sp<const DisplayDevice>& hw,
3771 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003772 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003773 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003774 bool useIdentityTransform, Transform::orientation_flags rotation,
3775 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003776{
3777 ATRACE_CALL();
3778
Mathias Agopian180f10d2013-04-10 22:55:41 -07003779 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003780 uint32_t hw_w = hw->getWidth();
3781 uint32_t hw_h = hw->getHeight();
3782
3783 if (rotation & Transform::ROT_90) {
3784 std::swap(hw_w, hw_h);
3785 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003786
Mathias Agopian180f10d2013-04-10 22:55:41 -07003787 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3788 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3789 reqWidth, reqHeight, hw_w, hw_h);
3790 return BAD_VALUE;
3791 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003792
Mathias Agopian180f10d2013-04-10 22:55:41 -07003793 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3794 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3795
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003796 bool secureLayerIsVisible = false;
3797 const LayerVector& layers(mDrawingState.layersSortedByZ);
3798 const size_t count = layers.size();
3799 for (size_t i = 0 ; i < count ; ++i) {
3800 const sp<Layer>& layer(layers[i]);
3801 const Layer::State& state(layer->getDrawingState());
3802 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3803 state.z <= maxLayerZ && layer->isVisible() &&
3804 layer->isSecure()) {
3805 secureLayerIsVisible = true;
3806 }
3807 }
3808
3809 if (!isLocalScreenshot && secureLayerIsVisible) {
3810 ALOGW("FB is protected: PERMISSION_DENIED");
3811 return PERMISSION_DENIED;
3812 }
3813
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003814 // create a surface (because we're a producer, and we need to
3815 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003816 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003817
3818 // Put the screenshot Surface into async mode so that
3819 // Layer::headFenceHasSignaled will always return true and we'll latch the
3820 // first buffer regardless of whether or not its acquire fence has
3821 // signaled. This is needed to avoid a race condition in the rotation
3822 // animation. See b/30209608
3823 sur->setAsyncMode(true);
3824
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003825 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003826
Michael Lentine5a16a622015-05-21 13:48:24 -07003827 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3828 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003829 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3830 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003831
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003832 int err = 0;
3833 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003834 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003835 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3836 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003837
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003838 if (err == NO_ERROR) {
3839 ANativeWindowBuffer* buffer;
3840 /* TODO: Once we have the sync framework everywhere this can use
3841 * server-side waits on the fence that dequeueBuffer returns.
3842 */
3843 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3844 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003845 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003846 // create an EGLImage from the buffer so we can later
3847 // turn it into a texture
3848 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3849 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3850 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003851 // this binds the given EGLImage as a framebuffer for the
3852 // duration of this scope.
3853 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3854 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003855 // this will in fact render into our dequeued buffer
3856 // via an FBO, which means we didn't have to create
3857 // an EGLSurface and therefore we're not
3858 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003859 renderScreenImplLocked(
3860 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3861 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003862
Riley Andrews86639902014-08-15 12:27:24 -07003863 // Attempt to create a sync khr object that can produce a sync point. If that
3864 // isn't available, create a non-dupable sync object in the fallback path and
3865 // wait on it directly.
3866 EGLSyncKHR sync;
3867 if (!DEBUG_SCREENSHOTS) {
3868 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003869 // native fence fd will not be populated until flush() is done.
3870 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003871 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003872 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003873 }
Riley Andrews86639902014-08-15 12:27:24 -07003874 if (sync != EGL_NO_SYNC_KHR) {
3875 // get the sync fd
3876 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3877 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3878 ALOGW("captureScreen: failed to dup sync khr object");
3879 syncFd = -1;
3880 }
3881 eglDestroySyncKHR(mEGLDisplay, sync);
3882 } else {
3883 // fallback path
3884 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3885 if (sync != EGL_NO_SYNC_KHR) {
3886 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3887 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3888 EGLint eglErr = eglGetError();
3889 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3890 ALOGW("captureScreen: fence wait timed out");
3891 } else {
3892 ALOGW_IF(eglErr != EGL_SUCCESS,
3893 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3894 }
3895 eglDestroySyncKHR(mEGLDisplay, sync);
3896 } else {
3897 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3898 }
3899 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003900 if (DEBUG_SCREENSHOTS) {
3901 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3902 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3903 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3904 hw, minLayerZ, maxLayerZ);
3905 delete [] pixels;
3906 }
3907
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003908 } else {
3909 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3910 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003911 window->cancelBuffer(window, buffer, syncFd);
3912 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003913 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003914 // destroy our image
3915 eglDestroyImageKHR(mEGLDisplay, image);
3916 } else {
3917 result = BAD_VALUE;
3918 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003919 if (buffer) {
3920 // queueBuffer takes ownership of syncFd
3921 result = window->queueBuffer(window, buffer, syncFd);
3922 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003923 }
3924 } else {
3925 result = BAD_VALUE;
3926 }
3927 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3928 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003929
Mathias Agopian74c40c02010-09-29 13:02:36 -07003930 return result;
3931}
3932
Mathias Agopiand5556842013-09-19 17:08:37 -07003933void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3934 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003935 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003936 for (size_t y=0 ; y<h ; y++) {
3937 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3938 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003939 if (p[x] != 0xFF000000) return;
3940 }
3941 }
3942 ALOGE("*** we just took a black screenshot ***\n"
3943 "requested minz=%d, maxz=%d, layerStack=%d",
3944 minLayerZ, maxLayerZ, hw->getLayerStack());
3945 const LayerVector& layers( mDrawingState.layersSortedByZ );
3946 const size_t count = layers.size();
3947 for (size_t i=0 ; i<count ; ++i) {
3948 const sp<Layer>& layer(layers[i]);
3949 const Layer::State& state(layer->getDrawingState());
3950 const bool visible = (state.layerStack == hw->getLayerStack())
3951 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3952 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003953 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003954 visible ? '+' : '-',
3955 i, layer->getName().string(), state.layerStack, state.z,
3956 layer->isVisible(), state.flags, state.alpha);
3957 }
3958 }
3959}
3960
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003961// ---------------------------------------------------------------------------
3962
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003963SurfaceFlinger::LayerVector::LayerVector() {
3964}
3965
3966SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003967 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003968}
3969
3970int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3971 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003972{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003973 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003974 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3975 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003976
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003977 uint32_t ls = l->getCurrentState().layerStack;
3978 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003979 if (ls != rs)
3980 return ls - rs;
3981
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003982 uint32_t lz = l->getCurrentState().z;
3983 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003984 if (lz != rz)
3985 return lz - rz;
3986
3987 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003988}
3989
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003991
3992
3993#if defined(__gl_h_)
3994#error "don't include gl/gl.h in this file"
3995#endif
3996
3997#if defined(__gl2_h_)
3998#error "don't include gl2/gl2.h in this file"
3999#endif