blob: 45d1477ff01ef100d331620f81848b52695433b4 [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
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096// This is the phase offset in nanoseconds of the software vsync event
97// relative to the vsync event reported by HWComposer. The software vsync
98// event is when SurfaceFlinger and Choreographer-based applications run each
99// frame.
100//
101// This phase offset allows adjustment of the minimum latency from application
102// wake-up (by Choregographer) time to the time at which the resulting window
103// image is displayed. This value may be either positive (after the HW vsync)
104// or negative (before the HW vsync). Setting it to 0 will result in a
105// minimum latency of two vsync periods because the app and SurfaceFlinger
106// will run just after the HW vsync. Setting it to a positive number will
107// result in the minimum latency being:
108//
109// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
110//
111// Note that reducing this latency makes it more likely for the applications
112// to not have their window content image ready in time. When this happens
113// the latency will end up being an additional vsync period, and animations
114// will hiccup. Therefore, this latency should be tuned somewhat
115// conservatively (or at least with awareness of the trade-off being made).
116static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
117
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700118// This is the phase offset at which SurfaceFlinger's composition runs.
119static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121// ---------------------------------------------------------------------------
122
Mathias Agopian99b49842011-06-27 16:05:52 -0700123const String16 sHardwareTest("android.permission.HARDWARE_TEST");
124const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
125const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
126const String16 sDump("android.permission.DUMP");
127
128// ---------------------------------------------------------------------------
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700131 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700133 mTransactionPending(false),
134 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700136 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700137 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700153 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800157 mHasColorMatrix(false),
158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Steve Blocka19954a2012-01-04 20:05:49 +0000163 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164
165 // debugging stuff...
166 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700167
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700169 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 property_get("debug.sf.showupdates", value, "0");
172 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174 property_get("debug.sf.ddms", value, "0");
175 mDebugDDMS = atoi(value);
176 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700177 if (!startDdmConnection()) {
178 // start failed, and DDMS debugging not enabled
179 mDebugDDMS = 0;
180 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700181 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700182 ALOGI_IF(mDebugRegion, "showupdates enabled");
183 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700184
185 property_get("debug.sf.disable_backpressure", value, "0");
186 mPropagateBackpressure = !atoi(value);
187 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700188
189 property_get("debug.sf.disable_hwc_vds", value, "0");
190 mUseHwcVirtualDisplays = !atoi(value);
191 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192}
193
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800194void SurfaceFlinger::onFirstRef()
195{
196 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197}
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199SurfaceFlinger::~SurfaceFlinger()
200{
Mathias Agopiana4912602012-07-12 14:25:33 -0700201 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
202 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
203 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204}
205
Dan Stozac7014012014-02-14 15:03:43 -0800206void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207{
208 // the window manager died on us. prepare its eulogy.
209
Andy McFadden13a082e2012-08-24 10:16:42 -0700210 // restore initial conditions (default device unblank, etc)
211 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800212
213 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700214 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800215}
216
Mathias Agopian7e27f052010-05-28 14:22:23 -0700217sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218{
Mathias Agopian96f08192010-06-02 23:28:45 -0700219 sp<ISurfaceComposerClient> bclient;
220 sp<Client> client(new Client(this));
221 status_t err = client->initCheck();
222 if (err == NO_ERROR) {
223 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 return bclient;
226}
227
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700228sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
229 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700230{
231 class DisplayToken : public BBinder {
232 sp<SurfaceFlinger> flinger;
233 virtual ~DisplayToken() {
234 // no more references, this display must be terminated
235 Mutex::Autolock _l(flinger->mStateLock);
236 flinger->mCurrentState.displays.removeItem(this);
237 flinger->setTransactionFlags(eDisplayTransactionNeeded);
238 }
239 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700240 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241 : flinger(flinger) {
242 }
243 };
244
245 sp<BBinder> token = new DisplayToken(this);
246
247 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700248 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700249 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700250 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700251 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700252 return token;
253}
254
Jesse Hall6c913be2013-08-08 12:15:49 -0700255void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
256 Mutex::Autolock _l(mStateLock);
257
258 ssize_t idx = mCurrentState.displays.indexOfKey(display);
259 if (idx < 0) {
260 ALOGW("destroyDisplay: invalid display token");
261 return;
262 }
263
264 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
265 if (!info.isVirtualDisplay()) {
266 ALOGE("destroyDisplay called for non-virtual display");
267 return;
268 }
Irvelffc9efc2016-07-27 15:16:37 -0700269 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700270 mCurrentState.displays.removeItemsAt(idx);
271 setTransactionFlags(eDisplayTransactionNeeded);
272}
273
Jesse Hall692c7232012-11-08 15:41:56 -0800274void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800275 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800276 ALOGW_IF(mBuiltinDisplays[type],
277 "Overwriting display token for display type %d", type);
278 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800279 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700280 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800281 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700282 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800283}
284
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700286 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700287 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
288 return NULL;
289 }
Jesse Hall692c7232012-11-08 15:41:56 -0800290 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291}
292
Jamie Gennis9a78c902011-01-12 18:30:40 -0800293sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
294{
295 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
296 return gba;
297}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299void SurfaceFlinger::bootFinished()
300{
301 const nsecs_t now = systemTime();
302 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000303 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700304 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700305
306 // wait patiently for the window manager death
307 const String16 name("window");
308 sp<IBinder> window(defaultServiceManager()->getService(name));
309 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700310 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700311 }
312
313 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700314 // formerly we would just kill the process, but we now ask it to exit so it
315 // can choose where to stop the animation.
316 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700317
318 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
319 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
320 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Mathias Agopian3f844832013-08-07 21:24:32 -0700323void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700324 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 RenderEngine& engine;
326 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700327 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700328 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
329 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330 }
331 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700332 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700333 return true;
334 }
335 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700336 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337}
338
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700339class DispSyncSource : public VSyncSource, private DispSync::Callback {
340public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700341 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000342 const char* name) :
343 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700344 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700345 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
347 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700348 mDispSync(dispSync),
349 mCallbackMutex(),
350 mCallback(),
351 mVsyncMutex(),
352 mPhaseOffset(phaseOffset),
353 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700354
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700355 virtual ~DispSyncSource() {}
356
357 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700358 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700359 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000360 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 static_cast<DispSync::Callback*>(this));
362 if (err != NO_ERROR) {
363 ALOGE("error registering vsync callback: %s (%d)",
364 strerror(-err), err);
365 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700366 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 } else {
368 status_t err = mDispSync->removeEventListener(
369 static_cast<DispSync::Callback*>(this));
370 if (err != NO_ERROR) {
371 ALOGE("error unregistering vsync callback: %s (%d)",
372 strerror(-err), err);
373 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700374 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700376 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 }
378
379 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 mCallback = callback;
382 }
383
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700384 virtual void setPhaseOffset(nsecs_t phaseOffset) {
385 Mutex::Autolock lock(mVsyncMutex);
386
387 // Normalize phaseOffset to [0, period)
388 auto period = mDispSync->getPeriod();
389 phaseOffset %= period;
390 if (phaseOffset < 0) {
391 // If we're here, then phaseOffset is in (-period, 0). After this
392 // operation, it will be in (0, period)
393 phaseOffset += period;
394 }
395 mPhaseOffset = phaseOffset;
396
397 // If we're not enabled, we don't need to mess with the listeners
398 if (!mEnabled) {
399 return;
400 }
401
402 // Remove the listener with the old offset
403 status_t err = mDispSync->removeEventListener(
404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error unregistering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
409
410 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error registering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
417 }
418
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419private:
420 virtual void onDispSyncEvent(nsecs_t when) {
421 sp<VSyncSource::Callback> callback;
422 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 callback = mCallback;
425
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700426 if (mTraceVsync) {
427 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700429 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
431
432 if (callback != NULL) {
433 callback->onVSyncEvent(when);
434 }
435 }
436
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 const char* const mName;
438
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 int mValue;
440
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700441 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700442 const String8 mVsyncOnLabel;
443 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700444
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446
447 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449
450 Mutex mVsyncMutex; // Protects the following
451 nsecs_t mPhaseOffset;
452 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453};
454
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700455class InjectVSyncSource : public VSyncSource {
456public:
457 InjectVSyncSource() {}
458
459 virtual ~InjectVSyncSource() {}
460
461 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
462 std::lock_guard<std::mutex> lock(mCallbackMutex);
463 mCallback = callback;
464 }
465
466 virtual void onInjectSyncEvent(nsecs_t when) {
467 std::lock_guard<std::mutex> lock(mCallbackMutex);
468 mCallback->onVSyncEvent(when);
469 }
470
471 virtual void setVSyncEnabled(bool) {}
472 virtual void setPhaseOffset(nsecs_t) {}
473
474private:
475 std::mutex mCallbackMutex; // Protects the following
476 sp<VSyncSource::Callback> mCallback;
477};
478
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700480 ALOGI( "SurfaceFlinger's main thread ready to run. "
481 "Initializing graphics H/W...");
482
Dan Stoza9e56aa02015-11-02 13:00:03 -0800483 { // Autolock scope
484 Mutex::Autolock _l(mStateLock);
485
486 // initialize EGL for the default display
487 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
488 eglInitialize(mEGLDisplay, NULL, NULL);
489
490 // start the EventThread
491 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
492 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700493 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800494 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
495 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700496 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800497 mEventQueue.setEventThread(mSFEventThread);
498
Tim Murrayacff43d2016-07-29 13:57:24 -0700499 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700500 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700501 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700502 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
503 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
504 }
505
Dan Stoza9e56aa02015-11-02 13:00:03 -0800506 // Get a RenderEngine for the given display / config (can't fail)
507 mRenderEngine = RenderEngine::create(mEGLDisplay,
508 HAL_PIXEL_FORMAT_RGBA_8888);
509 }
510
511 // Drop the state lock while we initialize the hardware composer. We drop
512 // the lock because on creation, it will call back into SurfaceFlinger to
513 // initialize the primary display.
514 mHwc = new HWComposer(this);
515 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
516
Jesse Hall692c7232012-11-08 15:41:56 -0800517 Mutex::Autolock _l(mStateLock);
518
Mathias Agopian875d8e12013-06-07 15:35:48 -0700519 // retrieve the EGL context that was selected/created
520 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700521
Mathias Agopianda27af92012-09-13 18:17:13 -0700522 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
523 "couldn't create EGLContext");
524
Dan Stoza9e56aa02015-11-02 13:00:03 -0800525 // make the GLContext current so that we can create textures when creating
526 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700527 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
528
Jamie Gennisd1700752013-10-14 12:22:52 -0700529 mEventControlThread = new EventControlThread(this);
530 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
531
Mathias Agopian92a979a2012-08-02 18:32:23 -0700532 // initialize our drawing state
533 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700534
Andy McFadden13a082e2012-08-24 10:16:42 -0700535 // set initial conditions (e.g. unblank default device)
536 initializeDisplays();
537
Dan Stoza4e637772016-07-28 13:31:51 -0700538 mRenderEngine->primeCache();
539
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700540 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700541 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542
Dan Stoza9e56aa02015-11-02 13:00:03 -0800543 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700544}
545
Mathias Agopiana67e4182012-06-19 17:26:12 -0700546void SurfaceFlinger::startBootAnim() {
547 // start boot animation
548 property_set("service.bootanim.exit", "0");
549 property_set("ctl.start", "bootanim");
550}
551
Mathias Agopian875d8e12013-06-07 15:35:48 -0700552size_t SurfaceFlinger::getMaxTextureSize() const {
553 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700554}
555
Mathias Agopian875d8e12013-06-07 15:35:48 -0700556size_t SurfaceFlinger::getMaxViewportDims() const {
557 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700558}
559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800561
Jamie Gennis582270d2011-08-17 18:19:00 -0700562bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800563 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800564 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800565 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700566 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800567}
568
Brian Anderson069b3652016-07-22 10:32:47 -0700569status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700570 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700571 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700572 FrameEvent::REQUESTED_PRESENT,
573 FrameEvent::ACQUIRE,
574 FrameEvent::FIRST_REFRESH_START,
575 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson069b3652016-07-22 10:32:47 -0700576 getHwComposer().retireFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700577 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
578 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700579 };
580 return NO_ERROR;
581}
582
Dan Stoza7f7da322014-05-02 15:26:25 -0700583status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
584 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700585 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700586 return BAD_VALUE;
587 }
588
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500589 if (!display.get())
590 return NAME_NOT_FOUND;
591
Jesse Hall692c7232012-11-08 15:41:56 -0800592 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700593 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800594 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700595 type = i;
596 break;
597 }
598 }
599
600 if (type < 0) {
601 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700602 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700603
Mathias Agopian8b736f12012-08-13 17:54:26 -0700604 // TODO: Not sure if display density should handled by SF any longer
605 class Density {
606 static int getDensityFromProperty(char const* propName) {
607 char property[PROPERTY_VALUE_MAX];
608 int density = 0;
609 if (property_get(propName, property, NULL) > 0) {
610 density = atoi(property);
611 }
612 return density;
613 }
614 public:
615 static int getEmuDensity() {
616 return getDensityFromProperty("qemu.sf.lcd_density"); }
617 static int getBuildDensity() {
618 return getDensityFromProperty("ro.sf.lcd_density"); }
619 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700620
Dan Stoza7f7da322014-05-02 15:26:25 -0700621 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700622
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700624 DisplayInfo info = DisplayInfo();
625
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626 float xdpi = hwConfig->getDpiX();
627 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700628
629 if (type == DisplayDevice::DISPLAY_PRIMARY) {
630 // The density of the device is provided by a build property
631 float density = Density::getBuildDensity() / 160.0f;
632 if (density == 0) {
633 // the build doesn't provide a density -- this is wrong!
634 // use xdpi instead
635 ALOGE("ro.sf.lcd_density must be defined as a build property");
636 density = xdpi / 160.0f;
637 }
638 if (Density::getEmuDensity()) {
639 // if "qemu.sf.lcd_density" is specified, it overrides everything
640 xdpi = ydpi = density = Density::getEmuDensity();
641 density /= 160.0f;
642 }
643 info.density = density;
644
645 // TODO: this needs to go away (currently needed only by webkit)
646 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
647 info.orientation = hw->getOrientation();
648 } else {
649 // TODO: where should this value come from?
650 static const int TV_DENSITY = 213;
651 info.density = TV_DENSITY / 160.0f;
652 info.orientation = 0;
653 }
654
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655 info.w = hwConfig->getWidth();
656 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700657 info.xdpi = xdpi;
658 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700660 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661
Andy McFadden91b2ca82014-06-13 14:04:23 -0700662 // This is how far in advance a buffer must be queued for
663 // presentation at a given time. If you want a buffer to appear
664 // on the screen at time N, you must submit the buffer before
665 // (N - presentationDeadline).
666 //
667 // Normally it's one full refresh period (to give SF a chance to
668 // latch the buffer), but this can be reduced by configuring a
669 // DispSync offset. Any additional delays introduced by the hardware
670 // composer or panel must be accounted for here.
671 //
672 // We add an additional 1ms to allow for processing time and
673 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674 info.presentationDeadline = hwConfig->getVsyncPeriod() -
675 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700676
677 // All non-virtual displays are currently considered secure.
678 info.secure = true;
679
Michael Wright28f24d02016-07-12 13:30:53 -0700680 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700681 }
682
Dan Stoza7f7da322014-05-02 15:26:25 -0700683 return NO_ERROR;
684}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700685
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800686status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700687 DisplayStatInfo* stats) {
688 if (stats == NULL) {
689 return BAD_VALUE;
690 }
691
692 // FIXME for now we always return stats for the primary display
693 memset(stats, 0, sizeof(*stats));
694 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
695 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
696 return NO_ERROR;
697}
698
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700699int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700700 sp<DisplayDevice> device(getDisplayDevice(display));
701 if (device != NULL) {
702 return device->getActiveConfig();
703 }
704 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700705}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700706
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700707void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
708 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
709 this);
710 int32_t type = hw->getDisplayType();
711 int currentMode = hw->getActiveConfig();
712
713 if (mode == currentMode) {
714 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
715 return;
716 }
717
718 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
719 ALOGW("Trying to set config for virtual display");
720 return;
721 }
722
723 hw->setActiveConfig(mode);
724 getHwComposer().setActiveConfig(type, mode);
725}
726
727status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
728 class MessageSetActiveConfig: public MessageBase {
729 SurfaceFlinger& mFlinger;
730 sp<IBinder> mDisplay;
731 int mMode;
732 public:
733 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
734 int mode) :
735 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
736 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700737 Vector<DisplayInfo> configs;
738 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700739 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700740 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700741 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700742 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700743 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700744 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
745 if (hw == NULL) {
746 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700747 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700748 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
749 ALOGW("Attempt to set active config = %d for virtual display",
750 mMode);
751 } else {
752 mFlinger.setActiveConfigInternal(hw, mMode);
753 }
754 return true;
755 }
756 };
757 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
758 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700759 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700760}
Michael Wright28f24d02016-07-12 13:30:53 -0700761status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
762 Vector<android_color_mode_t>* outColorModes) {
763 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
764 return BAD_VALUE;
765 }
766
767 if (!display.get()) {
768 return NAME_NOT_FOUND;
769 }
770
771 int32_t type = NAME_NOT_FOUND;
772 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
773 if (display == mBuiltinDisplays[i]) {
774 type = i;
775 break;
776 }
777 }
778
779 if (type < 0) {
780 return type;
781 }
782
783 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
784 outColorModes->clear();
785 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
786
787 return NO_ERROR;
788}
789
790android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
791 sp<DisplayDevice> device(getDisplayDevice(display));
792 if (device != nullptr) {
793 return device->getActiveColorMode();
794 }
795 return static_cast<android_color_mode_t>(BAD_VALUE);
796}
797
798void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
799 android_color_mode_t mode) {
800 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
801 this);
802 int32_t type = hw->getDisplayType();
803 android_color_mode_t currentMode = hw->getActiveColorMode();
804
805 if (mode == currentMode) {
806 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
807 return;
808 }
809
810 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
811 ALOGW("Trying to set config for virtual display");
812 return;
813 }
814
815 hw->setActiveColorMode(mode);
816 getHwComposer().setActiveColorMode(type, mode);
817}
818
819
820status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
821 android_color_mode_t colorMode) {
822 class MessageSetActiveColorMode: public MessageBase {
823 SurfaceFlinger& mFlinger;
824 sp<IBinder> mDisplay;
825 android_color_mode_t mMode;
826 public:
827 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
828 android_color_mode_t mode) :
829 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
830 virtual bool handler() {
831 Vector<android_color_mode_t> modes;
832 mFlinger.getDisplayColorModes(mDisplay, &modes);
833 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
834 if (mMode < 0 || !exists) {
835 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
836 mDisplay.get());
837 return true;
838 }
839 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
840 if (hw == nullptr) {
841 ALOGE("Attempt to set active color mode = %d for null display %p",
842 mMode, mDisplay.get());
843 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
844 ALOGW("Attempt to set active color mode= %d for virtual display",
845 mMode);
846 } else {
847 mFlinger.setActiveColorModeInternal(hw, mMode);
848 }
849 return true;
850 }
851 };
852 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
853 postMessageSync(msg);
854 return NO_ERROR;
855}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700856
Svetoslavd85084b2014-03-20 10:28:31 -0700857status_t SurfaceFlinger::clearAnimationFrameStats() {
858 Mutex::Autolock _l(mStateLock);
859 mAnimFrameTracker.clearStats();
860 return NO_ERROR;
861}
862
863status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
864 Mutex::Autolock _l(mStateLock);
865 mAnimFrameTracker.getStats(outStats);
866 return NO_ERROR;
867}
868
Dan Stozac4f471e2016-03-24 09:31:08 -0700869status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
870 HdrCapabilities* outCapabilities) const {
871 Mutex::Autolock _l(mStateLock);
872
873 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
874 if (displayDevice == nullptr) {
875 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
876 return BAD_VALUE;
877 }
878
879 std::unique_ptr<HdrCapabilities> capabilities =
880 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
881 if (capabilities) {
882 std::swap(*outCapabilities, *capabilities);
883 } else {
884 return BAD_VALUE;
885 }
886
887 return NO_ERROR;
888}
889
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700890status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
891 if (enable == mInjectVSyncs) {
892 return NO_ERROR;
893 }
894
895 if (enable) {
896 mInjectVSyncs = enable;
897 ALOGV("VSync Injections enabled");
898 if (mVSyncInjector.get() == nullptr) {
899 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700900 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700901 }
902 mEventQueue.setEventThread(mInjectorEventThread);
903 } else {
904 mInjectVSyncs = enable;
905 ALOGV("VSync Injections disabled");
906 mEventQueue.setEventThread(mSFEventThread);
907 mVSyncInjector.clear();
908 }
909 return NO_ERROR;
910}
911
912status_t SurfaceFlinger::injectVSync(nsecs_t when) {
913 if (!mInjectVSyncs) {
914 ALOGE("VSync Injections not enabled");
915 return BAD_VALUE;
916 }
917 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
918 ALOGV("Injecting VSync inside SurfaceFlinger");
919 mVSyncInjector->onInjectSyncEvent(when);
920 }
921 return NO_ERROR;
922}
923
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800924// ----------------------------------------------------------------------------
925
926sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800927 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700928}
929
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800930// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800931
932void SurfaceFlinger::waitForEvent() {
933 mEventQueue.waitMessage();
934}
935
936void SurfaceFlinger::signalTransaction() {
937 mEventQueue.invalidate();
938}
939
940void SurfaceFlinger::signalLayerUpdate() {
941 mEventQueue.invalidate();
942}
943
944void SurfaceFlinger::signalRefresh() {
945 mEventQueue.refresh();
946}
947
948status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800949 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800950 return mEventQueue.postMessage(msg, reltime);
951}
952
953status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800954 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800955 status_t res = mEventQueue.postMessage(msg, reltime);
956 if (res == NO_ERROR) {
957 msg->wait();
958 }
959 return res;
960}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700962void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700963 do {
964 waitForEvent();
965 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800966}
967
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700968void SurfaceFlinger::enableHardwareVsync() {
969 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700970 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700971 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700972 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
973 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700974 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700975 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700976}
977
Jesse Hall948fe0c2013-10-14 12:56:09 -0700978void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700979 Mutex::Autolock _l(mHWVsyncLock);
980
Jesse Hall948fe0c2013-10-14 12:56:09 -0700981 if (makeAvailable) {
982 mHWVsyncAvailable = true;
983 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700984 // Hardware vsync is not currently available, so abort the resync
985 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700986 return;
987 }
988
Dan Stoza9e56aa02015-11-02 13:00:03 -0800989 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
990 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700991
992 mPrimaryDispSync.reset();
993 mPrimaryDispSync.setPeriod(period);
994
995 if (!mPrimaryHWVsyncEnabled) {
996 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700997 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
998 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700999 mPrimaryHWVsyncEnabled = true;
1000 }
1001}
1002
Jesse Hall948fe0c2013-10-14 12:56:09 -07001003void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001004 Mutex::Autolock _l(mHWVsyncLock);
1005 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001006 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1007 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001008 mPrimaryDispSync.endResync();
1009 mPrimaryHWVsyncEnabled = false;
1010 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001011 if (makeUnavailable) {
1012 mHWVsyncAvailable = false;
1013 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001014}
1015
Tim Murray4a4e4a22016-04-19 16:29:23 +00001016void SurfaceFlinger::resyncWithRateLimit() {
1017 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1018 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001019 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001020 }
1021}
1022
Dan Stoza9e56aa02015-11-02 13:00:03 -08001023void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001024 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001025
Jamie Gennisd1700752013-10-14 12:22:52 -07001026 { // Scope for the lock
1027 Mutex::Autolock _l(mHWVsyncLock);
1028 if (type == 0 && mPrimaryHWVsyncEnabled) {
1029 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001030 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001031 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001032
1033 if (needsHwVsync) {
1034 enableHardwareVsync();
1035 } else {
1036 disableHardwareVsync(false);
1037 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001038}
1039
Dan Stoza9e56aa02015-11-02 13:00:03 -08001040void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1041 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1042 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1043 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001044
Dan Stoza9e56aa02015-11-02 13:00:03 -08001045 // All non-virtual displays are currently considered secure.
1046 bool isSecure = true;
1047
1048 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1049 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1050 wp<IBinder> token = mBuiltinDisplays[type];
1051
1052 sp<IGraphicBufferProducer> producer;
1053 sp<IGraphicBufferConsumer> consumer;
1054 BufferQueue::createBufferQueue(&producer, &consumer,
1055 new GraphicBufferAlloc());
1056
1057 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1058 DisplayDevice::DISPLAY_PRIMARY, consumer);
1059 sp<DisplayDevice> hw = new DisplayDevice(this,
1060 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1061 producer, mRenderEngine->getEGLConfig());
1062 mDisplays.add(token, hw);
1063 } else {
1064 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001065 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001066 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001067 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001068 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001069 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1070 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001071 }
1072 setTransactionFlags(eDisplayTransactionNeeded);
1073
Andy McFadden9e9689c2012-10-10 18:17:51 -07001074 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001075 }
Mathias Agopian86303202012-07-24 22:46:10 -07001076}
1077
Dan Stoza9e56aa02015-11-02 13:00:03 -08001078void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001080 getHwComposer().setVsyncEnabled(disp,
1081 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001082}
1083
Mathias Agopian4fec8732012-06-29 14:12:52 -07001084void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001085 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001086 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001087 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001088 bool frameMissed = !mHadClientComposition &&
1089 mPreviousPresentFence != Fence::NO_FENCE &&
1090 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1091 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001092 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001093 signalLayerUpdate();
1094 break;
1095 }
1096
Dan Stoza6b9454d2014-11-07 16:00:59 -08001097 bool refreshNeeded = handleMessageTransaction();
1098 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001099 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001100 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001101 // Signal a refresh if a transaction modified the window state,
1102 // a new buffer was latched, or if HWC has requested a full
1103 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001104 signalRefresh();
1105 }
1106 break;
1107 }
1108 case MessageQueue::REFRESH: {
1109 handleMessageRefresh();
1110 break;
1111 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001112 }
1113}
1114
Dan Stoza6b9454d2014-11-07 16:00:59 -08001115bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001116 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001117 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001118 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001119 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001120 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001121 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001122}
1123
Dan Stoza6b9454d2014-11-07 16:00:59 -08001124bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001125 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001126 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001127}
1128
1129void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001130 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001131
Pablo Ceballos40845df2016-01-25 17:41:15 -08001132 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001133
Brian Andersond6927fb2016-07-23 23:37:30 -07001134 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001135 rebuildLayerStacks();
1136 setUpHWComposer();
1137 doDebugFlashRegions();
1138 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001139 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001140
1141 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001142
1143 mHadClientComposition = false;
1144 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1145 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1146 mHadClientComposition = mHadClientComposition ||
1147 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1148 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001149
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001151}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001152
Mathias Agopiancd60f992012-08-16 16:28:27 -07001153void SurfaceFlinger::doDebugFlashRegions()
1154{
1155 // is debugging enabled
1156 if (CC_LIKELY(!mDebugRegion))
1157 return;
1158
1159 const bool repaintEverything = mRepaintEverything;
1160 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1161 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001162 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001163 // transform the dirty region into this screen's coordinate space
1164 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1165 if (!dirtyRegion.isEmpty()) {
1166 // redraw the whole screen
1167 doComposeSurfaces(hw, Region(hw->bounds()));
1168
1169 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001170 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001171 RenderEngine& engine(getRenderEngine());
1172 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1173
Mathias Agopianda27af92012-09-13 18:17:13 -07001174 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001175 }
1176 }
1177 }
1178
1179 postFramebuffer();
1180
1181 if (mDebugRegion > 1) {
1182 usleep(mDebugRegion * 1000);
1183 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001184
Dan Stoza9e56aa02015-11-02 13:00:03 -08001185 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001186 auto& displayDevice = mDisplays[displayId];
1187 if (!displayDevice->isDisplayOn()) {
1188 continue;
1189 }
1190
1191 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1193 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001194 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001195}
1196
Brian Andersond6927fb2016-07-23 23:37:30 -07001197void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001198{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199 ATRACE_CALL();
1200 ALOGV("preComposition");
1201
Mathias Agopiancd60f992012-08-16 16:28:27 -07001202 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001203 const LayerVector& layers(mDrawingState.layersSortedByZ);
1204 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001205 for (size_t i=0 ; i<count ; i++) {
Brian Andersond6927fb2016-07-23 23:37:30 -07001206 if (layers[i]->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001207 needExtraInvalidate = true;
1208 }
1209 }
1210 if (needExtraInvalidate) {
1211 signalLayerUpdate();
1212 }
1213}
1214
Brian Andersond6927fb2016-07-23 23:37:30 -07001215void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001216{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217 ATRACE_CALL();
1218 ALOGV("postComposition");
1219
Brian Anderson3546a3f2016-07-14 11:51:14 -07001220 // Release any buffers which were replaced this frame
1221 for (auto& layer : mLayersWithQueuedFrames) {
1222 layer->releasePendingBuffer();
1223 }
1224
Brian Andersond6927fb2016-07-23 23:37:30 -07001225 bool hadClientComposition = mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY);
1226
1227 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1228 sp<Fence> glCompositionDoneFence = hadClientComposition
1229 ? hw->getClientTargetAcquireFence()
1230 : Fence::NO_FENCE;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001231 const LayerVector& layers(mDrawingState.layersSortedByZ);
1232 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001233 for (size_t i=0 ; i<count ; i++) {
Brian Andersond6927fb2016-07-23 23:37:30 -07001234 bool frameLatched = layers[i]->onPostComposition(glCompositionDoneFence);
Dan Stozae77c7662016-05-13 11:37:28 -07001235 if (frameLatched) {
1236 recordBufferingStats(layers[i]->getName().string(),
1237 layers[i]->getOccupancyHistory(false));
1238 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001239 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001240
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242
1243 if (presentFence->isValid()) {
1244 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1245 enableHardwareVsync();
1246 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001247 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 }
1249 }
1250
Andy McFadden5167ec62014-05-22 13:08:43 -07001251 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001252 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 enableHardwareVsync();
1254 }
1255 }
1256
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001257 if (mAnimCompositionPending) {
1258 mAnimCompositionPending = false;
1259
Jesse Halla9a1b002013-02-27 16:39:25 -08001260 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001261 mAnimFrameTracker.setActualPresentFence(presentFence);
1262 } else {
1263 // The HWC doesn't support present fences, so use the refresh
1264 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001265 nsecs_t presentTime =
1266 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001267 mAnimFrameTracker.setActualPresentTime(presentTime);
1268 }
1269 mAnimFrameTracker.advanceFrame();
1270 }
Dan Stozab90cf072015-03-05 11:05:59 -08001271
1272 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1273 return;
1274 }
1275
1276 nsecs_t currentTime = systemTime();
1277 if (mHasPoweredOff) {
1278 mHasPoweredOff = false;
1279 } else {
1280 nsecs_t period = mPrimaryDispSync.getPeriod();
1281 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1282 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1283 if (numPeriods < NUM_BUCKETS - 1) {
1284 mFrameBuckets[numPeriods] += elapsedTime;
1285 } else {
1286 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1287 }
1288 mTotalTime += elapsedTime;
1289 }
1290 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001291}
1292
1293void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001294 ATRACE_CALL();
1295 ALOGV("rebuildLayerStacks");
1296
Mathias Agopiancd60f992012-08-16 16:28:27 -07001297 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001298 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001299 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001300 mVisibleRegionsDirty = false;
1301 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001302
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001303 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001304 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001305 Region opaqueRegion;
1306 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 Vector<sp<Layer>> layersSortedByZ;
1308 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1309 const Transform& tr(displayDevice->getTransform());
1310 const Rect bounds(displayDevice->getBounds());
1311 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001312 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 displayDevice->getLayerStack(), dirtyRegion,
1314 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001315
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001316 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001317 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001318 const sp<Layer>& layer(layers[i]);
1319 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001321 Region drawRegion(tr.transform(
1322 layer->visibleNonTransparentRegion));
1323 drawRegion.andSelf(bounds);
1324 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001325 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 } else {
1327 // Clear out the HWC layer if this layer was
1328 // previously visible, but no longer is
1329 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1330 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001331 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001332 }
1333 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001334 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001335 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1336 displayDevice->undefinedRegion.set(bounds);
1337 displayDevice->undefinedRegion.subtractSelf(
1338 tr.transform(opaqueRegion));
1339 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001340 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001341 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001343
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001345 ATRACE_CALL();
1346 ALOGV("setUpHWComposer");
1347
Jesse Hall028dc8f2013-08-20 16:35:32 -07001348 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001349 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1350 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1351 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1352
1353 // If nothing has changed (!dirty), don't recompose.
1354 // If something changed, but we don't currently have any visible layers,
1355 // and didn't when we last did a composition, then skip it this time.
1356 // The second rule does two things:
1357 // - When all layers are removed from a display, we'll emit one black
1358 // frame, then nothing more until we get new layers.
1359 // - When a display is created with a private layer stack, we won't
1360 // emit any black frames until a layer is added to the layer stack.
1361 bool mustRecompose = dirty && !(empty && wasEmpty);
1362
1363 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1364 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1365 mustRecompose ? "doing" : "skipping",
1366 dirty ? "+" : "-",
1367 empty ? "+" : "-",
1368 wasEmpty ? "+" : "-");
1369
Dan Stoza71433162014-02-04 16:22:36 -08001370 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001371
1372 if (mustRecompose) {
1373 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1374 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001375 }
1376
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 // build the h/w work list
1378 if (CC_UNLIKELY(mGeometryInvalid)) {
1379 mGeometryInvalid = false;
1380 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1381 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1382 const auto hwcId = displayDevice->getHwcDisplayId();
1383 if (hwcId >= 0) {
1384 const Vector<sp<Layer>>& currentLayers(
1385 displayDevice->getVisibleLayersSortedByZ());
1386 bool foundLayerWithoutHwc = false;
1387 for (auto& layer : currentLayers) {
1388 if (!layer->hasHwcLayer(hwcId)) {
1389 auto hwcLayer = mHwc->createLayer(hwcId);
1390 if (hwcLayer) {
1391 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1392 } else {
1393 layer->forceClientComposition(hwcId);
1394 foundLayerWithoutHwc = true;
1395 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001396 }
1397 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001398
Dan Stoza9e56aa02015-11-02 13:00:03 -08001399 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001400 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001401 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001402 }
1403 }
1404 }
1405 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001406 }
Riley Andrews03414a12014-07-01 14:22:59 -07001407
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001408
1409 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1410
Dan Stoza9e56aa02015-11-02 13:00:03 -08001411 // Set the per-frame data
1412 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1413 auto& displayDevice = mDisplays[displayId];
1414 const auto hwcId = displayDevice->getHwcDisplayId();
1415 if (hwcId < 0) {
1416 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001417 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001418 if (colorMatrix != mPreviousColorMatrix) {
1419 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1420 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1421 "display %zd: %d", displayId, result);
1422 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001423 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1424 layer->setPerFrameData(displayDevice);
1425 }
1426 }
1427
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001428 mPreviousColorMatrix = colorMatrix;
1429
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001431 auto& displayDevice = mDisplays[displayId];
1432 if (!displayDevice->isDisplayOn()) {
1433 continue;
1434 }
1435
1436 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001437 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1438 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001439 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001441
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442void SurfaceFlinger::doComposition() {
1443 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001444 ALOGV("doComposition");
1445
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001446 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001447 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001448 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001449 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001450 // transform the dirty region into this screen's coordinate space
1451 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001452
1453 // repaint the framebuffer (if needed)
1454 doDisplayComposition(hw, dirtyRegion);
1455
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456 hw->dirtyRegion.clear();
1457 hw->flip(hw->swapRegion);
1458 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001459 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001461 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462}
1463
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464void SurfaceFlinger::postFramebuffer()
1465{
Mathias Agopian841cde52012-03-01 15:44:37 -08001466 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001468
Mathias Agopiana44b0412011-10-16 18:46:35 -07001469 const nsecs_t now = systemTime();
1470 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001471
Dan Stoza9e56aa02015-11-02 13:00:03 -08001472 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1473 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001474 if (!displayDevice->isDisplayOn()) {
1475 continue;
1476 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 const auto hwcId = displayDevice->getHwcDisplayId();
1478 if (hwcId >= 0) {
1479 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001480 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001481 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001482 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001483 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1484 sp<Fence> releaseFence = Fence::NO_FENCE;
1485 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1486 releaseFence = displayDevice->getClientTargetAcquireFence();
1487 } else {
1488 auto hwcLayer = layer->getHwcLayer(hwcId);
1489 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001490 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001491 layer->onLayerDisplayed(releaseFence);
1492 }
1493 if (hwcId >= 0) {
1494 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001495 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001496 }
1497
Mathias Agopiana44b0412011-10-16 18:46:35 -07001498 mLastSwapBufferTime = systemTime() - now;
1499 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001500
1501 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1502 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1503 logFrameStats();
1504 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001505}
1506
Mathias Agopian87baae12012-07-31 12:38:26 -07001507void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001508{
Mathias Agopian841cde52012-03-01 15:44:37 -08001509 ATRACE_CALL();
1510
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001511 // here we keep a copy of the drawing state (that is the state that's
1512 // going to be overwritten by handleTransactionLocked()) outside of
1513 // mStateLock so that the side-effects of the State assignment
1514 // don't happen with mStateLock held (which can cause deadlocks).
1515 State drawingState(mDrawingState);
1516
Mathias Agopianca4d3602011-05-19 15:38:14 -07001517 Mutex::Autolock _l(mStateLock);
1518 const nsecs_t now = systemTime();
1519 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001520
Mathias Agopianca4d3602011-05-19 15:38:14 -07001521 // Here we're guaranteed that some transaction flags are set
1522 // so we can call handleTransactionLocked() unconditionally.
1523 // We call getTransactionFlags(), which will also clear the flags,
1524 // with mStateLock held to guarantee that mCurrentState won't change
1525 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001526
Mathias Agopiane57f2922012-08-09 16:29:12 -07001527 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001528 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001529
Mathias Agopianca4d3602011-05-19 15:38:14 -07001530 mLastTransactionTime = systemTime() - now;
1531 mDebugInTransaction = 0;
1532 invalidateHwcGeometry();
1533 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001534}
1535
Mathias Agopian87baae12012-07-31 12:38:26 -07001536void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001537{
1538 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001539 const size_t count = currentLayers.size();
1540
Dan Stoza7dde5992015-05-22 09:51:44 -07001541 // Notify all layers of available frames
1542 for (size_t i = 0; i < count; ++i) {
1543 currentLayers[i]->notifyAvailableFrames();
1544 }
1545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001546 /*
1547 * Traversal of the children
1548 * (perform the transaction for each of them if needed)
1549 */
1550
Mathias Agopian3559b072012-08-15 13:46:03 -07001551 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001552 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001553 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001554 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1555 if (!trFlags) continue;
1556
1557 const uint32_t flags = layer->doTransaction(0);
1558 if (flags & Layer::eVisibleRegion)
1559 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560 }
1561 }
1562
1563 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001564 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001565 */
1566
Mathias Agopiane57f2922012-08-09 16:29:12 -07001567 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001568 // here we take advantage of Vector's copy-on-write semantics to
1569 // improve performance by skipping the transaction entirely when
1570 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001571 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1572 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001573 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001574 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001575 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001576 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001577
1578 // find the displays that were removed
1579 // (ie: in drawing state but not in current state)
1580 // also handle displays that changed
1581 // (ie: displays that are in both lists)
1582 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001583 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1584 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001585 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001586 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001587 // Call makeCurrent() on the primary display so we can
1588 // be sure that nothing associated with this display
1589 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001590 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001591 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001592 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1593 if (hw != NULL)
1594 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001595 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001596 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001597 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001598 } else {
1599 ALOGW("trying to remove the main display");
1600 }
1601 } else {
1602 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001603 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001604 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001605 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1606 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001607 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001608 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001609 // recreating the DisplayDevice, so we just remove it
1610 // from the drawing state, so that it get re-added
1611 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001612 sp<DisplayDevice> hw(getDisplayDevice(display));
1613 if (hw != NULL)
1614 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001615 mDisplays.removeItem(display);
1616 mDrawingState.displays.removeItemsAt(i);
1617 dc--; i--;
1618 // at this point we must loop to the next item
1619 continue;
1620 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001621
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001622 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001623 if (disp != NULL) {
1624 if (state.layerStack != draw[i].layerStack) {
1625 disp->setLayerStack(state.layerStack);
1626 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001627 if ((state.orientation != draw[i].orientation)
1628 || (state.viewport != draw[i].viewport)
1629 || (state.frame != draw[i].frame))
1630 {
1631 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001632 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001633 }
Michael Lentine47e45402014-07-18 15:34:25 -07001634 if (state.width != draw[i].width || state.height != draw[i].height) {
1635 disp->setDisplaySize(state.width, state.height);
1636 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001637 }
1638 }
1639 }
1640
1641 // find displays that were added
1642 // (ie: in current state but not in drawing state)
1643 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001644 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001645 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001646
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001647 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001648 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001649 sp<IGraphicBufferProducer> bqProducer;
1650 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001651 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1652 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001653
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001655 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001656 // Virtual displays without a surface are dormant:
1657 // they have external state (layer stack, projection,
1658 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001659 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001660
Dan Stoza8cf150a2016-08-02 10:27:31 -07001661 if (mUseHwcVirtualDisplays) {
1662 int width = 0;
1663 int status = state.surface->query(
1664 NATIVE_WINDOW_WIDTH, &width);
1665 ALOGE_IF(status != NO_ERROR,
1666 "Unable to query width (%d)", status);
1667 int height = 0;
1668 status = state.surface->query(
1669 NATIVE_WINDOW_HEIGHT, &height);
1670 ALOGE_IF(status != NO_ERROR,
1671 "Unable to query height (%d)", status);
1672 int intFormat = 0;
1673 status = state.surface->query(
1674 NATIVE_WINDOW_FORMAT, &intFormat);
1675 ALOGE_IF(status != NO_ERROR,
1676 "Unable to query format (%d)", status);
1677 auto format = static_cast<android_pixel_format_t>(
1678 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001679
Dan Stoza8cf150a2016-08-02 10:27:31 -07001680 mHwc->allocateVirtualDisplay(width, height, &format,
1681 &hwcId);
1682 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683
Dan Stoza5cf424b2016-05-20 14:02:39 -07001684 // TODO: Plumb requested format back up to consumer
1685
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 sp<VirtualDisplaySurface> vds =
1687 new VirtualDisplaySurface(*mHwc,
1688 hwcId, state.surface, bqProducer,
1689 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001690
1691 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001692 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001693 }
1694 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001695 ALOGE_IF(state.surface!=NULL,
1696 "adding a supported display, but rendering "
1697 "surface is provided (%p), ignoring it",
1698 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001699 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1700 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1701 dispSurface = new FramebufferSurface(*mHwc,
1702 DisplayDevice::DISPLAY_EXTERNAL,
1703 bqConsumer);
1704 producer = bqProducer;
1705 } else {
1706 ALOGE("Attempted to add non-external non-virtual"
1707 " display");
1708 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001709 }
1710
1711 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001712 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001713 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001714 state.type, hwcId, state.isSecure, display,
1715 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001716 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001717 hw->setLayerStack(state.layerStack);
1718 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001719 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001720 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001721 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001722 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001723 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001724 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001725 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001726 }
1727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001728 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001730
Mathias Agopian84300952012-11-21 16:02:13 -08001731 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1732 // The transform hint might have changed for some layers
1733 // (either because a display has changed, or because a layer
1734 // as changed).
1735 //
1736 // Walk through all the layers in currentLayers,
1737 // and update their transform hint.
1738 //
1739 // If a layer is visible only on a single display, then that
1740 // display is used to calculate the hint, otherwise we use the
1741 // default display.
1742 //
1743 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1744 // the hint is set before we acquire a buffer from the surface texture.
1745 //
1746 // NOTE: layer transactions have taken place already, so we use their
1747 // drawing state. However, SurfaceFlinger's own transaction has not
1748 // happened yet, so we must use the current state layer list
1749 // (soon to become the drawing state list).
1750 //
1751 sp<const DisplayDevice> disp;
1752 uint32_t currentlayerStack = 0;
1753 for (size_t i=0; i<count; i++) {
1754 // NOTE: we rely on the fact that layers are sorted by
1755 // layerStack first (so we don't have to traverse the list
1756 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001757 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001758 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001759 if (i==0 || currentlayerStack != layerStack) {
1760 currentlayerStack = layerStack;
1761 // figure out if this layerstack is mirrored
1762 // (more than one display) if so, pick the default display,
1763 // if not, pick the only display it's on.
1764 disp.clear();
1765 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1766 sp<const DisplayDevice> hw(mDisplays[dpy]);
1767 if (hw->getLayerStack() == currentlayerStack) {
1768 if (disp == NULL) {
1769 disp = hw;
1770 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001771 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001772 break;
1773 }
1774 }
1775 }
1776 }
Chet Haase91d25932013-04-11 15:24:55 -07001777 if (disp == NULL) {
1778 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1779 // redraw after transform hint changes. See bug 8508397.
1780
1781 // could be null when this layer is using a layerStack
1782 // that is not visible on any display. Also can occur at
1783 // screen off/on times.
1784 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001785 }
Chet Haase91d25932013-04-11 15:24:55 -07001786 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001787 }
1788 }
1789
1790
Mathias Agopian3559b072012-08-15 13:46:03 -07001791 /*
1792 * Perform our own transaction if needed
1793 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001794
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001795 const LayerVector& layers(mDrawingState.layersSortedByZ);
1796 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001797 // layers have been added
1798 mVisibleRegionsDirty = true;
1799 }
1800
1801 // some layers might have been removed, so
1802 // we need to update the regions they're exposing.
1803 if (mLayersRemoved) {
1804 mLayersRemoved = false;
1805 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001806 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001807 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001808 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001809 if (currentLayers.indexOf(layer) < 0) {
1810 // this layer is not visible anymore
1811 // TODO: we could traverse the tree from front to back and
1812 // compute the actual visible region
1813 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001814 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001815 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001816 Region(Rect(s.active.w, s.active.h)));
1817 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001818 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 }
1821
1822 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001823
1824 updateCursorAsync();
1825}
1826
1827void SurfaceFlinger::updateCursorAsync()
1828{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1830 auto& displayDevice = mDisplays[displayId];
1831 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001832 continue;
1833 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834
1835 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1836 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001837 }
1838 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001839}
1840
1841void SurfaceFlinger::commitTransaction()
1842{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001843 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001844 // Notify removed layers now that they can't be drawn from
1845 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001846 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1847 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001848 mLayersPendingRemoval[i]->onRemoved();
1849 }
1850 mLayersPendingRemoval.clear();
1851 }
1852
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001853 // If this transaction is part of a window animation then the next frame
1854 // we composite should be considered an animation as well.
1855 mAnimCompositionPending = mAnimTransactionPending;
1856
Mathias Agopian4fec8732012-06-29 14:12:52 -07001857 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001858 mTransactionPending = false;
1859 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001860 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001861}
1862
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001863void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001864 const LayerVector& currentLayers, uint32_t layerStack,
1865 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866{
Mathias Agopian841cde52012-03-01 15:44:37 -08001867 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001869
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001870 Region aboveOpaqueLayers;
1871 Region aboveCoveredLayers;
1872 Region dirty;
1873
Mathias Agopian87baae12012-07-31 12:38:26 -07001874 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875
1876 size_t i = currentLayers.size();
1877 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001878 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001879
1880 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001881 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001882
Jesse Hall01e29052013-02-19 16:13:35 -08001883 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001884 if (s.layerStack != layerStack)
1885 continue;
1886
Mathias Agopianab028732010-03-16 16:41:46 -07001887 /*
1888 * opaqueRegion: area of a surface that is fully opaque.
1889 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001890 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001891
1892 /*
1893 * visibleRegion: area of a surface that is visible on screen
1894 * and not fully transparent. This is essentially the layer's
1895 * footprint minus the opaque regions above it.
1896 * Areas covered by a translucent surface are considered visible.
1897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001898 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001899
1900 /*
1901 * coveredRegion: area of a surface that is covered by all
1902 * visible regions above it (which includes the translucent areas).
1903 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001904 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001905
Jesse Halla8026d22012-09-25 13:25:04 -07001906 /*
1907 * transparentRegion: area of a surface that is hinted to be completely
1908 * transparent. This is only used to tell when the layer has no visible
1909 * non-transparent regions and can be removed from the layer list. It
1910 * does not affect the visibleRegion of this layer or any layers
1911 * beneath it. The hint may not be correct if apps don't respect the
1912 * SurfaceView restrictions (which, sadly, some don't).
1913 */
1914 Region transparentRegion;
1915
Mathias Agopianab028732010-03-16 16:41:46 -07001916
1917 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001918 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001919 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001920 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001921 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001922 if (!visibleRegion.isEmpty()) {
1923 // Remove the transparent area from the visible region
1924 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001925 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001926 if (tr.preserveRects()) {
1927 // transform the transparent region
1928 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001929 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001930 // transformation too complex, can't do the
1931 // transparent region optimization.
1932 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001933 }
Mathias Agopianab028732010-03-16 16:41:46 -07001934 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001935
Mathias Agopianab028732010-03-16 16:41:46 -07001936 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001937 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001939 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1940 // the opaque region is the layer's footprint
1941 opaqueRegion = visibleRegion;
1942 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001943 }
1944 }
1945
Mathias Agopianab028732010-03-16 16:41:46 -07001946 // Clip the covered region to the visible region
1947 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1948
1949 // Update aboveCoveredLayers for next (lower) layer
1950 aboveCoveredLayers.orSelf(visibleRegion);
1951
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001952 // subtract the opaque region covered by the layers above us
1953 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001954
1955 // compute this layer's dirty region
1956 if (layer->contentDirty) {
1957 // we need to invalidate the whole region
1958 dirty = visibleRegion;
1959 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001960 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001961 layer->contentDirty = false;
1962 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001963 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001964 * the exposed region consists of two components:
1965 * 1) what's VISIBLE now and was COVERED before
1966 * 2) what's EXPOSED now less what was EXPOSED before
1967 *
1968 * note that (1) is conservative, we start with the whole
1969 * visible region but only keep what used to be covered by
1970 * something -- which mean it may have been exposed.
1971 *
1972 * (2) handles areas that were not covered by anything but got
1973 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001974 */
Mathias Agopianab028732010-03-16 16:41:46 -07001975 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001976 const Region oldVisibleRegion = layer->visibleRegion;
1977 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001978 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1979 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980 }
1981 dirty.subtractSelf(aboveOpaqueLayers);
1982
1983 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001984 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985
Mathias Agopianab028732010-03-16 16:41:46 -07001986 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001988
Jesse Halla8026d22012-09-25 13:25:04 -07001989 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990 layer->setVisibleRegion(visibleRegion);
1991 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001992 layer->setVisibleNonTransparentRegion(
1993 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994 }
1995
Mathias Agopian87baae12012-07-31 12:38:26 -07001996 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997}
1998
Mathias Agopian87baae12012-07-31 12:38:26 -07001999void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2000 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002001 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002002 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2003 if (hw->getLayerStack() == layerStack) {
2004 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002005 }
2006 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002007}
2008
Dan Stoza6b9454d2014-11-07 16:00:59 -08002009bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ALOGV("handlePageFlip");
2012
Brian Andersond6927fb2016-07-23 23:37:30 -07002013 nsecs_t latchTime = systemTime();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002017 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002018 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002019
2020 // Store the set of layers that need updates. This set must not change as
2021 // buffers are being latched, as this could result in a deadlock.
2022 // Example: Two producers share the same command stream and:
2023 // 1.) Layer 0 is latched
2024 // 2.) Layer 0 gets a new frame
2025 // 2.) Layer 1 gets a new frame
2026 // 3.) Layer 1 is latched.
2027 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2028 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002029 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002030 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002031 if (layer->hasQueuedFrame()) {
2032 frameQueued = true;
2033 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002035 } else {
2036 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002037 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002038 } else {
2039 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002040 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002041 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002043 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002044 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002045 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002046 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002047 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002048
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002049 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002050
2051 // If we will need to wake up at some time in the future to deal with a
2052 // queued frame that shouldn't be displayed during this vsync period, wake
2053 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002055 signalLayerUpdate();
2056 }
2057
2058 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060}
2061
Mathias Agopianad456f92011-01-13 17:53:01 -08002062void SurfaceFlinger::invalidateHwcGeometry()
2063{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002065}
2066
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002067
Mathias Agopiancd60f992012-08-16 16:28:27 -07002068void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070{
Dan Stoza71433162014-02-04 16:22:36 -08002071 // We only need to actually compose the display if:
2072 // 1) It is being handled by hardware composer, which may need this to
2073 // keep its virtual display state machine in sync, or
2074 // 2) There is work to be done (the dirty region isn't empty)
2075 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2076 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002078 return;
2079 }
2080
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 ALOGV("doDisplayComposition");
2082
Mathias Agopian87baae12012-07-31 12:38:26 -07002083 Region dirtyRegion(inDirtyRegion);
2084
Mathias Agopianb8a55602009-06-26 19:06:36 -07002085 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002086 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087
Mathias Agopian42977342012-08-05 00:40:46 -07002088 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002089 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002090 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2091 // takes a rectangle, we must make sure to update that whole
2092 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002093 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002094 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002095 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002096 // We need to redraw the rectangle that will be updated
2097 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002098 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002099 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002100 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002101 } else {
2102 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002103 dirtyRegion.set(hw->bounds());
2104 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105 }
2106 }
2107
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002108 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002110 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002111 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002112
2113 // swap buffers (presentation)
2114 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115}
2116
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117bool SurfaceFlinger::doComposeSurfaces(
2118 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002119{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002121
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002123
2124 mat4 oldColorMatrix;
2125 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2126 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2127 if (applyColorMatrix) {
2128 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2129 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2130 }
2131
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2133 if (hasClientComposition) {
2134 ALOGV("hasClientComposition");
2135
2136 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002137 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002139 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2140 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2141 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2142 }
2143 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002144 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002145
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002146 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2148 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002149 // when using overlays, we assume a fully transparent framebuffer
2150 // NOTE: we could reduce how much we need to clear, for instance
2151 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002152 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002153 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002155 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002156 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002158
2159 // we remove the scissor part
2160 // we're left with the letterbox region
2161 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002163
2164 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002166
2167 // but limit it to the dirty region
2168 region.andSelf(dirty);
2169
Mathias Agopianb9494d52012-04-18 02:28:45 -07002170 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002171 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002172 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002174 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002175 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002176
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002178 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002179 // scissor on the main display. It should never be needed
2180 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 const Rect& bounds(displayDevice->getBounds());
2182 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002183 if (scissor != bounds) {
2184 // scissor doesn't match the screen's dimensions, so we
2185 // need to clear everything outside of it and enable
2186 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002187
Mathias Agopianf45c5102012-10-24 16:29:17 -07002188 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 const uint32_t height = displayDevice->getHeight();
2190 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002191 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002192 }
2193 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002194 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002195
Mathias Agopian85d751c2012-08-29 16:59:24 -07002196 /*
2197 * and then, render the layers targeted at the framebuffer
2198 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002199
Dan Stoza9e56aa02015-11-02 13:00:03 -08002200 ALOGV("Rendering client layers");
2201 const Transform& displayTransform = displayDevice->getTransform();
2202 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002203 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204 bool firstLayer = true;
2205 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2206 const Region clip(dirty.intersect(
2207 displayTransform.transform(layer->visibleRegion)));
2208 ALOGV("Layer: %s", layer->getName().string());
2209 ALOGV(" Composition type: %s",
2210 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002211 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 switch (layer->getCompositionType(hwcId)) {
2213 case HWC2::Composition::Cursor:
2214 case HWC2::Composition::Device:
2215 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002216 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2218 layer->isOpaque(state) && (state.alpha == 1.0f)
2219 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220 // never clear the very first layer since we're
2221 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002223 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002224 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 case HWC2::Composition::Client: {
2227 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002228 break;
2229 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002231 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002232 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 } else {
2234 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002235 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002237 }
2238 } else {
2239 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002241 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002243 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002245 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002246 }
2247 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002248
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002249 if (applyColorMatrix) {
2250 getRenderEngine().setupColorTransform(oldColorMatrix);
2251 }
2252
Mathias Agopianf45c5102012-10-24 16:29:17 -07002253 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002255 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256}
2257
Mathias Agopian3f844832013-08-07 21:24:32 -07002258void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002259 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002260 RenderEngine& engine(getRenderEngine());
2261 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262}
2263
Dan Stoza7d89d062015-04-30 13:29:25 -07002264status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002265 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002266 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002267 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002268{
Dan Stoza7d89d062015-04-30 13:29:25 -07002269 // add this layer to the current state list
2270 {
2271 Mutex::Autolock _l(mStateLock);
2272 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2273 return NO_MEMORY;
2274 }
2275 mCurrentState.layersSortedByZ.add(lbc);
2276 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2277 }
2278
Mathias Agopian96f08192010-06-02 23:28:45 -07002279 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002280 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002281
Dan Stoza7d89d062015-04-30 13:29:25 -07002282 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002283}
2284
Dan Stoza22851c32016-08-09 13:21:03 -07002285status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002287 sp<Layer> layer = weakLayer.promote();
2288 if (layer == nullptr) {
2289 // The layer has already been removed, carry on
2290 return NO_ERROR;
2291 }
2292
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002293 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2294 if (index >= 0) {
2295 mLayersPendingRemoval.push(layer);
2296 mLayersRemoved = true;
2297 setTransactionFlags(eTransactionNeeded);
2298 return NO_ERROR;
2299 }
2300 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301}
2302
Dan Stozac7014012014-02-14 15:03:43 -08002303uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002304 return android_atomic_release_load(&mTransactionFlags);
2305}
2306
Mathias Agopian3f844832013-08-07 21:24:32 -07002307uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2309}
2310
Mathias Agopian3f844832013-08-07 21:24:32 -07002311uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2313 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002314 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315 }
2316 return old;
2317}
2318
Mathias Agopian8b33f032012-07-24 20:43:54 -07002319void SurfaceFlinger::setTransactionState(
2320 const Vector<ComposerState>& state,
2321 const Vector<DisplayState>& displays,
2322 uint32_t flags)
2323{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002324 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002325 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002326 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002327
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002328 if (flags & eAnimation) {
2329 // For window updates that are part of an animation we must wait for
2330 // previous animation "frames" to be handled.
2331 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002332 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002333 if (CC_UNLIKELY(err != NO_ERROR)) {
2334 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002335 // caller after a few seconds.
2336 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2337 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002338 mAnimTransactionPending = false;
2339 break;
2340 }
2341 }
2342 }
2343
Mathias Agopiane57f2922012-08-09 16:29:12 -07002344 size_t count = displays.size();
2345 for (size_t i=0 ; i<count ; i++) {
2346 const DisplayState& s(displays[i]);
2347 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002348 }
2349
Mathias Agopiane57f2922012-08-09 16:29:12 -07002350 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002351 for (size_t i=0 ; i<count ; i++) {
2352 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002353 // Here we need to check that the interface we're given is indeed
2354 // one of our own. A malicious client could give us a NULL
2355 // IInterface, or one of its own or even one of our own but a
2356 // different type. All these situations would cause us to crash.
2357 //
2358 // NOTE: it would be better to use RTTI as we could directly check
2359 // that we have a Client*. however, RTTI is disabled in Android.
2360 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002361 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002362 if (binder != NULL) {
2363 String16 desc(binder->getInterfaceDescriptor());
2364 if (desc == ISurfaceComposerClient::descriptor) {
2365 sp<Client> client( static_cast<Client *>(s.client.get()) );
2366 transactionFlags |= setClientStateLocked(client, s.state);
2367 }
2368 }
2369 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002370 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002371
Robert Carr2a7dbb42016-05-24 11:41:28 -07002372 // If a synchronous transaction is explicitly requested without any changes,
2373 // force a transaction anyway. This can be used as a flush mechanism for
2374 // previous async transactions.
2375 if (transactionFlags == 0 && (flags & eSynchronous)) {
2376 transactionFlags = eTransactionNeeded;
2377 }
2378
Mathias Agopian386aa982011-11-07 21:58:03 -08002379 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002380 if (mInterceptor.isEnabled()) {
2381 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2382 }
Irvel468051e2016-06-13 16:44:44 -07002383
Mathias Agopian386aa982011-11-07 21:58:03 -08002384 // this triggers the transaction
2385 setTransactionFlags(transactionFlags);
2386
2387 // if this is a synchronous transaction, wait for it to take effect
2388 // before returning.
2389 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002390 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002391 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002392 if (flags & eAnimation) {
2393 mAnimTransactionPending = true;
2394 }
2395 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002396 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2397 if (CC_UNLIKELY(err != NO_ERROR)) {
2398 // just in case something goes wrong in SF, return to the
2399 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002400 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2401 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002402 break;
2403 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405 }
2406}
2407
Mathias Agopiane57f2922012-08-09 16:29:12 -07002408uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2409{
Jesse Hall9a143922012-10-04 16:29:19 -07002410 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2411 if (dpyIdx < 0)
2412 return 0;
2413
Mathias Agopiane57f2922012-08-09 16:29:12 -07002414 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002415 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002416 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002417 const uint32_t what = s.what;
2418 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002419 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002420 disp.surface = s.surface;
2421 flags |= eDisplayTransactionNeeded;
2422 }
2423 }
2424 if (what & DisplayState::eLayerStackChanged) {
2425 if (disp.layerStack != s.layerStack) {
2426 disp.layerStack = s.layerStack;
2427 flags |= eDisplayTransactionNeeded;
2428 }
2429 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002430 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002431 if (disp.orientation != s.orientation) {
2432 disp.orientation = s.orientation;
2433 flags |= eDisplayTransactionNeeded;
2434 }
2435 if (disp.frame != s.frame) {
2436 disp.frame = s.frame;
2437 flags |= eDisplayTransactionNeeded;
2438 }
2439 if (disp.viewport != s.viewport) {
2440 disp.viewport = s.viewport;
2441 flags |= eDisplayTransactionNeeded;
2442 }
2443 }
Michael Lentine47e45402014-07-18 15:34:25 -07002444 if (what & DisplayState::eDisplaySizeChanged) {
2445 if (disp.width != s.width) {
2446 disp.width = s.width;
2447 flags |= eDisplayTransactionNeeded;
2448 }
2449 if (disp.height != s.height) {
2450 disp.height = s.height;
2451 flags |= eDisplayTransactionNeeded;
2452 }
2453 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 }
2455 return flags;
2456}
2457
2458uint32_t SurfaceFlinger::setClientStateLocked(
2459 const sp<Client>& client,
2460 const layer_state_t& s)
2461{
2462 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002463 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002464 if (layer != 0) {
2465 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002466 bool geometryAppliesWithResize =
2467 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002468 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002469 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002470 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002471 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002472 }
2473 if (what & layer_state_t::eLayerChanged) {
2474 // NOTE: index needs to be calculated before we update the state
2475 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002476 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002477 mCurrentState.layersSortedByZ.removeAt(idx);
2478 mCurrentState.layersSortedByZ.add(layer);
2479 // we need traversal (state changed)
2480 // AND transaction (list changed)
2481 flags |= eTransactionNeeded|eTraversalNeeded;
2482 }
2483 }
2484 if (what & layer_state_t::eSizeChanged) {
2485 if (layer->setSize(s.w, s.h)) {
2486 flags |= eTraversalNeeded;
2487 }
2488 }
2489 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002491 flags |= eTraversalNeeded;
2492 }
2493 if (what & layer_state_t::eMatrixChanged) {
2494 if (layer->setMatrix(s.matrix))
2495 flags |= eTraversalNeeded;
2496 }
2497 if (what & layer_state_t::eTransparentRegionChanged) {
2498 if (layer->setTransparentRegionHint(s.transparentRegion))
2499 flags |= eTraversalNeeded;
2500 }
Dan Stoza23116082015-06-18 14:58:39 -07002501 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002502 if (layer->setFlags(s.flags, s.mask))
2503 flags |= eTraversalNeeded;
2504 }
2505 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002506 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002507 flags |= eTraversalNeeded;
2508 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002509 if (what & layer_state_t::eFinalCropChanged) {
2510 if (layer->setFinalCrop(s.finalCrop))
2511 flags |= eTraversalNeeded;
2512 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002513 if (what & layer_state_t::eLayerStackChanged) {
2514 // NOTE: index needs to be calculated before we update the state
2515 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002516 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002517 mCurrentState.layersSortedByZ.removeAt(idx);
2518 mCurrentState.layersSortedByZ.add(layer);
2519 // we need traversal (state changed)
2520 // AND transaction (list changed)
2521 flags |= eTransactionNeeded|eTraversalNeeded;
2522 }
2523 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002524 if (what & layer_state_t::eDeferTransaction) {
2525 layer->deferTransactionUntil(s.handle, s.frameNumber);
2526 // We don't trigger a traversal here because if no other state is
2527 // changed, we don't want this to cause any more work
2528 }
Robert Carrc3574f72016-03-24 12:19:32 -07002529 if (what & layer_state_t::eOverrideScalingModeChanged) {
2530 layer->setOverrideScalingMode(s.overrideScalingMode);
2531 // We don't trigger a traversal here because if no other state is
2532 // changed, we don't want this to cause any more work
2533 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002534 }
2535 return flags;
2536}
2537
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002538status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002539 const String8& name,
2540 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002541 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2542 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002544 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002545 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002546 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002547 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002548 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002549
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002550 status_t result = NO_ERROR;
2551
2552 sp<Layer> layer;
2553
Mathias Agopian3165cc22012-08-08 19:42:09 -07002554 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2555 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002556 result = createNormalLayer(client,
2557 name, w, h, flags, format,
2558 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002560 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002561 result = createDimLayer(client,
2562 name, w, h, flags,
2563 handle, gbp, &layer);
2564 break;
2565 default:
2566 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 break;
2568 }
2569
Dan Stoza7d89d062015-04-30 13:29:25 -07002570 if (result != NO_ERROR) {
2571 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002573
2574 result = addClientLayer(client, *handle, *gbp, layer);
2575 if (result != NO_ERROR) {
2576 return result;
2577 }
Irvelffc9efc2016-07-27 15:16:37 -07002578 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002579
2580 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002581 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582}
2583
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002584status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2585 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2586 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587{
2588 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002589 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 case PIXEL_FORMAT_TRANSPARENT:
2591 case PIXEL_FORMAT_TRANSLUCENT:
2592 format = PIXEL_FORMAT_RGBA_8888;
2593 break;
2594 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002595 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 break;
2597 }
2598
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002599 *outLayer = new Layer(this, client, name, w, h, flags);
2600 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2601 if (err == NO_ERROR) {
2602 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002603 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002605
2606 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2607 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608}
2609
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002610status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2611 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2612 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002614 *outLayer = new LayerDim(this, client, name, w, h, flags);
2615 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002616 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002617 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002618}
2619
Mathias Agopianac9fa422013-02-11 16:40:36 -08002620status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621{
Mathias Agopian67106042013-03-14 19:18:13 -07002622 // called by the window manager when it wants to remove a Layer
2623 status_t err = NO_ERROR;
2624 sp<Layer> l(client->getLayerUser(handle));
2625 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002626 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002627 err = removeLayer(l);
2628 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2629 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002630 }
2631 return err;
2632}
2633
Mathias Agopian13127d82013-03-05 17:47:11 -08002634status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002635{
Mathias Agopian67106042013-03-14 19:18:13 -07002636 // called by ~LayerCleaner() when all references to the IBinder (handle)
2637 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002638 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639}
2640
Mathias Agopianb60314a2012-04-10 22:09:54 -07002641// ---------------------------------------------------------------------------
2642
Andy McFadden13a082e2012-08-24 10:16:42 -07002643void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002644 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002645 Vector<ComposerState> state;
2646 Vector<DisplayState> displays;
2647 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002648 d.what = DisplayState::eDisplayProjectionChanged |
2649 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002650 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002651 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002652 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002653 d.frame.makeInvalid();
2654 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002655 d.width = 0;
2656 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002657 displays.add(d);
2658 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002659 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002660
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2662 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002663 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002664}
2665
2666void SurfaceFlinger::initializeDisplays() {
2667 class MessageScreenInitialized : public MessageBase {
2668 SurfaceFlinger* flinger;
2669 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002670 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002671 virtual bool handler() {
2672 flinger->onInitializeDisplays();
2673 return true;
2674 }
2675 };
2676 sp<MessageBase> msg = new MessageScreenInitialized(this);
2677 postMessageAsync(msg); // we may be called from main thread, use async message
2678}
2679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002680void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2681 int mode) {
2682 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2683 this);
2684 int32_t type = hw->getDisplayType();
2685 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002686
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002687 if (mode == currentMode) {
2688 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002689 return;
2690 }
2691
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002692 hw->setPowerMode(mode);
2693 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2694 ALOGW("Trying to set power mode for virtual display");
2695 return;
2696 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002697
Irvelffc9efc2016-07-27 15:16:37 -07002698 if (mInterceptor.isEnabled()) {
2699 Mutex::Autolock _l(mStateLock);
2700 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2701 if (idx < 0) {
2702 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2703 return;
2704 }
2705 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2706 }
2707
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002708 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002709 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002710 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002711 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2712 // FIXME: eventthread only knows about the main display right now
2713 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002714 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002717 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002718 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002719 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002720
2721 struct sched_param param = {0};
2722 param.sched_priority = 1;
2723 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2724 ALOGW("Couldn't set SCHED_FIFO on display on");
2725 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002726 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002727 // Turn off the display
2728 struct sched_param param = {0};
2729 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2730 ALOGW("Couldn't set SCHED_OTHER on display off");
2731 }
2732
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002733 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002734 disableHardwareVsync(true); // also cancels any in-progress resync
2735
Mathias Agopiancde87a32012-09-13 14:09:01 -07002736 // FIXME: eventthread only knows about the main display right now
2737 mEventThread->onScreenReleased();
2738 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002739
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002740 getHwComposer().setPowerMode(type, mode);
2741 mVisibleRegionsDirty = true;
2742 // from this point on, SF will stop drawing on this display
2743 } else {
2744 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002745 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002746}
2747
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002748void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2749 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002750 SurfaceFlinger& mFlinger;
2751 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002752 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002753 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002754 MessageSetPowerMode(SurfaceFlinger& flinger,
2755 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2756 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002757 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002758 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002759 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002760 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002761 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002762 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002763 ALOGW("Attempt to set power mode = %d for virtual display",
2764 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002765 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002766 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002767 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002768 return true;
2769 }
2770 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002771 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002772 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002773}
2774
2775// ---------------------------------------------------------------------------
2776
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2778{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002780
Mathias Agopianbd115332013-04-18 16:41:04 -07002781 IPCThreadState* ipc = IPCThreadState::self();
2782 const int pid = ipc->getCallingPid();
2783 const int uid = ipc->getCallingUid();
2784 if ((uid != AID_SHELL) &&
2785 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002786 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002787 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002789 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002790 // (this would indicate SF is stuck, but we want to be able to
2791 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002792 status_t err = mStateLock.timedLock(s2ns(1));
2793 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002794 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002795 result.appendFormat(
2796 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2797 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002798 }
2799
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002800 bool dumpAll = true;
2801 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002802 size_t numArgs = args.size();
2803 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002804 if ((index < numArgs) &&
2805 (args[index] == String16("--list"))) {
2806 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002807 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002808 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002809 }
2810
2811 if ((index < numArgs) &&
2812 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002813 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002814 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002815 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002816 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002817
2818 if ((index < numArgs) &&
2819 (args[index] == String16("--latency-clear"))) {
2820 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002821 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002822 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002823 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002824
2825 if ((index < numArgs) &&
2826 (args[index] == String16("--dispsync"))) {
2827 index++;
2828 mPrimaryDispSync.dump(result);
2829 dumpAll = false;
2830 }
Dan Stozab90cf072015-03-05 11:05:59 -08002831
2832 if ((index < numArgs) &&
2833 (args[index] == String16("--static-screen"))) {
2834 index++;
2835 dumpStaticScreenStats(result);
2836 dumpAll = false;
2837 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002838
2839 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002840 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002841 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002842 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002843 dumpAll = false;
2844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002846
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002847 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002848 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002849 }
2850
Mathias Agopian9795c422009-08-26 16:36:26 -07002851 if (locked) {
2852 mStateLock.unlock();
2853 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
2855 write(fd, result.string(), result.size());
2856 return NO_ERROR;
2857}
2858
Dan Stozac7014012014-02-14 15:03:43 -08002859void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2860 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002861{
2862 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2863 const size_t count = currentLayers.size();
2864 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002865 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002866 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002867 }
2868}
2869
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002870void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002871 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002872{
2873 String8 name;
2874 if (index < args.size()) {
2875 name = String8(args[index]);
2876 index++;
2877 }
2878
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2880 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002881 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002882
2883 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002884 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002885 } else {
2886 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2887 const size_t count = currentLayers.size();
2888 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002889 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002890 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002891 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002892 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002893 }
2894 }
2895}
2896
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002897void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002898 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002899{
2900 String8 name;
2901 if (index < args.size()) {
2902 name = String8(args[index]);
2903 index++;
2904 }
2905
2906 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2907 const size_t count = currentLayers.size();
2908 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002909 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002910 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002911 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002912 }
2913 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002914
Svetoslavd85084b2014-03-20 10:28:31 -07002915 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002916}
2917
Jamie Gennis6547ff42013-07-16 20:12:42 -07002918// This should only be called from the main thread. Otherwise it would need
2919// the lock and should use mCurrentState rather than mDrawingState.
2920void SurfaceFlinger::logFrameStats() {
2921 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2922 const size_t count = drawingLayers.size();
2923 for (size_t i=0 ; i<count ; i++) {
2924 const sp<Layer>& layer(drawingLayers[i]);
2925 layer->logFrameStats();
2926 }
2927
2928 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2929}
2930
Andy McFadden4803b742012-09-24 19:07:20 -07002931/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2932{
2933 static const char* config =
2934 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002935#ifdef HAS_CONTEXT_PRIORITY
2936 " HAS_CONTEXT_PRIORITY"
2937#endif
2938#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2939 " NEVER_DEFAULT_TO_ASYNC_MODE"
2940#endif
2941#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2942 " TARGET_DISABLE_TRIPLE_BUFFERING"
2943#endif
2944 "]";
2945 result.append(config);
2946}
2947
Dan Stozab90cf072015-03-05 11:05:59 -08002948void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2949{
2950 result.appendFormat("Static screen stats:\n");
2951 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2952 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2953 float percent = 100.0f *
2954 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2955 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2956 b + 1, bucketTimeSec, percent);
2957 }
2958 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2959 float percent = 100.0f *
2960 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2961 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2962 NUM_BUCKETS - 1, bucketTimeSec, percent);
2963}
2964
Dan Stozae77c7662016-05-13 11:37:28 -07002965void SurfaceFlinger::recordBufferingStats(const char* layerName,
2966 std::vector<OccupancyTracker::Segment>&& history) {
2967 Mutex::Autolock lock(mBufferingStatsMutex);
2968 auto& stats = mBufferingStats[layerName];
2969 for (const auto& segment : history) {
2970 if (!segment.usedThirdBuffer) {
2971 stats.twoBufferTime += segment.totalTime;
2972 }
2973 if (segment.occupancyAverage < 1.0f) {
2974 stats.doubleBufferedTime += segment.totalTime;
2975 } else if (segment.occupancyAverage < 2.0f) {
2976 stats.tripleBufferedTime += segment.totalTime;
2977 }
2978 ++stats.numSegments;
2979 stats.totalTime += segment.totalTime;
2980 }
2981}
2982
Brian Andersond6927fb2016-07-23 23:37:30 -07002983void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
2984 result.appendFormat("Layer frame timestamps:\n");
2985
2986 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2987 const size_t count = currentLayers.size();
2988 for (size_t i=0 ; i<count ; i++) {
2989 currentLayers[i]->dumpFrameEvents(result);
2990 }
2991}
2992
Dan Stozae77c7662016-05-13 11:37:28 -07002993void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2994 result.append("Buffering stats:\n");
2995 result.append(" [Layer name] <Active time> <Two buffer> "
2996 "<Double buffered> <Triple buffered>\n");
2997 Mutex::Autolock lock(mBufferingStatsMutex);
2998 typedef std::tuple<std::string, float, float, float> BufferTuple;
2999 std::map<float, BufferTuple, std::greater<float>> sorted;
3000 for (const auto& statsPair : mBufferingStats) {
3001 const char* name = statsPair.first.c_str();
3002 const BufferingStats& stats = statsPair.second;
3003 if (stats.numSegments == 0) {
3004 continue;
3005 }
3006 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3007 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3008 stats.totalTime;
3009 float doubleBufferRatio = static_cast<float>(
3010 stats.doubleBufferedTime) / stats.totalTime;
3011 float tripleBufferRatio = static_cast<float>(
3012 stats.tripleBufferedTime) / stats.totalTime;
3013 sorted.insert({activeTime, {name, twoBufferRatio,
3014 doubleBufferRatio, tripleBufferRatio}});
3015 }
3016 for (const auto& sortedPair : sorted) {
3017 float activeTime = sortedPair.first;
3018 const BufferTuple& values = sortedPair.second;
3019 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3020 std::get<0>(values).c_str(), activeTime,
3021 std::get<1>(values), std::get<2>(values),
3022 std::get<3>(values));
3023 }
3024 result.append("\n");
3025}
3026
3027
Mathias Agopian74d211a2013-04-22 16:55:35 +02003028void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3029 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003030{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003031 bool colorize = false;
3032 if (index < args.size()
3033 && (args[index] == String16("--color"))) {
3034 colorize = true;
3035 index++;
3036 }
3037
3038 Colorizer colorizer(colorize);
3039
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003040 // figure out if we're stuck somewhere
3041 const nsecs_t now = systemTime();
3042 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3043 const nsecs_t inTransaction(mDebugInTransaction);
3044 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3045 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3046
3047 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003048 * Dump library configuration.
3049 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003050
3051 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003052 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003053 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003054 appendSfConfigString(result);
3055 appendUiConfigString(result);
3056 appendGuiConfigString(result);
3057 result.append("\n");
3058
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003059 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003060 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003061 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003062 result.append(SyncFeatures::getInstance().toString());
3063 result.append("\n");
3064
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3066
Andy McFadden41d67d72014-04-25 16:58:34 -07003067 colorizer.bold(result);
3068 result.append("DispSync configuration: ");
3069 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003070 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3071 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003072 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3073 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003074 result.append("\n");
3075
Dan Stozab90cf072015-03-05 11:05:59 -08003076 // Dump static screen stats
3077 result.append("\n");
3078 dumpStaticScreenStats(result);
3079 result.append("\n");
3080
Dan Stozae77c7662016-05-13 11:37:28 -07003081 dumpBufferingStats(result);
3082
Andy McFadden4803b742012-09-24 19:07:20 -07003083 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003084 * Dump the visible layer list
3085 */
3086 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3087 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003088 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003089 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003090 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003091 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003092 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003093 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003094 }
3095
3096 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003097 * Dump Display state
3098 */
3099
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003100 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003101 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003102 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003103 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3104 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003105 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003106 }
3107
3108 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003109 * Dump SurfaceFlinger global state
3110 */
3111
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003112 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003113 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003114 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003115
Mathias Agopian888c8222012-08-04 21:10:38 -07003116 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003117 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003118
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003119 colorizer.bold(result);
3120 result.appendFormat("EGL implementation : %s\n",
3121 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3122 colorizer.reset(result);
3123 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003124 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003125
Mathias Agopian875d8e12013-06-07 15:35:48 -07003126 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003127
Mathias Agopian42977342012-08-05 00:40:46 -07003128 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003129 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3130 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003131 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003132 " last eglSwapBuffers() time: %f us\n"
3133 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003134 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135 " refresh-rate : %f fps\n"
3136 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003137 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003138 " gpu_to_cpu_unsupported : %d\n"
3139 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003140 mLastSwapBufferTime/1000.0,
3141 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003142 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003143 1e9 / activeConfig->getVsyncPeriod(),
3144 activeConfig->getDpiX(),
3145 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003146 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003147
Mathias Agopian74d211a2013-04-22 16:55:35 +02003148 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003149 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150
Mathias Agopian74d211a2013-04-22 16:55:35 +02003151 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003152 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003153
3154 /*
3155 * VSYNC state
3156 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003157 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003158 result.append("\n");
3159
3160 /*
3161 * HWC layer minidump
3162 */
3163 for (size_t d = 0; d < mDisplays.size(); d++) {
3164 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3165 int32_t hwcId = displayDevice->getHwcDisplayId();
3166 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3167 continue;
3168 }
3169
3170 result.appendFormat("Display %d HWC layers:\n", hwcId);
3171 Layer::miniDumpHeader(result);
3172 for (size_t l = 0; l < count; l++) {
3173 const sp<Layer>& layer(currentLayers[l]);
3174 layer->miniDump(result, hwcId);
3175 }
3176 result.append("\n");
3177 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003178
3179 /*
3180 * Dump HWComposer state
3181 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003182 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003183 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003184 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003185 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003186 result.appendFormat(" h/w composer %s\n",
3187 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003188 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003189
3190 /*
3191 * Dump gralloc state
3192 */
3193 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3194 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003195}
3196
Mathias Agopian13127d82013-03-05 17:47:11 -08003197const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003198SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003199 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003200 wp<IBinder> dpy;
3201 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3202 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3203 dpy = mDisplays.keyAt(i);
3204 break;
3205 }
3206 }
3207 if (dpy == NULL) {
3208 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3209 // Just use the primary display so we have something to return
3210 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3211 }
3212 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003213}
3214
Keun young Park63f165f2012-08-31 10:53:36 -07003215bool SurfaceFlinger::startDdmConnection()
3216{
3217 void* libddmconnection_dso =
3218 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3219 if (!libddmconnection_dso) {
3220 return false;
3221 }
3222 void (*DdmConnection_start)(const char* name);
3223 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003224 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003225 if (!DdmConnection_start) {
3226 dlclose(libddmconnection_dso);
3227 return false;
3228 }
3229 (*DdmConnection_start)(getServiceName());
3230 return true;
3231}
3232
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003233status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 switch (code) {
3235 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003236 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003237 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003239 case CLEAR_ANIMATION_FRAME_STATS:
3240 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003241 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003242 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 {
3244 // codes that require permission check
3245 IPCThreadState* ipc = IPCThreadState::self();
3246 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003247 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003248 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003249 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003250 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003251 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003253 break;
3254 }
3255 case CAPTURE_SCREEN:
3256 {
3257 // codes that require permission check
3258 IPCThreadState* ipc = IPCThreadState::self();
3259 const int pid = ipc->getCallingPid();
3260 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003261 if ((uid != AID_GRAPHICS) &&
3262 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003263 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003264 return PERMISSION_DENIED;
3265 }
3266 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003269 return OK;
3270}
3271
3272status_t SurfaceFlinger::onTransact(
3273 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3274{
3275 status_t credentialCheck = CheckTransactCodeCredentials(code);
3276 if (credentialCheck != OK) {
3277 return credentialCheck;
3278 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003279
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3281 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003282 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003283 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003284 IPCThreadState* ipc = IPCThreadState::self();
3285 const int pid = ipc->getCallingPid();
3286 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003287 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003288 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 return PERMISSION_DENIED;
3290 }
3291 int n;
3292 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003293 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003294 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295 return NO_ERROR;
3296 case 1002: // SHOW_UPDATES
3297 n = data.readInt32();
3298 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003299 invalidateHwcGeometry();
3300 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003303 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003304 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003306 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307 setTransactionFlags(
3308 eTransactionNeeded|
3309 eDisplayTransactionNeeded|
3310 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003311 return NO_ERROR;
3312 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003313 case 1006:{ // send empty update
3314 signalRefresh();
3315 return NO_ERROR;
3316 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003317 case 1008: // toggle use of hw composer
3318 n = data.readInt32();
3319 mDebugDisableHWC = n ? 1 : 0;
3320 invalidateHwcGeometry();
3321 repaintEverything();
3322 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003323 case 1009: // toggle use of transform hint
3324 n = data.readInt32();
3325 mDebugDisableTransformHint = n ? 1 : 0;
3326 invalidateHwcGeometry();
3327 repaintEverything();
3328 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003330 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 reply->writeInt32(0);
3332 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003333 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003334 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 return NO_ERROR;
3336 case 1013: {
3337 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003338 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3339 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003340 return NO_ERROR;
3341 }
3342 case 1014: {
3343 // daltonize
3344 n = data.readInt32();
3345 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003346 case 1:
3347 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3348 break;
3349 case 2:
3350 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3351 break;
3352 case 3:
3353 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3354 break;
3355 default:
3356 mDaltonizer.setType(ColorBlindnessType::None);
3357 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003358 }
3359 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003360 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003361 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003362 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003363 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003364 invalidateHwcGeometry();
3365 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003366 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003368 case 1015: {
3369 // apply a color matrix
3370 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003371 if (n) {
3372 // color matrix is sent as mat3 matrix followed by vec3
3373 // offset, then packed into a mat4 where the last row is
3374 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003375 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003376 for (size_t j = 0; j < 4; j++) {
3377 mColorMatrix[i][j] = data.readFloat();
3378 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003379 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003380 } else {
3381 mColorMatrix = mat4();
3382 }
3383 invalidateHwcGeometry();
3384 repaintEverything();
3385 return NO_ERROR;
3386 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003387 // This is an experimental interface
3388 // Needs to be shifted to proper binder interface when we productize
3389 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003390 n = data.readInt32();
3391 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003392 return NO_ERROR;
3393 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003394 case 1017: {
3395 n = data.readInt32();
3396 mForceFullDamage = static_cast<bool>(n);
3397 return NO_ERROR;
3398 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003399 case 1018: { // Modify Choreographer's phase offset
3400 n = data.readInt32();
3401 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3402 return NO_ERROR;
3403 }
3404 case 1019: { // Modify SurfaceFlinger's phase offset
3405 n = data.readInt32();
3406 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3407 return NO_ERROR;
3408 }
Irvel468051e2016-06-13 16:44:44 -07003409 case 1020: { // Layer updates interceptor
3410 n = data.readInt32();
3411 if (n) {
3412 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003413 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003414 }
3415 else{
3416 ALOGV("Interceptor disabled");
3417 mInterceptor.disable();
3418 }
3419 return NO_ERROR;
3420 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003421 case 1021: { // Disable HWC virtual displays
3422 n = data.readInt32();
3423 mUseHwcVirtualDisplays = !n;
3424 return NO_ERROR;
3425 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003426 }
3427 }
3428 return err;
3429}
3430
Mathias Agopian53331da2011-08-22 21:44:41 -07003431void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003432 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003433 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003434}
3435
Mathias Agopian59119e62010-10-11 12:37:43 -07003436// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003437// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003438// ---------------------------------------------------------------------------
3439
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003440/* The code below is here to handle b/8734824
3441 *
3442 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003443 * from the surfaceflinger thread to the calling binder thread, where they
3444 * are executed. This allows the calling thread in the calling process to be
3445 * reused and not depend on having "enough" binder threads to handle the
3446 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003447 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003448class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003449 /* Parts of GraphicProducerWrapper are run on two different threads,
3450 * communicating by sending messages via Looper but also by shared member
3451 * data. Coherence maintenance is subtle and in places implicit (ugh).
3452 *
3453 * Don't rely on Looper's sendMessage/handleMessage providing
3454 * release/acquire semantics for any data not actually in the Message.
3455 * Data going from surfaceflinger to binder threads needs to be
3456 * synchronized explicitly.
3457 *
3458 * Barrier open/wait do provide release/acquire semantics. This provides
3459 * implicit synchronization for data coming back from binder to
3460 * surfaceflinger threads.
3461 */
3462
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003463 sp<IGraphicBufferProducer> impl;
3464 sp<Looper> looper;
3465 status_t result;
3466 bool exitPending;
3467 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003468 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003469 uint32_t code;
3470 Parcel const* data;
3471 Parcel* reply;
3472
3473 enum {
3474 MSG_API_CALL,
3475 MSG_EXIT
3476 };
3477
3478 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003479 * Called on surfaceflinger thread. This is called by our "fake"
3480 * BpGraphicBufferProducer. We package the data and reply Parcel and
3481 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003482 */
3483 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003484 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003485 this->code = code;
3486 this->data = &data;
3487 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003488 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003489 // if we've exited, we run the message synchronously right here.
3490 // note (JH): as far as I can tell from looking at the code, this
3491 // never actually happens. if it does, i'm not sure if it happens
3492 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003493 handleMessage(Message(MSG_API_CALL));
3494 } else {
3495 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003496 // Prevent stores to this->{code, data, reply} from being
3497 // reordered later than the construction of Message.
3498 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003499 looper->sendMessage(this, Message(MSG_API_CALL));
3500 barrier.wait();
3501 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003502 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003503 }
3504
3505 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003506 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003507 * call the real BpGraphicBufferProducer.
3508 */
3509 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003510 int what = message.what;
3511 // Prevent reads below from happening before the read from Message
3512 atomic_thread_fence(memory_order_acquire);
3513 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003514 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003515 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003516 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003517 exitRequested = true;
3518 }
3519 }
3520
3521public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003522 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003523 : impl(impl),
3524 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003525 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003526 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003527 exitRequested(false),
3528 code(0),
3529 data(NULL),
3530 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003531 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003532
Jesse Hallb154c422014-07-13 12:47:02 -07003533 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003534 status_t waitForResponse() {
3535 do {
3536 looper->pollOnce(-1);
3537 } while (!exitRequested);
3538 return result;
3539 }
3540
Jesse Hallb154c422014-07-13 12:47:02 -07003541 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003542 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003543 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003544 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003545 // Ensure this->result is visible to the binder thread before it
3546 // handles the message.
3547 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003548 looper->sendMessage(this, Message(MSG_EXIT));
3549 }
3550};
3551
3552
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003553status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3554 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003555 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003556 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003557 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003558
3559 if (CC_UNLIKELY(display == 0))
3560 return BAD_VALUE;
3561
3562 if (CC_UNLIKELY(producer == 0))
3563 return BAD_VALUE;
3564
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003565 // if we have secure windows on this display, never allow the screen capture
3566 // unless the producer interface is local (i.e.: we can take a screenshot for
3567 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003568 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003569
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003570 // Convert to surfaceflinger's internal rotation type.
3571 Transform::orientation_flags rotationFlags;
3572 switch (rotation) {
3573 case ISurfaceComposer::eRotateNone:
3574 rotationFlags = Transform::ROT_0;
3575 break;
3576 case ISurfaceComposer::eRotate90:
3577 rotationFlags = Transform::ROT_90;
3578 break;
3579 case ISurfaceComposer::eRotate180:
3580 rotationFlags = Transform::ROT_180;
3581 break;
3582 case ISurfaceComposer::eRotate270:
3583 rotationFlags = Transform::ROT_270;
3584 break;
3585 default:
3586 rotationFlags = Transform::ROT_0;
3587 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3588 break;
3589 }
3590
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003591 class MessageCaptureScreen : public MessageBase {
3592 SurfaceFlinger* flinger;
3593 sp<IBinder> display;
3594 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003595 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003596 uint32_t reqWidth, reqHeight;
3597 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003598 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003599 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003600 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003601 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003602 public:
3603 MessageCaptureScreen(SurfaceFlinger* flinger,
3604 const sp<IBinder>& display,
3605 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003606 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003607 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003608 bool useIdentityTransform,
3609 Transform::orientation_flags rotation,
3610 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003611 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003612 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003613 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003614 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003615 rotation(rotation), result(PERMISSION_DENIED),
3616 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003617 {
3618 }
3619 status_t getResult() const {
3620 return result;
3621 }
3622 virtual bool handler() {
3623 Mutex::Autolock _l(flinger->mStateLock);
3624 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003625 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003626 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003627 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003628 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003629 return true;
3630 }
3631 };
3632
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003633 // this creates a "fake" BBinder which will serve as a "fake" remote
3634 // binder to receive the marshaled calls and forward them to the
3635 // real remote (a BpGraphicBufferProducer)
3636 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3637
3638 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3639 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003640 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003641 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003642 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003643 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003644
3645 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003646 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003647 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003648 }
3649 return res;
3650}
3651
Mathias Agopian180f10d2013-04-10 22:55:41 -07003652
3653void SurfaceFlinger::renderScreenImplLocked(
3654 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003655 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003656 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003657 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003658{
3659 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003660 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003661
3662 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003663 const int32_t hw_w = hw->getWidth();
3664 const int32_t hw_h = hw->getHeight();
3665 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003666 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003667
Dan Stozac1879002014-05-22 15:59:05 -07003668 // if a default or invalid sourceCrop is passed in, set reasonable values
3669 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3670 !sourceCrop.isValid()) {
3671 sourceCrop.setLeftTop(Point(0, 0));
3672 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3673 }
3674
3675 // ensure that sourceCrop is inside screen
3676 if (sourceCrop.left < 0) {
3677 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3678 }
Dan Stozabe31f442014-06-11 11:20:54 -07003679 if (sourceCrop.right > hw_w) {
3680 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003681 }
3682 if (sourceCrop.top < 0) {
3683 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3684 }
Dan Stozabe31f442014-06-11 11:20:54 -07003685 if (sourceCrop.bottom > hw_h) {
3686 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003687 }
3688
Mathias Agopian180f10d2013-04-10 22:55:41 -07003689 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003690 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003691
3692 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003693 engine.setViewportAndProjection(
3694 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003695 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003696
3697 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003698 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003699
3700 const LayerVector& layers( mDrawingState.layersSortedByZ );
3701 const size_t count = layers.size();
3702 for (size_t i=0 ; i<count ; ++i) {
3703 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003704 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003705 if (state.layerStack == hw->getLayerStack()) {
3706 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3707 if (layer->isVisible()) {
3708 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003709 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003710 if (filtering) layer->setFiltering(false);
3711 }
3712 }
3713 }
3714 }
3715
Mathias Agopian931bda12013-08-28 18:11:46 -07003716 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003717}
3718
3719
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003720status_t SurfaceFlinger::captureScreenImplLocked(
3721 const sp<const DisplayDevice>& hw,
3722 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003723 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003724 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003725 bool useIdentityTransform, Transform::orientation_flags rotation,
3726 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003727{
3728 ATRACE_CALL();
3729
Mathias Agopian180f10d2013-04-10 22:55:41 -07003730 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003731 uint32_t hw_w = hw->getWidth();
3732 uint32_t hw_h = hw->getHeight();
3733
3734 if (rotation & Transform::ROT_90) {
3735 std::swap(hw_w, hw_h);
3736 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003737
Mathias Agopian180f10d2013-04-10 22:55:41 -07003738 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3739 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3740 reqWidth, reqHeight, hw_w, hw_h);
3741 return BAD_VALUE;
3742 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003743
Mathias Agopian180f10d2013-04-10 22:55:41 -07003744 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3745 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3746
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003747 bool secureLayerIsVisible = false;
3748 const LayerVector& layers(mDrawingState.layersSortedByZ);
3749 const size_t count = layers.size();
3750 for (size_t i = 0 ; i < count ; ++i) {
3751 const sp<Layer>& layer(layers[i]);
3752 const Layer::State& state(layer->getDrawingState());
3753 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3754 state.z <= maxLayerZ && layer->isVisible() &&
3755 layer->isSecure()) {
3756 secureLayerIsVisible = true;
3757 }
3758 }
3759
3760 if (!isLocalScreenshot && secureLayerIsVisible) {
3761 ALOGW("FB is protected: PERMISSION_DENIED");
3762 return PERMISSION_DENIED;
3763 }
3764
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003765 // create a surface (because we're a producer, and we need to
3766 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003767 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003768
3769 // Put the screenshot Surface into async mode so that
3770 // Layer::headFenceHasSignaled will always return true and we'll latch the
3771 // first buffer regardless of whether or not its acquire fence has
3772 // signaled. This is needed to avoid a race condition in the rotation
3773 // animation. See b/30209608
3774 sur->setAsyncMode(true);
3775
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003776 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003777
Michael Lentine5a16a622015-05-21 13:48:24 -07003778 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3779 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003780 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3781 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003782
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003783 int err = 0;
3784 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003785 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003786 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3787 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003788
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003789 if (err == NO_ERROR) {
3790 ANativeWindowBuffer* buffer;
3791 /* TODO: Once we have the sync framework everywhere this can use
3792 * server-side waits on the fence that dequeueBuffer returns.
3793 */
3794 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3795 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003796 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003797 // create an EGLImage from the buffer so we can later
3798 // turn it into a texture
3799 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3800 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3801 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003802 // this binds the given EGLImage as a framebuffer for the
3803 // duration of this scope.
3804 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3805 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003806 // this will in fact render into our dequeued buffer
3807 // via an FBO, which means we didn't have to create
3808 // an EGLSurface and therefore we're not
3809 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003810 renderScreenImplLocked(
3811 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3812 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003813
Riley Andrews86639902014-08-15 12:27:24 -07003814 // Attempt to create a sync khr object that can produce a sync point. If that
3815 // isn't available, create a non-dupable sync object in the fallback path and
3816 // wait on it directly.
3817 EGLSyncKHR sync;
3818 if (!DEBUG_SCREENSHOTS) {
3819 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003820 // native fence fd will not be populated until flush() is done.
3821 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003822 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003823 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003824 }
Riley Andrews86639902014-08-15 12:27:24 -07003825 if (sync != EGL_NO_SYNC_KHR) {
3826 // get the sync fd
3827 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3828 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3829 ALOGW("captureScreen: failed to dup sync khr object");
3830 syncFd = -1;
3831 }
3832 eglDestroySyncKHR(mEGLDisplay, sync);
3833 } else {
3834 // fallback path
3835 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3836 if (sync != EGL_NO_SYNC_KHR) {
3837 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3838 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3839 EGLint eglErr = eglGetError();
3840 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3841 ALOGW("captureScreen: fence wait timed out");
3842 } else {
3843 ALOGW_IF(eglErr != EGL_SUCCESS,
3844 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3845 }
3846 eglDestroySyncKHR(mEGLDisplay, sync);
3847 } else {
3848 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3849 }
3850 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003851 if (DEBUG_SCREENSHOTS) {
3852 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3853 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3854 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3855 hw, minLayerZ, maxLayerZ);
3856 delete [] pixels;
3857 }
3858
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003859 } else {
3860 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3861 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003862 window->cancelBuffer(window, buffer, syncFd);
3863 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003864 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003865 // destroy our image
3866 eglDestroyImageKHR(mEGLDisplay, image);
3867 } else {
3868 result = BAD_VALUE;
3869 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003870 if (buffer) {
3871 // queueBuffer takes ownership of syncFd
3872 result = window->queueBuffer(window, buffer, syncFd);
3873 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003874 }
3875 } else {
3876 result = BAD_VALUE;
3877 }
3878 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3879 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003880
Mathias Agopian74c40c02010-09-29 13:02:36 -07003881 return result;
3882}
3883
Mathias Agopiand5556842013-09-19 17:08:37 -07003884void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3885 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003886 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003887 for (size_t y=0 ; y<h ; y++) {
3888 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3889 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003890 if (p[x] != 0xFF000000) return;
3891 }
3892 }
3893 ALOGE("*** we just took a black screenshot ***\n"
3894 "requested minz=%d, maxz=%d, layerStack=%d",
3895 minLayerZ, maxLayerZ, hw->getLayerStack());
3896 const LayerVector& layers( mDrawingState.layersSortedByZ );
3897 const size_t count = layers.size();
3898 for (size_t i=0 ; i<count ; ++i) {
3899 const sp<Layer>& layer(layers[i]);
3900 const Layer::State& state(layer->getDrawingState());
3901 const bool visible = (state.layerStack == hw->getLayerStack())
3902 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3903 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003904 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003905 visible ? '+' : '-',
3906 i, layer->getName().string(), state.layerStack, state.z,
3907 layer->isVisible(), state.flags, state.alpha);
3908 }
3909 }
3910}
3911
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003912// ---------------------------------------------------------------------------
3913
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003914SurfaceFlinger::LayerVector::LayerVector() {
3915}
3916
3917SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003918 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003919}
3920
3921int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3922 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003923{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003924 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003925 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3926 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003927
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003928 uint32_t ls = l->getCurrentState().layerStack;
3929 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003930 if (ls != rs)
3931 return ls - rs;
3932
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003933 uint32_t lz = l->getCurrentState().z;
3934 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003935 if (lz != rz)
3936 return lz - rz;
3937
3938 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003939}
3940
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003942
3943
3944#if defined(__gl_h_)
3945#error "don't include gl/gl.h in this file"
3946#endif
3947
3948#if defined(__gl2_h_)
3949#error "don't include gl2/gl2.h in this file"
3950#endif