blob: 88a221d79af689e808766d01dd998e633bd67332 [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
Dan Stoza7f7da322014-05-02 15:26:25 -0700569status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
570 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700571 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700572 return BAD_VALUE;
573 }
574
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500575 if (!display.get())
576 return NAME_NOT_FOUND;
577
Jesse Hall692c7232012-11-08 15:41:56 -0800578 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700579 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800580 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700581 type = i;
582 break;
583 }
584 }
585
586 if (type < 0) {
587 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700588 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700589
Mathias Agopian8b736f12012-08-13 17:54:26 -0700590 // TODO: Not sure if display density should handled by SF any longer
591 class Density {
592 static int getDensityFromProperty(char const* propName) {
593 char property[PROPERTY_VALUE_MAX];
594 int density = 0;
595 if (property_get(propName, property, NULL) > 0) {
596 density = atoi(property);
597 }
598 return density;
599 }
600 public:
601 static int getEmuDensity() {
602 return getDensityFromProperty("qemu.sf.lcd_density"); }
603 static int getBuildDensity() {
604 return getDensityFromProperty("ro.sf.lcd_density"); }
605 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700606
Dan Stoza7f7da322014-05-02 15:26:25 -0700607 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700608
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700610 DisplayInfo info = DisplayInfo();
611
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612 float xdpi = hwConfig->getDpiX();
613 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700614
615 if (type == DisplayDevice::DISPLAY_PRIMARY) {
616 // The density of the device is provided by a build property
617 float density = Density::getBuildDensity() / 160.0f;
618 if (density == 0) {
619 // the build doesn't provide a density -- this is wrong!
620 // use xdpi instead
621 ALOGE("ro.sf.lcd_density must be defined as a build property");
622 density = xdpi / 160.0f;
623 }
624 if (Density::getEmuDensity()) {
625 // if "qemu.sf.lcd_density" is specified, it overrides everything
626 xdpi = ydpi = density = Density::getEmuDensity();
627 density /= 160.0f;
628 }
629 info.density = density;
630
631 // TODO: this needs to go away (currently needed only by webkit)
632 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
633 info.orientation = hw->getOrientation();
634 } else {
635 // TODO: where should this value come from?
636 static const int TV_DENSITY = 213;
637 info.density = TV_DENSITY / 160.0f;
638 info.orientation = 0;
639 }
640
Dan Stoza9e56aa02015-11-02 13:00:03 -0800641 info.w = hwConfig->getWidth();
642 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700643 info.xdpi = xdpi;
644 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800645 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700646 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647
Andy McFadden91b2ca82014-06-13 14:04:23 -0700648 // This is how far in advance a buffer must be queued for
649 // presentation at a given time. If you want a buffer to appear
650 // on the screen at time N, you must submit the buffer before
651 // (N - presentationDeadline).
652 //
653 // Normally it's one full refresh period (to give SF a chance to
654 // latch the buffer), but this can be reduced by configuring a
655 // DispSync offset. Any additional delays introduced by the hardware
656 // composer or panel must be accounted for here.
657 //
658 // We add an additional 1ms to allow for processing time and
659 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660 info.presentationDeadline = hwConfig->getVsyncPeriod() -
661 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700662
663 // All non-virtual displays are currently considered secure.
664 info.secure = true;
665
Michael Wright28f24d02016-07-12 13:30:53 -0700666 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700667 }
668
Dan Stoza7f7da322014-05-02 15:26:25 -0700669 return NO_ERROR;
670}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700671
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800672status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700673 DisplayStatInfo* stats) {
674 if (stats == NULL) {
675 return BAD_VALUE;
676 }
677
678 // FIXME for now we always return stats for the primary display
679 memset(stats, 0, sizeof(*stats));
680 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
681 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
682 return NO_ERROR;
683}
684
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700685int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800686 if (display == NULL) {
687 ALOGE("%s : display is NULL", __func__);
688 return BAD_VALUE;
689 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700690 sp<DisplayDevice> device(getDisplayDevice(display));
691 if (device != NULL) {
692 return device->getActiveConfig();
693 }
694 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700695}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700696
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700697void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
698 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
699 this);
700 int32_t type = hw->getDisplayType();
701 int currentMode = hw->getActiveConfig();
702
703 if (mode == currentMode) {
704 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
705 return;
706 }
707
708 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
709 ALOGW("Trying to set config for virtual display");
710 return;
711 }
712
713 hw->setActiveConfig(mode);
714 getHwComposer().setActiveConfig(type, mode);
715}
716
717status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
718 class MessageSetActiveConfig: public MessageBase {
719 SurfaceFlinger& mFlinger;
720 sp<IBinder> mDisplay;
721 int mMode;
722 public:
723 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
724 int mode) :
725 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
726 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700727 Vector<DisplayInfo> configs;
728 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700729 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700730 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700731 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700732 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700733 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700734 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
735 if (hw == NULL) {
736 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700737 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700738 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
739 ALOGW("Attempt to set active config = %d for virtual display",
740 mMode);
741 } else {
742 mFlinger.setActiveConfigInternal(hw, mMode);
743 }
744 return true;
745 }
746 };
747 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
748 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700749 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700750}
Michael Wright28f24d02016-07-12 13:30:53 -0700751status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
752 Vector<android_color_mode_t>* outColorModes) {
753 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
754 return BAD_VALUE;
755 }
756
757 if (!display.get()) {
758 return NAME_NOT_FOUND;
759 }
760
761 int32_t type = NAME_NOT_FOUND;
762 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
763 if (display == mBuiltinDisplays[i]) {
764 type = i;
765 break;
766 }
767 }
768
769 if (type < 0) {
770 return type;
771 }
772
773 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
774 outColorModes->clear();
775 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
776
777 return NO_ERROR;
778}
779
780android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
781 sp<DisplayDevice> device(getDisplayDevice(display));
782 if (device != nullptr) {
783 return device->getActiveColorMode();
784 }
785 return static_cast<android_color_mode_t>(BAD_VALUE);
786}
787
788void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
789 android_color_mode_t mode) {
790 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
791 this);
792 int32_t type = hw->getDisplayType();
793 android_color_mode_t currentMode = hw->getActiveColorMode();
794
795 if (mode == currentMode) {
796 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
797 return;
798 }
799
800 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
801 ALOGW("Trying to set config for virtual display");
802 return;
803 }
804
805 hw->setActiveColorMode(mode);
806 getHwComposer().setActiveColorMode(type, mode);
807}
808
809
810status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
811 android_color_mode_t colorMode) {
812 class MessageSetActiveColorMode: public MessageBase {
813 SurfaceFlinger& mFlinger;
814 sp<IBinder> mDisplay;
815 android_color_mode_t mMode;
816 public:
817 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
818 android_color_mode_t mode) :
819 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
820 virtual bool handler() {
821 Vector<android_color_mode_t> modes;
822 mFlinger.getDisplayColorModes(mDisplay, &modes);
823 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
824 if (mMode < 0 || !exists) {
825 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
826 mDisplay.get());
827 return true;
828 }
829 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
830 if (hw == nullptr) {
831 ALOGE("Attempt to set active color mode = %d for null display %p",
832 mMode, mDisplay.get());
833 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
834 ALOGW("Attempt to set active color mode= %d for virtual display",
835 mMode);
836 } else {
837 mFlinger.setActiveColorModeInternal(hw, mMode);
838 }
839 return true;
840 }
841 };
842 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
843 postMessageSync(msg);
844 return NO_ERROR;
845}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700846
Svetoslavd85084b2014-03-20 10:28:31 -0700847status_t SurfaceFlinger::clearAnimationFrameStats() {
848 Mutex::Autolock _l(mStateLock);
849 mAnimFrameTracker.clearStats();
850 return NO_ERROR;
851}
852
853status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
854 Mutex::Autolock _l(mStateLock);
855 mAnimFrameTracker.getStats(outStats);
856 return NO_ERROR;
857}
858
Dan Stozac4f471e2016-03-24 09:31:08 -0700859status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
860 HdrCapabilities* outCapabilities) const {
861 Mutex::Autolock _l(mStateLock);
862
863 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
864 if (displayDevice == nullptr) {
865 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
866 return BAD_VALUE;
867 }
868
869 std::unique_ptr<HdrCapabilities> capabilities =
870 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
871 if (capabilities) {
872 std::swap(*outCapabilities, *capabilities);
873 } else {
874 return BAD_VALUE;
875 }
876
877 return NO_ERROR;
878}
879
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700880status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
881 if (enable == mInjectVSyncs) {
882 return NO_ERROR;
883 }
884
885 if (enable) {
886 mInjectVSyncs = enable;
887 ALOGV("VSync Injections enabled");
888 if (mVSyncInjector.get() == nullptr) {
889 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700890 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700891 }
892 mEventQueue.setEventThread(mInjectorEventThread);
893 } else {
894 mInjectVSyncs = enable;
895 ALOGV("VSync Injections disabled");
896 mEventQueue.setEventThread(mSFEventThread);
897 mVSyncInjector.clear();
898 }
899 return NO_ERROR;
900}
901
902status_t SurfaceFlinger::injectVSync(nsecs_t when) {
903 if (!mInjectVSyncs) {
904 ALOGE("VSync Injections not enabled");
905 return BAD_VALUE;
906 }
907 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
908 ALOGV("Injecting VSync inside SurfaceFlinger");
909 mVSyncInjector->onInjectSyncEvent(when);
910 }
911 return NO_ERROR;
912}
913
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800914// ----------------------------------------------------------------------------
915
916sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800917 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700918}
919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800920// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800921
922void SurfaceFlinger::waitForEvent() {
923 mEventQueue.waitMessage();
924}
925
926void SurfaceFlinger::signalTransaction() {
927 mEventQueue.invalidate();
928}
929
930void SurfaceFlinger::signalLayerUpdate() {
931 mEventQueue.invalidate();
932}
933
934void SurfaceFlinger::signalRefresh() {
935 mEventQueue.refresh();
936}
937
938status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800939 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800940 return mEventQueue.postMessage(msg, reltime);
941}
942
943status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800944 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800945 status_t res = mEventQueue.postMessage(msg, reltime);
946 if (res == NO_ERROR) {
947 msg->wait();
948 }
949 return res;
950}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800951
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700952void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700953 do {
954 waitForEvent();
955 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800956}
957
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700958void SurfaceFlinger::enableHardwareVsync() {
959 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700960 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700961 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700962 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
963 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700964 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700965 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700966}
967
Jesse Hall948fe0c2013-10-14 12:56:09 -0700968void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700969 Mutex::Autolock _l(mHWVsyncLock);
970
Jesse Hall948fe0c2013-10-14 12:56:09 -0700971 if (makeAvailable) {
972 mHWVsyncAvailable = true;
973 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700974 // Hardware vsync is not currently available, so abort the resync
975 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700976 return;
977 }
978
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
980 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700981
982 mPrimaryDispSync.reset();
983 mPrimaryDispSync.setPeriod(period);
984
985 if (!mPrimaryHWVsyncEnabled) {
986 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700987 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
988 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700989 mPrimaryHWVsyncEnabled = true;
990 }
991}
992
Jesse Hall948fe0c2013-10-14 12:56:09 -0700993void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700994 Mutex::Autolock _l(mHWVsyncLock);
995 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700996 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
997 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700998 mPrimaryDispSync.endResync();
999 mPrimaryHWVsyncEnabled = false;
1000 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001001 if (makeUnavailable) {
1002 mHWVsyncAvailable = false;
1003 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001004}
1005
Tim Murray4a4e4a22016-04-19 16:29:23 +00001006void SurfaceFlinger::resyncWithRateLimit() {
1007 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1008 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001009 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001010 }
1011}
1012
Dan Stoza9e56aa02015-11-02 13:00:03 -08001013void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001014 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001015
Jamie Gennisd1700752013-10-14 12:22:52 -07001016 { // Scope for the lock
1017 Mutex::Autolock _l(mHWVsyncLock);
1018 if (type == 0 && mPrimaryHWVsyncEnabled) {
1019 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001020 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001021 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001022
1023 if (needsHwVsync) {
1024 enableHardwareVsync();
1025 } else {
1026 disableHardwareVsync(false);
1027 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001028}
1029
Dan Stoza9e56aa02015-11-02 13:00:03 -08001030void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1031 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1032 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1033 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001034
Dan Stoza9e56aa02015-11-02 13:00:03 -08001035 // All non-virtual displays are currently considered secure.
1036 bool isSecure = true;
1037
1038 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1039 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1040 wp<IBinder> token = mBuiltinDisplays[type];
1041
1042 sp<IGraphicBufferProducer> producer;
1043 sp<IGraphicBufferConsumer> consumer;
1044 BufferQueue::createBufferQueue(&producer, &consumer,
1045 new GraphicBufferAlloc());
1046
1047 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1048 DisplayDevice::DISPLAY_PRIMARY, consumer);
1049 sp<DisplayDevice> hw = new DisplayDevice(this,
1050 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1051 producer, mRenderEngine->getEGLConfig());
1052 mDisplays.add(token, hw);
1053 } else {
1054 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001055 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001056 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001057 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001058 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001059 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1060 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001061 }
1062 setTransactionFlags(eDisplayTransactionNeeded);
1063
Andy McFadden9e9689c2012-10-10 18:17:51 -07001064 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001065 }
Mathias Agopian86303202012-07-24 22:46:10 -07001066}
1067
Dan Stoza9e56aa02015-11-02 13:00:03 -08001068void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001070 getHwComposer().setVsyncEnabled(disp,
1071 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001072}
1073
Mathias Agopian4fec8732012-06-29 14:12:52 -07001074void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001075 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001076 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001077 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001078 bool frameMissed = !mHadClientComposition &&
1079 mPreviousPresentFence != Fence::NO_FENCE &&
1080 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1081 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001082 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001083 signalLayerUpdate();
1084 break;
1085 }
1086
Dan Stoza6b9454d2014-11-07 16:00:59 -08001087 bool refreshNeeded = handleMessageTransaction();
1088 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001089 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001090 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001091 // Signal a refresh if a transaction modified the window state,
1092 // a new buffer was latched, or if HWC has requested a full
1093 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001094 signalRefresh();
1095 }
1096 break;
1097 }
1098 case MessageQueue::REFRESH: {
1099 handleMessageRefresh();
1100 break;
1101 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001102 }
1103}
1104
Dan Stoza6b9454d2014-11-07 16:00:59 -08001105bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001106 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001107 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001108 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001109 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001110 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001111 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001112}
1113
Dan Stoza6b9454d2014-11-07 16:00:59 -08001114bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001115 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001116 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001117}
1118
1119void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001120 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001121
Pablo Ceballos40845df2016-01-25 17:41:15 -08001122 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001123
Dan Stoza05dacfb2016-07-01 13:33:38 -07001124 preComposition();
1125 rebuildLayerStacks();
1126 setUpHWComposer();
1127 doDebugFlashRegions();
1128 doComposition();
1129 postComposition(refreshStartTime);
1130
1131 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001132
1133 mHadClientComposition = false;
1134 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1135 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1136 mHadClientComposition = mHadClientComposition ||
1137 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1138 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001139
Dan Stoza9e56aa02015-11-02 13:00:03 -08001140 // Release any buffers which were replaced this frame
1141 for (auto& layer : mLayersWithQueuedFrames) {
1142 layer->releasePendingBuffer();
1143 }
1144 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001145}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001146
Mathias Agopiancd60f992012-08-16 16:28:27 -07001147void SurfaceFlinger::doDebugFlashRegions()
1148{
1149 // is debugging enabled
1150 if (CC_LIKELY(!mDebugRegion))
1151 return;
1152
1153 const bool repaintEverything = mRepaintEverything;
1154 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1155 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001156 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001157 // transform the dirty region into this screen's coordinate space
1158 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1159 if (!dirtyRegion.isEmpty()) {
1160 // redraw the whole screen
1161 doComposeSurfaces(hw, Region(hw->bounds()));
1162
1163 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001164 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001165 RenderEngine& engine(getRenderEngine());
1166 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1167
Mathias Agopianda27af92012-09-13 18:17:13 -07001168 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001169 }
1170 }
1171 }
1172
1173 postFramebuffer();
1174
1175 if (mDebugRegion > 1) {
1176 usleep(mDebugRegion * 1000);
1177 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001178
Dan Stoza9e56aa02015-11-02 13:00:03 -08001179 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001180 auto& displayDevice = mDisplays[displayId];
1181 if (!displayDevice->isDisplayOn()) {
1182 continue;
1183 }
1184
1185 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1187 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001188 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001189}
1190
1191void SurfaceFlinger::preComposition()
1192{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193 ATRACE_CALL();
1194 ALOGV("preComposition");
1195
Mathias Agopiancd60f992012-08-16 16:28:27 -07001196 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001197 const LayerVector& layers(mDrawingState.layersSortedByZ);
1198 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001199 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001200 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001201 needExtraInvalidate = true;
1202 }
1203 }
1204 if (needExtraInvalidate) {
1205 signalLayerUpdate();
1206 }
1207}
1208
Pablo Ceballos40845df2016-01-25 17:41:15 -08001209void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001210{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 ATRACE_CALL();
1212 ALOGV("postComposition");
1213
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001214 const LayerVector& layers(mDrawingState.layersSortedByZ);
1215 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001216 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001217 bool frameLatched = layers[i]->onPostComposition();
1218 if (frameLatched) {
1219 recordBufferingStats(layers[i]->getName().string(),
1220 layers[i]->getOccupancyHistory(false));
1221 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001222 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001223
Dan Stoza9e56aa02015-11-02 13:00:03 -08001224 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225
1226 if (presentFence->isValid()) {
1227 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1228 enableHardwareVsync();
1229 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001230 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231 }
1232 }
1233
Dan Stozab90cf072015-03-05 11:05:59 -08001234 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001235 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001236 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 enableHardwareVsync();
1238 }
1239 }
1240
Pablo Ceballos40845df2016-01-25 17:41:15 -08001241 mFenceTracker.addFrame(refreshStartTime, presentFence,
1242 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1243
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001244 if (mAnimCompositionPending) {
1245 mAnimCompositionPending = false;
1246
Jesse Halla9a1b002013-02-27 16:39:25 -08001247 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001248 mAnimFrameTracker.setActualPresentFence(presentFence);
1249 } else {
1250 // The HWC doesn't support present fences, so use the refresh
1251 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001252 nsecs_t presentTime =
1253 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001254 mAnimFrameTracker.setActualPresentTime(presentTime);
1255 }
1256 mAnimFrameTracker.advanceFrame();
1257 }
Dan Stozab90cf072015-03-05 11:05:59 -08001258
1259 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1260 return;
1261 }
1262
1263 nsecs_t currentTime = systemTime();
1264 if (mHasPoweredOff) {
1265 mHasPoweredOff = false;
1266 } else {
1267 nsecs_t period = mPrimaryDispSync.getPeriod();
1268 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1269 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1270 if (numPeriods < NUM_BUCKETS - 1) {
1271 mFrameBuckets[numPeriods] += elapsedTime;
1272 } else {
1273 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1274 }
1275 mTotalTime += elapsedTime;
1276 }
1277 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001278}
1279
1280void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001281 ATRACE_CALL();
1282 ALOGV("rebuildLayerStacks");
1283
Mathias Agopiancd60f992012-08-16 16:28:27 -07001284 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001285 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001286 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001287 mVisibleRegionsDirty = false;
1288 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001289
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001290 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001291 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001292 Region opaqueRegion;
1293 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001294 Vector<sp<Layer>> layersSortedByZ;
1295 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1296 const Transform& tr(displayDevice->getTransform());
1297 const Rect bounds(displayDevice->getBounds());
1298 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001299 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 displayDevice->getLayerStack(), dirtyRegion,
1301 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001302
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001303 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001304 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001305 const sp<Layer>& layer(layers[i]);
1306 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001308 Region drawRegion(tr.transform(
1309 layer->visibleNonTransparentRegion));
1310 drawRegion.andSelf(bounds);
1311 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001312 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 } else {
1314 // Clear out the HWC layer if this layer was
1315 // previously visible, but no longer is
1316 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1317 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001318 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001319 }
1320 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001321 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001322 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1323 displayDevice->undefinedRegion.set(bounds);
1324 displayDevice->undefinedRegion.subtractSelf(
1325 tr.transform(opaqueRegion));
1326 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001327 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001328 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001329}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001330
Mathias Agopiancd60f992012-08-16 16:28:27 -07001331void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001332 ATRACE_CALL();
1333 ALOGV("setUpHWComposer");
1334
Jesse Hall028dc8f2013-08-20 16:35:32 -07001335 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001336 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1337 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1338 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1339
1340 // If nothing has changed (!dirty), don't recompose.
1341 // If something changed, but we don't currently have any visible layers,
1342 // and didn't when we last did a composition, then skip it this time.
1343 // The second rule does two things:
1344 // - When all layers are removed from a display, we'll emit one black
1345 // frame, then nothing more until we get new layers.
1346 // - When a display is created with a private layer stack, we won't
1347 // emit any black frames until a layer is added to the layer stack.
1348 bool mustRecompose = dirty && !(empty && wasEmpty);
1349
1350 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1351 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1352 mustRecompose ? "doing" : "skipping",
1353 dirty ? "+" : "-",
1354 empty ? "+" : "-",
1355 wasEmpty ? "+" : "-");
1356
Dan Stoza71433162014-02-04 16:22:36 -08001357 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001358
1359 if (mustRecompose) {
1360 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1361 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001362 }
1363
Dan Stoza9e56aa02015-11-02 13:00:03 -08001364 // build the h/w work list
1365 if (CC_UNLIKELY(mGeometryInvalid)) {
1366 mGeometryInvalid = false;
1367 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1368 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1369 const auto hwcId = displayDevice->getHwcDisplayId();
1370 if (hwcId >= 0) {
1371 const Vector<sp<Layer>>& currentLayers(
1372 displayDevice->getVisibleLayersSortedByZ());
1373 bool foundLayerWithoutHwc = false;
1374 for (auto& layer : currentLayers) {
1375 if (!layer->hasHwcLayer(hwcId)) {
1376 auto hwcLayer = mHwc->createLayer(hwcId);
1377 if (hwcLayer) {
1378 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1379 } else {
1380 layer->forceClientComposition(hwcId);
1381 foundLayerWithoutHwc = true;
1382 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001383 }
1384 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001385
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001387 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001389 }
1390 }
1391 }
1392 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001393 }
Riley Andrews03414a12014-07-01 14:22:59 -07001394
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001395
1396 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1397
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 // Set the per-frame data
1399 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1400 auto& displayDevice = mDisplays[displayId];
1401 const auto hwcId = displayDevice->getHwcDisplayId();
1402 if (hwcId < 0) {
1403 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001404 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001405 if (colorMatrix != mPreviousColorMatrix) {
1406 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1407 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1408 "display %zd: %d", displayId, result);
1409 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001410 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1411 layer->setPerFrameData(displayDevice);
1412 }
1413 }
1414
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001415 mPreviousColorMatrix = colorMatrix;
1416
Dan Stoza9e56aa02015-11-02 13:00:03 -08001417 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001418 auto& displayDevice = mDisplays[displayId];
1419 if (!displayDevice->isDisplayOn()) {
1420 continue;
1421 }
1422
1423 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001424 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1425 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001426 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001427}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001428
Mathias Agopiancd60f992012-08-16 16:28:27 -07001429void SurfaceFlinger::doComposition() {
1430 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001431 ALOGV("doComposition");
1432
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001433 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001434 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001435 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001436 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 // transform the dirty region into this screen's coordinate space
1438 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001439
1440 // repaint the framebuffer (if needed)
1441 doDisplayComposition(hw, dirtyRegion);
1442
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 hw->dirtyRegion.clear();
1444 hw->flip(hw->swapRegion);
1445 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001446 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001448 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001449}
1450
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001451void SurfaceFlinger::postFramebuffer()
1452{
Mathias Agopian841cde52012-03-01 15:44:37 -08001453 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001454 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001455
Mathias Agopiana44b0412011-10-16 18:46:35 -07001456 const nsecs_t now = systemTime();
1457 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001458
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1460 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001461 if (!displayDevice->isDisplayOn()) {
1462 continue;
1463 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001464 const auto hwcId = displayDevice->getHwcDisplayId();
1465 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001466 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001467 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001468 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001469 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001470 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1471 sp<Fence> releaseFence = Fence::NO_FENCE;
1472 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1473 releaseFence = displayDevice->getClientTargetAcquireFence();
1474 } else {
1475 auto hwcLayer = layer->getHwcLayer(hwcId);
1476 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001477 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478 layer->onLayerDisplayed(releaseFence);
1479 }
1480 if (hwcId >= 0) {
1481 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001482 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001483 }
1484
Mathias Agopiana44b0412011-10-16 18:46:35 -07001485 mLastSwapBufferTime = systemTime() - now;
1486 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001487
1488 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1489 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1490 logFrameStats();
1491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001492}
1493
Mathias Agopian87baae12012-07-31 12:38:26 -07001494void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001495{
Mathias Agopian841cde52012-03-01 15:44:37 -08001496 ATRACE_CALL();
1497
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001498 // here we keep a copy of the drawing state (that is the state that's
1499 // going to be overwritten by handleTransactionLocked()) outside of
1500 // mStateLock so that the side-effects of the State assignment
1501 // don't happen with mStateLock held (which can cause deadlocks).
1502 State drawingState(mDrawingState);
1503
Mathias Agopianca4d3602011-05-19 15:38:14 -07001504 Mutex::Autolock _l(mStateLock);
1505 const nsecs_t now = systemTime();
1506 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001507
Mathias Agopianca4d3602011-05-19 15:38:14 -07001508 // Here we're guaranteed that some transaction flags are set
1509 // so we can call handleTransactionLocked() unconditionally.
1510 // We call getTransactionFlags(), which will also clear the flags,
1511 // with mStateLock held to guarantee that mCurrentState won't change
1512 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001513
Mathias Agopiane57f2922012-08-09 16:29:12 -07001514 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001515 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001516
Mathias Agopianca4d3602011-05-19 15:38:14 -07001517 mLastTransactionTime = systemTime() - now;
1518 mDebugInTransaction = 0;
1519 invalidateHwcGeometry();
1520 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001521}
1522
Mathias Agopian87baae12012-07-31 12:38:26 -07001523void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001524{
1525 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001526 const size_t count = currentLayers.size();
1527
Dan Stoza7dde5992015-05-22 09:51:44 -07001528 // Notify all layers of available frames
1529 for (size_t i = 0; i < count; ++i) {
1530 currentLayers[i]->notifyAvailableFrames();
1531 }
1532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001533 /*
1534 * Traversal of the children
1535 * (perform the transaction for each of them if needed)
1536 */
1537
Mathias Agopian3559b072012-08-15 13:46:03 -07001538 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001539 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001540 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1542 if (!trFlags) continue;
1543
1544 const uint32_t flags = layer->doTransaction(0);
1545 if (flags & Layer::eVisibleRegion)
1546 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547 }
1548 }
1549
1550 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001551 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001552 */
1553
Mathias Agopiane57f2922012-08-09 16:29:12 -07001554 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001555 // here we take advantage of Vector's copy-on-write semantics to
1556 // improve performance by skipping the transaction entirely when
1557 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001558 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1559 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001560 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001561 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001562 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001563 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001564
1565 // find the displays that were removed
1566 // (ie: in drawing state but not in current state)
1567 // also handle displays that changed
1568 // (ie: displays that are in both lists)
1569 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001570 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1571 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001572 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001573 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001574 // Call makeCurrent() on the primary display so we can
1575 // be sure that nothing associated with this display
1576 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001577 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001578 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001579 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1580 if (hw != NULL)
1581 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001582 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001583 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001584 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001585 } else {
1586 ALOGW("trying to remove the main display");
1587 }
1588 } else {
1589 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001590 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001591 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001592 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1593 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001594 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001595 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001596 // recreating the DisplayDevice, so we just remove it
1597 // from the drawing state, so that it get re-added
1598 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001599 sp<DisplayDevice> hw(getDisplayDevice(display));
1600 if (hw != NULL)
1601 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001602 mDisplays.removeItem(display);
1603 mDrawingState.displays.removeItemsAt(i);
1604 dc--; i--;
1605 // at this point we must loop to the next item
1606 continue;
1607 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001608
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001609 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001610 if (disp != NULL) {
1611 if (state.layerStack != draw[i].layerStack) {
1612 disp->setLayerStack(state.layerStack);
1613 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001614 if ((state.orientation != draw[i].orientation)
1615 || (state.viewport != draw[i].viewport)
1616 || (state.frame != draw[i].frame))
1617 {
1618 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001619 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001620 }
Michael Lentine47e45402014-07-18 15:34:25 -07001621 if (state.width != draw[i].width || state.height != draw[i].height) {
1622 disp->setDisplaySize(state.width, state.height);
1623 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001624 }
1625 }
1626 }
1627
1628 // find displays that were added
1629 // (ie: in current state but not in drawing state)
1630 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001631 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001632 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001633
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001634 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001635 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001636 sp<IGraphicBufferProducer> bqProducer;
1637 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001638 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1639 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001640
Dan Stoza9e56aa02015-11-02 13:00:03 -08001641 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001642 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001643 // Virtual displays without a surface are dormant:
1644 // they have external state (layer stack, projection,
1645 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001646 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001647
Dan Stoza8cf150a2016-08-02 10:27:31 -07001648 if (mUseHwcVirtualDisplays) {
1649 int width = 0;
1650 int status = state.surface->query(
1651 NATIVE_WINDOW_WIDTH, &width);
1652 ALOGE_IF(status != NO_ERROR,
1653 "Unable to query width (%d)", status);
1654 int height = 0;
1655 status = state.surface->query(
1656 NATIVE_WINDOW_HEIGHT, &height);
1657 ALOGE_IF(status != NO_ERROR,
1658 "Unable to query height (%d)", status);
1659 int intFormat = 0;
1660 status = state.surface->query(
1661 NATIVE_WINDOW_FORMAT, &intFormat);
1662 ALOGE_IF(status != NO_ERROR,
1663 "Unable to query format (%d)", status);
1664 auto format = static_cast<android_pixel_format_t>(
1665 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001666
Dan Stoza8cf150a2016-08-02 10:27:31 -07001667 mHwc->allocateVirtualDisplay(width, height, &format,
1668 &hwcId);
1669 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670
Dan Stoza5cf424b2016-05-20 14:02:39 -07001671 // TODO: Plumb requested format back up to consumer
1672
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 sp<VirtualDisplaySurface> vds =
1674 new VirtualDisplaySurface(*mHwc,
1675 hwcId, state.surface, bqProducer,
1676 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001677
1678 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001679 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001680 }
1681 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001682 ALOGE_IF(state.surface!=NULL,
1683 "adding a supported display, but rendering "
1684 "surface is provided (%p), ignoring it",
1685 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1687 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1688 dispSurface = new FramebufferSurface(*mHwc,
1689 DisplayDevice::DISPLAY_EXTERNAL,
1690 bqConsumer);
1691 producer = bqProducer;
1692 } else {
1693 ALOGE("Attempted to add non-external non-virtual"
1694 " display");
1695 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001696 }
1697
1698 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001699 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001700 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001701 state.type, hwcId, state.isSecure, display,
1702 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001703 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001704 hw->setLayerStack(state.layerStack);
1705 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001706 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001707 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001708 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001710 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001711 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001712 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001713 }
1714 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001715 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001717
Mathias Agopian84300952012-11-21 16:02:13 -08001718 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1719 // The transform hint might have changed for some layers
1720 // (either because a display has changed, or because a layer
1721 // as changed).
1722 //
1723 // Walk through all the layers in currentLayers,
1724 // and update their transform hint.
1725 //
1726 // If a layer is visible only on a single display, then that
1727 // display is used to calculate the hint, otherwise we use the
1728 // default display.
1729 //
1730 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1731 // the hint is set before we acquire a buffer from the surface texture.
1732 //
1733 // NOTE: layer transactions have taken place already, so we use their
1734 // drawing state. However, SurfaceFlinger's own transaction has not
1735 // happened yet, so we must use the current state layer list
1736 // (soon to become the drawing state list).
1737 //
1738 sp<const DisplayDevice> disp;
1739 uint32_t currentlayerStack = 0;
1740 for (size_t i=0; i<count; i++) {
1741 // NOTE: we rely on the fact that layers are sorted by
1742 // layerStack first (so we don't have to traverse the list
1743 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001744 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001745 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001746 if (i==0 || currentlayerStack != layerStack) {
1747 currentlayerStack = layerStack;
1748 // figure out if this layerstack is mirrored
1749 // (more than one display) if so, pick the default display,
1750 // if not, pick the only display it's on.
1751 disp.clear();
1752 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1753 sp<const DisplayDevice> hw(mDisplays[dpy]);
1754 if (hw->getLayerStack() == currentlayerStack) {
1755 if (disp == NULL) {
1756 disp = hw;
1757 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001758 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001759 break;
1760 }
1761 }
1762 }
1763 }
Chet Haase91d25932013-04-11 15:24:55 -07001764 if (disp == NULL) {
1765 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1766 // redraw after transform hint changes. See bug 8508397.
1767
1768 // could be null when this layer is using a layerStack
1769 // that is not visible on any display. Also can occur at
1770 // screen off/on times.
1771 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001772 }
Chet Haase91d25932013-04-11 15:24:55 -07001773 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001774 }
1775 }
1776
1777
Mathias Agopian3559b072012-08-15 13:46:03 -07001778 /*
1779 * Perform our own transaction if needed
1780 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001781
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001782 const LayerVector& layers(mDrawingState.layersSortedByZ);
1783 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001784 // layers have been added
1785 mVisibleRegionsDirty = true;
1786 }
1787
1788 // some layers might have been removed, so
1789 // we need to update the regions they're exposing.
1790 if (mLayersRemoved) {
1791 mLayersRemoved = false;
1792 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001793 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001794 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001795 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001796 if (currentLayers.indexOf(layer) < 0) {
1797 // this layer is not visible anymore
1798 // TODO: we could traverse the tree from front to back and
1799 // compute the actual visible region
1800 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001801 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001802 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001803 Region(Rect(s.active.w, s.active.h)));
1804 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001805 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807 }
1808
1809 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001810
1811 updateCursorAsync();
1812}
1813
1814void SurfaceFlinger::updateCursorAsync()
1815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1817 auto& displayDevice = mDisplays[displayId];
1818 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001819 continue;
1820 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821
1822 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1823 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001824 }
1825 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001826}
1827
1828void SurfaceFlinger::commitTransaction()
1829{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001830 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001831 // Notify removed layers now that they can't be drawn from
1832 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001833 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1834 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835 mLayersPendingRemoval[i]->onRemoved();
1836 }
1837 mLayersPendingRemoval.clear();
1838 }
1839
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001840 // If this transaction is part of a window animation then the next frame
1841 // we composite should be considered an animation as well.
1842 mAnimCompositionPending = mAnimTransactionPending;
1843
Mathias Agopian4fec8732012-06-29 14:12:52 -07001844 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001845 mTransactionPending = false;
1846 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001847 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001848}
1849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001850void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001851 const LayerVector& currentLayers, uint32_t layerStack,
1852 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853{
Mathias Agopian841cde52012-03-01 15:44:37 -08001854 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001857 Region aboveOpaqueLayers;
1858 Region aboveCoveredLayers;
1859 Region dirty;
1860
Mathias Agopian87baae12012-07-31 12:38:26 -07001861 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862
1863 size_t i = currentLayers.size();
1864 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001865 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866
1867 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001868 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001869
Jesse Hall01e29052013-02-19 16:13:35 -08001870 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001871 if (s.layerStack != layerStack)
1872 continue;
1873
Mathias Agopianab028732010-03-16 16:41:46 -07001874 /*
1875 * opaqueRegion: area of a surface that is fully opaque.
1876 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001877 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001878
1879 /*
1880 * visibleRegion: area of a surface that is visible on screen
1881 * and not fully transparent. This is essentially the layer's
1882 * footprint minus the opaque regions above it.
1883 * Areas covered by a translucent surface are considered visible.
1884 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001886
1887 /*
1888 * coveredRegion: area of a surface that is covered by all
1889 * visible regions above it (which includes the translucent areas).
1890 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001892
Jesse Halla8026d22012-09-25 13:25:04 -07001893 /*
1894 * transparentRegion: area of a surface that is hinted to be completely
1895 * transparent. This is only used to tell when the layer has no visible
1896 * non-transparent regions and can be removed from the layer list. It
1897 * does not affect the visibleRegion of this layer or any layers
1898 * beneath it. The hint may not be correct if apps don't respect the
1899 * SurfaceView restrictions (which, sadly, some don't).
1900 */
1901 Region transparentRegion;
1902
Mathias Agopianab028732010-03-16 16:41:46 -07001903
1904 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001905 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001906 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001907 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001909 if (!visibleRegion.isEmpty()) {
1910 // Remove the transparent area from the visible region
1911 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001912 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001913 if (tr.preserveRects()) {
1914 // transform the transparent region
1915 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001916 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001917 // transformation too complex, can't do the
1918 // transparent region optimization.
1919 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001920 }
Mathias Agopianab028732010-03-16 16:41:46 -07001921 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001922
Mathias Agopianab028732010-03-16 16:41:46 -07001923 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001924 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001926 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1927 // the opaque region is the layer's footprint
1928 opaqueRegion = visibleRegion;
1929 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930 }
1931 }
1932
Mathias Agopianab028732010-03-16 16:41:46 -07001933 // Clip the covered region to the visible region
1934 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1935
1936 // Update aboveCoveredLayers for next (lower) layer
1937 aboveCoveredLayers.orSelf(visibleRegion);
1938
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001939 // subtract the opaque region covered by the layers above us
1940 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001941
1942 // compute this layer's dirty region
1943 if (layer->contentDirty) {
1944 // we need to invalidate the whole region
1945 dirty = visibleRegion;
1946 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001947 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948 layer->contentDirty = false;
1949 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001950 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001951 * the exposed region consists of two components:
1952 * 1) what's VISIBLE now and was COVERED before
1953 * 2) what's EXPOSED now less what was EXPOSED before
1954 *
1955 * note that (1) is conservative, we start with the whole
1956 * visible region but only keep what used to be covered by
1957 * something -- which mean it may have been exposed.
1958 *
1959 * (2) handles areas that were not covered by anything but got
1960 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001961 */
Mathias Agopianab028732010-03-16 16:41:46 -07001962 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001963 const Region oldVisibleRegion = layer->visibleRegion;
1964 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001965 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1966 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001967 }
1968 dirty.subtractSelf(aboveOpaqueLayers);
1969
1970 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001972
Mathias Agopianab028732010-03-16 16:41:46 -07001973 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001974 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001975
Jesse Halla8026d22012-09-25 13:25:04 -07001976 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977 layer->setVisibleRegion(visibleRegion);
1978 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001979 layer->setVisibleNonTransparentRegion(
1980 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981 }
1982
Mathias Agopian87baae12012-07-31 12:38:26 -07001983 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001984}
1985
Mathias Agopian87baae12012-07-31 12:38:26 -07001986void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1987 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001989 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1990 if (hw->getLayerStack() == layerStack) {
1991 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001992 }
1993 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001994}
1995
Dan Stoza6b9454d2014-11-07 16:00:59 -08001996bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 ALOGV("handlePageFlip");
1999
Mathias Agopian4fec8732012-06-29 14:12:52 -07002000 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001
Mathias Agopian4fec8732012-06-29 14:12:52 -07002002 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002003 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002004 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002005
2006 // Store the set of layers that need updates. This set must not change as
2007 // buffers are being latched, as this could result in a deadlock.
2008 // Example: Two producers share the same command stream and:
2009 // 1.) Layer 0 is latched
2010 // 2.) Layer 0 gets a new frame
2011 // 2.) Layer 1 gets a new frame
2012 // 3.) Layer 1 is latched.
2013 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2014 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002015 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002016 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002017 if (layer->hasQueuedFrame()) {
2018 frameQueued = true;
2019 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002021 } else {
2022 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002023 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002024 } else {
2025 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002026 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002027 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002029 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002030 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002031 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002032 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002033 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002034
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002035 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002036
2037 // If we will need to wake up at some time in the future to deal with a
2038 // queued frame that shouldn't be displayed during this vsync period, wake
2039 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002041 signalLayerUpdate();
2042 }
2043
2044 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046}
2047
Mathias Agopianad456f92011-01-13 17:53:01 -08002048void SurfaceFlinger::invalidateHwcGeometry()
2049{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002051}
2052
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002053
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002055 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056{
Dan Stoza71433162014-02-04 16:22:36 -08002057 // We only need to actually compose the display if:
2058 // 1) It is being handled by hardware composer, which may need this to
2059 // keep its virtual display state machine in sync, or
2060 // 2) There is work to be done (the dirty region isn't empty)
2061 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2062 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002064 return;
2065 }
2066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 ALOGV("doDisplayComposition");
2068
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 Region dirtyRegion(inDirtyRegion);
2070
Mathias Agopianb8a55602009-06-26 19:06:36 -07002071 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002072 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002073
Mathias Agopian42977342012-08-05 00:40:46 -07002074 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002075 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002076 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2077 // takes a rectangle, we must make sure to update that whole
2078 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002079 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002080 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002081 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002082 // We need to redraw the rectangle that will be updated
2083 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002084 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002085 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002086 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002087 } else {
2088 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002089 dirtyRegion.set(hw->bounds());
2090 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091 }
2092 }
2093
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002094 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002096 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002097 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002098
2099 // swap buffers (presentation)
2100 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101}
2102
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103bool SurfaceFlinger::doComposeSurfaces(
2104 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002105{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002107
Dan Stoza9e56aa02015-11-02 13:00:03 -08002108 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002109
2110 mat4 oldColorMatrix;
2111 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2112 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2113 if (applyColorMatrix) {
2114 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2115 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2116 }
2117
Dan Stoza9e56aa02015-11-02 13:00:03 -08002118 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2119 if (hasClientComposition) {
2120 ALOGV("hasClientComposition");
2121
2122 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002123 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002125 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2126 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2127 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2128 }
2129 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002130 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002131
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002132 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2134 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002135 // when using overlays, we assume a fully transparent framebuffer
2136 // NOTE: we could reduce how much we need to clear, for instance
2137 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002138 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002139 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002141 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002142 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002144
2145 // we remove the scissor part
2146 // we're left with the letterbox region
2147 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002149
2150 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002152
2153 // but limit it to the dirty region
2154 region.andSelf(dirty);
2155
Mathias Agopianb9494d52012-04-18 02:28:45 -07002156 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002157 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002158 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002160 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002161 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002162
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002164 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002165 // scissor on the main display. It should never be needed
2166 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 const Rect& bounds(displayDevice->getBounds());
2168 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002169 if (scissor != bounds) {
2170 // scissor doesn't match the screen's dimensions, so we
2171 // need to clear everything outside of it and enable
2172 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002173
Mathias Agopianf45c5102012-10-24 16:29:17 -07002174 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 const uint32_t height = displayDevice->getHeight();
2176 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002177 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002178 }
2179 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002180 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002181
Mathias Agopian85d751c2012-08-29 16:59:24 -07002182 /*
2183 * and then, render the layers targeted at the framebuffer
2184 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002185
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 ALOGV("Rendering client layers");
2187 const Transform& displayTransform = displayDevice->getTransform();
2188 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002189 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 bool firstLayer = true;
2191 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2192 const Region clip(dirty.intersect(
2193 displayTransform.transform(layer->visibleRegion)));
2194 ALOGV("Layer: %s", layer->getName().string());
2195 ALOGV(" Composition type: %s",
2196 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002197 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 switch (layer->getCompositionType(hwcId)) {
2199 case HWC2::Composition::Cursor:
2200 case HWC2::Composition::Device:
2201 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002202 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002203 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2204 layer->isOpaque(state) && (state.alpha == 1.0f)
2205 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002206 // never clear the very first layer since we're
2207 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002209 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002210 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002211 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 case HWC2::Composition::Client: {
2213 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002214 break;
2215 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002217 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002219 } else {
2220 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002221 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002223 }
2224 } else {
2225 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002227 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002229 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002231 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002232 }
2233 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002234
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002235 if (applyColorMatrix) {
2236 getRenderEngine().setupColorTransform(oldColorMatrix);
2237 }
2238
Mathias Agopianf45c5102012-10-24 16:29:17 -07002239 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002241 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242}
2243
Mathias Agopian3f844832013-08-07 21:24:32 -07002244void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002245 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002246 RenderEngine& engine(getRenderEngine());
2247 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248}
2249
Dan Stoza7d89d062015-04-30 13:29:25 -07002250status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002251 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002252 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002253 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002254{
Dan Stoza7d89d062015-04-30 13:29:25 -07002255 // add this layer to the current state list
2256 {
2257 Mutex::Autolock _l(mStateLock);
2258 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2259 return NO_MEMORY;
2260 }
2261 mCurrentState.layersSortedByZ.add(lbc);
2262 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2263 }
2264
Mathias Agopian96f08192010-06-02 23:28:45 -07002265 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002266 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002267
Dan Stoza7d89d062015-04-30 13:29:25 -07002268 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002269}
2270
Dan Stoza22851c32016-08-09 13:21:03 -07002271status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002273 sp<Layer> layer = weakLayer.promote();
2274 if (layer == nullptr) {
2275 // The layer has already been removed, carry on
2276 return NO_ERROR;
2277 }
2278
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002279 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2280 if (index >= 0) {
2281 mLayersPendingRemoval.push(layer);
2282 mLayersRemoved = true;
2283 setTransactionFlags(eTransactionNeeded);
2284 return NO_ERROR;
2285 }
2286 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287}
2288
Dan Stozac7014012014-02-14 15:03:43 -08002289uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002290 return android_atomic_release_load(&mTransactionFlags);
2291}
2292
Mathias Agopian3f844832013-08-07 21:24:32 -07002293uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2295}
2296
Mathias Agopian3f844832013-08-07 21:24:32 -07002297uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2299 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002300 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301 }
2302 return old;
2303}
2304
Mathias Agopian8b33f032012-07-24 20:43:54 -07002305void SurfaceFlinger::setTransactionState(
2306 const Vector<ComposerState>& state,
2307 const Vector<DisplayState>& displays,
2308 uint32_t flags)
2309{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002310 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002311 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002312 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002313
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002314 if (flags & eAnimation) {
2315 // For window updates that are part of an animation we must wait for
2316 // previous animation "frames" to be handled.
2317 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002319 if (CC_UNLIKELY(err != NO_ERROR)) {
2320 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002321 // caller after a few seconds.
2322 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2323 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002324 mAnimTransactionPending = false;
2325 break;
2326 }
2327 }
2328 }
2329
Mathias Agopiane57f2922012-08-09 16:29:12 -07002330 size_t count = displays.size();
2331 for (size_t i=0 ; i<count ; i++) {
2332 const DisplayState& s(displays[i]);
2333 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002334 }
2335
Mathias Agopiane57f2922012-08-09 16:29:12 -07002336 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002337 for (size_t i=0 ; i<count ; i++) {
2338 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002339 // Here we need to check that the interface we're given is indeed
2340 // one of our own. A malicious client could give us a NULL
2341 // IInterface, or one of its own or even one of our own but a
2342 // different type. All these situations would cause us to crash.
2343 //
2344 // NOTE: it would be better to use RTTI as we could directly check
2345 // that we have a Client*. however, RTTI is disabled in Android.
2346 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002347 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002348 if (binder != NULL) {
2349 String16 desc(binder->getInterfaceDescriptor());
2350 if (desc == ISurfaceComposerClient::descriptor) {
2351 sp<Client> client( static_cast<Client *>(s.client.get()) );
2352 transactionFlags |= setClientStateLocked(client, s.state);
2353 }
2354 }
2355 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002356 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002357
Robert Carr2a7dbb42016-05-24 11:41:28 -07002358 // If a synchronous transaction is explicitly requested without any changes,
2359 // force a transaction anyway. This can be used as a flush mechanism for
2360 // previous async transactions.
2361 if (transactionFlags == 0 && (flags & eSynchronous)) {
2362 transactionFlags = eTransactionNeeded;
2363 }
2364
Mathias Agopian386aa982011-11-07 21:58:03 -08002365 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002366 if (mInterceptor.isEnabled()) {
2367 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2368 }
Irvel468051e2016-06-13 16:44:44 -07002369
Mathias Agopian386aa982011-11-07 21:58:03 -08002370 // this triggers the transaction
2371 setTransactionFlags(transactionFlags);
2372
2373 // if this is a synchronous transaction, wait for it to take effect
2374 // before returning.
2375 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002376 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002377 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002378 if (flags & eAnimation) {
2379 mAnimTransactionPending = true;
2380 }
2381 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002382 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2383 if (CC_UNLIKELY(err != NO_ERROR)) {
2384 // just in case something goes wrong in SF, return to the
2385 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002386 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2387 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002388 break;
2389 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002390 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391 }
2392}
2393
Mathias Agopiane57f2922012-08-09 16:29:12 -07002394uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2395{
Jesse Hall9a143922012-10-04 16:29:19 -07002396 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2397 if (dpyIdx < 0)
2398 return 0;
2399
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002401 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002402 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002403 const uint32_t what = s.what;
2404 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002405 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002406 disp.surface = s.surface;
2407 flags |= eDisplayTransactionNeeded;
2408 }
2409 }
2410 if (what & DisplayState::eLayerStackChanged) {
2411 if (disp.layerStack != s.layerStack) {
2412 disp.layerStack = s.layerStack;
2413 flags |= eDisplayTransactionNeeded;
2414 }
2415 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002416 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002417 if (disp.orientation != s.orientation) {
2418 disp.orientation = s.orientation;
2419 flags |= eDisplayTransactionNeeded;
2420 }
2421 if (disp.frame != s.frame) {
2422 disp.frame = s.frame;
2423 flags |= eDisplayTransactionNeeded;
2424 }
2425 if (disp.viewport != s.viewport) {
2426 disp.viewport = s.viewport;
2427 flags |= eDisplayTransactionNeeded;
2428 }
2429 }
Michael Lentine47e45402014-07-18 15:34:25 -07002430 if (what & DisplayState::eDisplaySizeChanged) {
2431 if (disp.width != s.width) {
2432 disp.width = s.width;
2433 flags |= eDisplayTransactionNeeded;
2434 }
2435 if (disp.height != s.height) {
2436 disp.height = s.height;
2437 flags |= eDisplayTransactionNeeded;
2438 }
2439 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002440 }
2441 return flags;
2442}
2443
2444uint32_t SurfaceFlinger::setClientStateLocked(
2445 const sp<Client>& client,
2446 const layer_state_t& s)
2447{
2448 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002449 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002450 if (layer != 0) {
2451 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002452 bool geometryAppliesWithResize =
2453 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002455 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002456 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002457 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002458 }
2459 if (what & layer_state_t::eLayerChanged) {
2460 // NOTE: index needs to be calculated before we update the state
2461 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002462 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002463 mCurrentState.layersSortedByZ.removeAt(idx);
2464 mCurrentState.layersSortedByZ.add(layer);
2465 // we need traversal (state changed)
2466 // AND transaction (list changed)
2467 flags |= eTransactionNeeded|eTraversalNeeded;
2468 }
2469 }
2470 if (what & layer_state_t::eSizeChanged) {
2471 if (layer->setSize(s.w, s.h)) {
2472 flags |= eTraversalNeeded;
2473 }
2474 }
2475 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002477 flags |= eTraversalNeeded;
2478 }
2479 if (what & layer_state_t::eMatrixChanged) {
2480 if (layer->setMatrix(s.matrix))
2481 flags |= eTraversalNeeded;
2482 }
2483 if (what & layer_state_t::eTransparentRegionChanged) {
2484 if (layer->setTransparentRegionHint(s.transparentRegion))
2485 flags |= eTraversalNeeded;
2486 }
Dan Stoza23116082015-06-18 14:58:39 -07002487 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002488 if (layer->setFlags(s.flags, s.mask))
2489 flags |= eTraversalNeeded;
2490 }
2491 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002492 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002493 flags |= eTraversalNeeded;
2494 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002495 if (what & layer_state_t::eFinalCropChanged) {
2496 if (layer->setFinalCrop(s.finalCrop))
2497 flags |= eTraversalNeeded;
2498 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 if (what & layer_state_t::eLayerStackChanged) {
2500 // NOTE: index needs to be calculated before we update the state
2501 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002502 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 mCurrentState.layersSortedByZ.removeAt(idx);
2504 mCurrentState.layersSortedByZ.add(layer);
2505 // we need traversal (state changed)
2506 // AND transaction (list changed)
2507 flags |= eTransactionNeeded|eTraversalNeeded;
2508 }
2509 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002510 if (what & layer_state_t::eDeferTransaction) {
2511 layer->deferTransactionUntil(s.handle, s.frameNumber);
2512 // We don't trigger a traversal here because if no other state is
2513 // changed, we don't want this to cause any more work
2514 }
Robert Carrc3574f72016-03-24 12:19:32 -07002515 if (what & layer_state_t::eOverrideScalingModeChanged) {
2516 layer->setOverrideScalingMode(s.overrideScalingMode);
2517 // We don't trigger a traversal here because if no other state is
2518 // changed, we don't want this to cause any more work
2519 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002520 }
2521 return flags;
2522}
2523
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002524status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002525 const String8& name,
2526 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002527 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2528 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002530 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002531 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002532 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002533 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002534 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002535
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002536 status_t result = NO_ERROR;
2537
2538 sp<Layer> layer;
2539
Mathias Agopian3165cc22012-08-08 19:42:09 -07002540 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2541 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002542 result = createNormalLayer(client,
2543 name, w, h, flags, format,
2544 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002546 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002547 result = createDimLayer(client,
2548 name, w, h, flags,
2549 handle, gbp, &layer);
2550 break;
2551 default:
2552 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 break;
2554 }
2555
Dan Stoza7d89d062015-04-30 13:29:25 -07002556 if (result != NO_ERROR) {
2557 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002559
2560 result = addClientLayer(client, *handle, *gbp, layer);
2561 if (result != NO_ERROR) {
2562 return result;
2563 }
Irvelffc9efc2016-07-27 15:16:37 -07002564 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002565
2566 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002567 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568}
2569
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002570status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2571 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2572 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573{
2574 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002575 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 case PIXEL_FORMAT_TRANSPARENT:
2577 case PIXEL_FORMAT_TRANSLUCENT:
2578 format = PIXEL_FORMAT_RGBA_8888;
2579 break;
2580 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002581 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 break;
2583 }
2584
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002585 *outLayer = new Layer(this, client, name, w, h, flags);
2586 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2587 if (err == NO_ERROR) {
2588 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002589 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002591
2592 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2593 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594}
2595
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002596status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2597 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2598 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002600 *outLayer = new LayerDim(this, client, name, w, h, flags);
2601 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002602 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002603 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002604}
2605
Mathias Agopianac9fa422013-02-11 16:40:36 -08002606status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607{
Mathias Agopian67106042013-03-14 19:18:13 -07002608 // called by the window manager when it wants to remove a Layer
2609 status_t err = NO_ERROR;
2610 sp<Layer> l(client->getLayerUser(handle));
2611 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002612 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002613 err = removeLayer(l);
2614 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2615 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002616 }
2617 return err;
2618}
2619
Mathias Agopian13127d82013-03-05 17:47:11 -08002620status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002621{
Mathias Agopian67106042013-03-14 19:18:13 -07002622 // called by ~LayerCleaner() when all references to the IBinder (handle)
2623 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002624 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625}
2626
Mathias Agopianb60314a2012-04-10 22:09:54 -07002627// ---------------------------------------------------------------------------
2628
Andy McFadden13a082e2012-08-24 10:16:42 -07002629void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002630 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002631 Vector<ComposerState> state;
2632 Vector<DisplayState> displays;
2633 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002634 d.what = DisplayState::eDisplayProjectionChanged |
2635 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002636 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002637 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002638 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002639 d.frame.makeInvalid();
2640 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002641 d.width = 0;
2642 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002643 displays.add(d);
2644 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002645 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002646
Dan Stoza9e56aa02015-11-02 13:00:03 -08002647 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2648 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002649 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002650}
2651
2652void SurfaceFlinger::initializeDisplays() {
2653 class MessageScreenInitialized : public MessageBase {
2654 SurfaceFlinger* flinger;
2655 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002656 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002657 virtual bool handler() {
2658 flinger->onInitializeDisplays();
2659 return true;
2660 }
2661 };
2662 sp<MessageBase> msg = new MessageScreenInitialized(this);
2663 postMessageAsync(msg); // we may be called from main thread, use async message
2664}
2665
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002666void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2667 int mode) {
2668 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2669 this);
2670 int32_t type = hw->getDisplayType();
2671 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002672
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002673 if (mode == currentMode) {
2674 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002675 return;
2676 }
2677
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002678 hw->setPowerMode(mode);
2679 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2680 ALOGW("Trying to set power mode for virtual display");
2681 return;
2682 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002683
Irvelffc9efc2016-07-27 15:16:37 -07002684 if (mInterceptor.isEnabled()) {
2685 Mutex::Autolock _l(mStateLock);
2686 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2687 if (idx < 0) {
2688 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2689 return;
2690 }
2691 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2692 }
2693
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002694 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002695 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002696 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002697 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2698 // FIXME: eventthread only knows about the main display right now
2699 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002700 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002703 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002704 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002705 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002706
2707 struct sched_param param = {0};
2708 param.sched_priority = 1;
2709 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2710 ALOGW("Couldn't set SCHED_FIFO on display on");
2711 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002712 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002713 // Turn off the display
2714 struct sched_param param = {0};
2715 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2716 ALOGW("Couldn't set SCHED_OTHER on display off");
2717 }
2718
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002719 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002720 disableHardwareVsync(true); // also cancels any in-progress resync
2721
Mathias Agopiancde87a32012-09-13 14:09:01 -07002722 // FIXME: eventthread only knows about the main display right now
2723 mEventThread->onScreenReleased();
2724 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002726 getHwComposer().setPowerMode(type, mode);
2727 mVisibleRegionsDirty = true;
2728 // from this point on, SF will stop drawing on this display
2729 } else {
2730 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002731 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002732}
2733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002734void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2735 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002736 SurfaceFlinger& mFlinger;
2737 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002738 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002739 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002740 MessageSetPowerMode(SurfaceFlinger& flinger,
2741 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2742 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002743 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002744 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002745 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002746 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002747 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002748 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002749 ALOGW("Attempt to set power mode = %d for virtual display",
2750 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002751 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002752 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002753 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002754 return true;
2755 }
2756 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002757 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002758 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002759}
2760
2761// ---------------------------------------------------------------------------
2762
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2764{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002766
Mathias Agopianbd115332013-04-18 16:41:04 -07002767 IPCThreadState* ipc = IPCThreadState::self();
2768 const int pid = ipc->getCallingPid();
2769 const int uid = ipc->getCallingUid();
2770 if ((uid != AID_SHELL) &&
2771 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002772 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002773 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002775 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002776 // (this would indicate SF is stuck, but we want to be able to
2777 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002778 status_t err = mStateLock.timedLock(s2ns(1));
2779 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002780 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002781 result.appendFormat(
2782 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2783 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002784 }
2785
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002786 bool dumpAll = true;
2787 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002788 size_t numArgs = args.size();
2789 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002790 if ((index < numArgs) &&
2791 (args[index] == String16("--list"))) {
2792 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002793 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002794 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002795 }
2796
2797 if ((index < numArgs) &&
2798 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002799 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002800 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002801 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002802 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002803
2804 if ((index < numArgs) &&
2805 (args[index] == String16("--latency-clear"))) {
2806 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002807 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002808 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002809 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002810
2811 if ((index < numArgs) &&
2812 (args[index] == String16("--dispsync"))) {
2813 index++;
2814 mPrimaryDispSync.dump(result);
2815 dumpAll = false;
2816 }
Dan Stozab90cf072015-03-05 11:05:59 -08002817
2818 if ((index < numArgs) &&
2819 (args[index] == String16("--static-screen"))) {
2820 index++;
2821 dumpStaticScreenStats(result);
2822 dumpAll = false;
2823 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002824
2825 if ((index < numArgs) &&
2826 (args[index] == String16("--fences"))) {
2827 index++;
2828 mFenceTracker.dump(&result);
2829 dumpAll = false;
2830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002833 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002834 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002835 }
2836
Mathias Agopian9795c422009-08-26 16:36:26 -07002837 if (locked) {
2838 mStateLock.unlock();
2839 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 }
2841 write(fd, result.string(), result.size());
2842 return NO_ERROR;
2843}
2844
Dan Stozac7014012014-02-14 15:03:43 -08002845void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2846 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002847{
2848 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2849 const size_t count = currentLayers.size();
2850 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002851 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002852 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002853 }
2854}
2855
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002856void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002857 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002858{
2859 String8 name;
2860 if (index < args.size()) {
2861 name = String8(args[index]);
2862 index++;
2863 }
2864
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2866 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002867 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002868
2869 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002870 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002871 } else {
2872 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2873 const size_t count = currentLayers.size();
2874 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002875 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002876 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002877 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002878 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002879 }
2880 }
2881}
2882
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002883void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002884 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002885{
2886 String8 name;
2887 if (index < args.size()) {
2888 name = String8(args[index]);
2889 index++;
2890 }
2891
2892 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2893 const size_t count = currentLayers.size();
2894 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002895 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002896 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002897 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002898 }
2899 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002900
Svetoslavd85084b2014-03-20 10:28:31 -07002901 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002902}
2903
Jamie Gennis6547ff42013-07-16 20:12:42 -07002904// This should only be called from the main thread. Otherwise it would need
2905// the lock and should use mCurrentState rather than mDrawingState.
2906void SurfaceFlinger::logFrameStats() {
2907 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2908 const size_t count = drawingLayers.size();
2909 for (size_t i=0 ; i<count ; i++) {
2910 const sp<Layer>& layer(drawingLayers[i]);
2911 layer->logFrameStats();
2912 }
2913
2914 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2915}
2916
Andy McFadden4803b742012-09-24 19:07:20 -07002917/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2918{
2919 static const char* config =
2920 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002921#ifdef HAS_CONTEXT_PRIORITY
2922 " HAS_CONTEXT_PRIORITY"
2923#endif
2924#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2925 " NEVER_DEFAULT_TO_ASYNC_MODE"
2926#endif
2927#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2928 " TARGET_DISABLE_TRIPLE_BUFFERING"
2929#endif
2930 "]";
2931 result.append(config);
2932}
2933
Dan Stozab90cf072015-03-05 11:05:59 -08002934void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2935{
2936 result.appendFormat("Static screen stats:\n");
2937 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2938 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2939 float percent = 100.0f *
2940 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2941 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2942 b + 1, bucketTimeSec, percent);
2943 }
2944 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2945 float percent = 100.0f *
2946 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2947 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2948 NUM_BUCKETS - 1, bucketTimeSec, percent);
2949}
2950
Dan Stozae77c7662016-05-13 11:37:28 -07002951void SurfaceFlinger::recordBufferingStats(const char* layerName,
2952 std::vector<OccupancyTracker::Segment>&& history) {
2953 Mutex::Autolock lock(mBufferingStatsMutex);
2954 auto& stats = mBufferingStats[layerName];
2955 for (const auto& segment : history) {
2956 if (!segment.usedThirdBuffer) {
2957 stats.twoBufferTime += segment.totalTime;
2958 }
2959 if (segment.occupancyAverage < 1.0f) {
2960 stats.doubleBufferedTime += segment.totalTime;
2961 } else if (segment.occupancyAverage < 2.0f) {
2962 stats.tripleBufferedTime += segment.totalTime;
2963 }
2964 ++stats.numSegments;
2965 stats.totalTime += segment.totalTime;
2966 }
2967}
2968
2969void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2970 result.append("Buffering stats:\n");
2971 result.append(" [Layer name] <Active time> <Two buffer> "
2972 "<Double buffered> <Triple buffered>\n");
2973 Mutex::Autolock lock(mBufferingStatsMutex);
2974 typedef std::tuple<std::string, float, float, float> BufferTuple;
2975 std::map<float, BufferTuple, std::greater<float>> sorted;
2976 for (const auto& statsPair : mBufferingStats) {
2977 const char* name = statsPair.first.c_str();
2978 const BufferingStats& stats = statsPair.second;
2979 if (stats.numSegments == 0) {
2980 continue;
2981 }
2982 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2983 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2984 stats.totalTime;
2985 float doubleBufferRatio = static_cast<float>(
2986 stats.doubleBufferedTime) / stats.totalTime;
2987 float tripleBufferRatio = static_cast<float>(
2988 stats.tripleBufferedTime) / stats.totalTime;
2989 sorted.insert({activeTime, {name, twoBufferRatio,
2990 doubleBufferRatio, tripleBufferRatio}});
2991 }
2992 for (const auto& sortedPair : sorted) {
2993 float activeTime = sortedPair.first;
2994 const BufferTuple& values = sortedPair.second;
2995 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2996 std::get<0>(values).c_str(), activeTime,
2997 std::get<1>(values), std::get<2>(values),
2998 std::get<3>(values));
2999 }
3000 result.append("\n");
3001}
3002
3003
Mathias Agopian74d211a2013-04-22 16:55:35 +02003004void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3005 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003006{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003007 bool colorize = false;
3008 if (index < args.size()
3009 && (args[index] == String16("--color"))) {
3010 colorize = true;
3011 index++;
3012 }
3013
3014 Colorizer colorizer(colorize);
3015
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003016 // figure out if we're stuck somewhere
3017 const nsecs_t now = systemTime();
3018 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3019 const nsecs_t inTransaction(mDebugInTransaction);
3020 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3021 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3022
3023 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003024 * Dump library configuration.
3025 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003026
3027 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003028 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003029 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003030 appendSfConfigString(result);
3031 appendUiConfigString(result);
3032 appendGuiConfigString(result);
3033 result.append("\n");
3034
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003035 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003036 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003037 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003038 result.append(SyncFeatures::getInstance().toString());
3039 result.append("\n");
3040
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3042
Andy McFadden41d67d72014-04-25 16:58:34 -07003043 colorizer.bold(result);
3044 result.append("DispSync configuration: ");
3045 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003046 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3047 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3049 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003050 result.append("\n");
3051
Dan Stozab90cf072015-03-05 11:05:59 -08003052 // Dump static screen stats
3053 result.append("\n");
3054 dumpStaticScreenStats(result);
3055 result.append("\n");
3056
Dan Stozae77c7662016-05-13 11:37:28 -07003057 dumpBufferingStats(result);
3058
Andy McFadden4803b742012-09-24 19:07:20 -07003059 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003060 * Dump the visible layer list
3061 */
3062 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3063 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003064 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003065 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003066 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003067 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003068 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003069 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003070 }
3071
3072 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003073 * Dump Display state
3074 */
3075
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003076 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003077 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003078 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003079 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3080 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003081 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003082 }
3083
3084 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003085 * Dump SurfaceFlinger global state
3086 */
3087
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003088 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003089 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003090 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003091
Mathias Agopian888c8222012-08-04 21:10:38 -07003092 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003093 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003094
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003095 colorizer.bold(result);
3096 result.appendFormat("EGL implementation : %s\n",
3097 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3098 colorizer.reset(result);
3099 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003100 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003101
Mathias Agopian875d8e12013-06-07 15:35:48 -07003102 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003103
Mathias Agopian42977342012-08-05 00:40:46 -07003104 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003105 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3106 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003107 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003108 " last eglSwapBuffers() time: %f us\n"
3109 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003110 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003111 " refresh-rate : %f fps\n"
3112 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003113 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003114 " gpu_to_cpu_unsupported : %d\n"
3115 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003116 mLastSwapBufferTime/1000.0,
3117 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003118 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003119 1e9 / activeConfig->getVsyncPeriod(),
3120 activeConfig->getDpiX(),
3121 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003122 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003123
Mathias Agopian74d211a2013-04-22 16:55:35 +02003124 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003126
Mathias Agopian74d211a2013-04-22 16:55:35 +02003127 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003128 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003129
3130 /*
3131 * VSYNC state
3132 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003133 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003134 result.append("\n");
3135
3136 /*
3137 * HWC layer minidump
3138 */
3139 for (size_t d = 0; d < mDisplays.size(); d++) {
3140 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3141 int32_t hwcId = displayDevice->getHwcDisplayId();
3142 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3143 continue;
3144 }
3145
3146 result.appendFormat("Display %d HWC layers:\n", hwcId);
3147 Layer::miniDumpHeader(result);
3148 for (size_t l = 0; l < count; l++) {
3149 const sp<Layer>& layer(currentLayers[l]);
3150 layer->miniDump(result, hwcId);
3151 }
3152 result.append("\n");
3153 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003154
3155 /*
3156 * Dump HWComposer state
3157 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003158 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003159 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003160 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003161 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003162 result.appendFormat(" h/w composer %s\n",
3163 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003164 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003165
3166 /*
3167 * Dump gralloc state
3168 */
3169 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3170 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003171}
3172
Mathias Agopian13127d82013-03-05 17:47:11 -08003173const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003174SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003175 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003176 wp<IBinder> dpy;
3177 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3178 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3179 dpy = mDisplays.keyAt(i);
3180 break;
3181 }
3182 }
3183 if (dpy == NULL) {
3184 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3185 // Just use the primary display so we have something to return
3186 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3187 }
3188 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003189}
3190
Keun young Park63f165f2012-08-31 10:53:36 -07003191bool SurfaceFlinger::startDdmConnection()
3192{
3193 void* libddmconnection_dso =
3194 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3195 if (!libddmconnection_dso) {
3196 return false;
3197 }
3198 void (*DdmConnection_start)(const char* name);
3199 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003200 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003201 if (!DdmConnection_start) {
3202 dlclose(libddmconnection_dso);
3203 return false;
3204 }
3205 (*DdmConnection_start)(getServiceName());
3206 return true;
3207}
3208
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003209status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 switch (code) {
3211 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003212 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003213 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003215 case CLEAR_ANIMATION_FRAME_STATS:
3216 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003217 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003218 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 {
3220 // codes that require permission check
3221 IPCThreadState* ipc = IPCThreadState::self();
3222 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003223 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003224 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003225 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003226 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003227 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003229 break;
3230 }
3231 case CAPTURE_SCREEN:
3232 {
3233 // codes that require permission check
3234 IPCThreadState* ipc = IPCThreadState::self();
3235 const int pid = ipc->getCallingPid();
3236 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003237 if ((uid != AID_GRAPHICS) &&
3238 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003239 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003240 return PERMISSION_DENIED;
3241 }
3242 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 }
3244 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003245 return OK;
3246}
3247
3248status_t SurfaceFlinger::onTransact(
3249 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3250{
3251 status_t credentialCheck = CheckTransactCodeCredentials(code);
3252 if (credentialCheck != OK) {
3253 return credentialCheck;
3254 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3257 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003258 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003259 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003260 IPCThreadState* ipc = IPCThreadState::self();
3261 const int pid = ipc->getCallingPid();
3262 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003263 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003264 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 return PERMISSION_DENIED;
3266 }
3267 int n;
3268 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003269 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003270 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 return NO_ERROR;
3272 case 1002: // SHOW_UPDATES
3273 n = data.readInt32();
3274 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003275 invalidateHwcGeometry();
3276 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003279 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003280 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003282 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283 setTransactionFlags(
3284 eTransactionNeeded|
3285 eDisplayTransactionNeeded|
3286 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003287 return NO_ERROR;
3288 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003289 case 1006:{ // send empty update
3290 signalRefresh();
3291 return NO_ERROR;
3292 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003293 case 1008: // toggle use of hw composer
3294 n = data.readInt32();
3295 mDebugDisableHWC = n ? 1 : 0;
3296 invalidateHwcGeometry();
3297 repaintEverything();
3298 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003299 case 1009: // toggle use of transform hint
3300 n = data.readInt32();
3301 mDebugDisableTransformHint = n ? 1 : 0;
3302 invalidateHwcGeometry();
3303 repaintEverything();
3304 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003306 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003307 reply->writeInt32(0);
3308 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003309 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003310 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003311 return NO_ERROR;
3312 case 1013: {
3313 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003314 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3315 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003316 return NO_ERROR;
3317 }
3318 case 1014: {
3319 // daltonize
3320 n = data.readInt32();
3321 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003322 case 1:
3323 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3324 break;
3325 case 2:
3326 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3327 break;
3328 case 3:
3329 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3330 break;
3331 default:
3332 mDaltonizer.setType(ColorBlindnessType::None);
3333 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003334 }
3335 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003336 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003337 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003338 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003339 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003340 invalidateHwcGeometry();
3341 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003342 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003344 case 1015: {
3345 // apply a color matrix
3346 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003347 if (n) {
3348 // color matrix is sent as mat3 matrix followed by vec3
3349 // offset, then packed into a mat4 where the last row is
3350 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003351 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003352 for (size_t j = 0; j < 4; j++) {
3353 mColorMatrix[i][j] = data.readFloat();
3354 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003355 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003356 } else {
3357 mColorMatrix = mat4();
3358 }
3359 invalidateHwcGeometry();
3360 repaintEverything();
3361 return NO_ERROR;
3362 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003363 // This is an experimental interface
3364 // Needs to be shifted to proper binder interface when we productize
3365 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003366 n = data.readInt32();
3367 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003368 return NO_ERROR;
3369 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003370 case 1017: {
3371 n = data.readInt32();
3372 mForceFullDamage = static_cast<bool>(n);
3373 return NO_ERROR;
3374 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003375 case 1018: { // Modify Choreographer's phase offset
3376 n = data.readInt32();
3377 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3378 return NO_ERROR;
3379 }
3380 case 1019: { // Modify SurfaceFlinger's phase offset
3381 n = data.readInt32();
3382 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3383 return NO_ERROR;
3384 }
Irvel468051e2016-06-13 16:44:44 -07003385 case 1020: { // Layer updates interceptor
3386 n = data.readInt32();
3387 if (n) {
3388 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003389 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003390 }
3391 else{
3392 ALOGV("Interceptor disabled");
3393 mInterceptor.disable();
3394 }
3395 return NO_ERROR;
3396 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003397 case 1021: { // Disable HWC virtual displays
3398 n = data.readInt32();
3399 mUseHwcVirtualDisplays = !n;
3400 return NO_ERROR;
3401 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402 }
3403 }
3404 return err;
3405}
3406
Mathias Agopian53331da2011-08-22 21:44:41 -07003407void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003408 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003409 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003410}
3411
Mathias Agopian59119e62010-10-11 12:37:43 -07003412// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003413// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003414// ---------------------------------------------------------------------------
3415
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003416/* The code below is here to handle b/8734824
3417 *
3418 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003419 * from the surfaceflinger thread to the calling binder thread, where they
3420 * are executed. This allows the calling thread in the calling process to be
3421 * reused and not depend on having "enough" binder threads to handle the
3422 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003423 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003424class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003425 /* Parts of GraphicProducerWrapper are run on two different threads,
3426 * communicating by sending messages via Looper but also by shared member
3427 * data. Coherence maintenance is subtle and in places implicit (ugh).
3428 *
3429 * Don't rely on Looper's sendMessage/handleMessage providing
3430 * release/acquire semantics for any data not actually in the Message.
3431 * Data going from surfaceflinger to binder threads needs to be
3432 * synchronized explicitly.
3433 *
3434 * Barrier open/wait do provide release/acquire semantics. This provides
3435 * implicit synchronization for data coming back from binder to
3436 * surfaceflinger threads.
3437 */
3438
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003439 sp<IGraphicBufferProducer> impl;
3440 sp<Looper> looper;
3441 status_t result;
3442 bool exitPending;
3443 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003444 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003445 uint32_t code;
3446 Parcel const* data;
3447 Parcel* reply;
3448
3449 enum {
3450 MSG_API_CALL,
3451 MSG_EXIT
3452 };
3453
3454 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003455 * Called on surfaceflinger thread. This is called by our "fake"
3456 * BpGraphicBufferProducer. We package the data and reply Parcel and
3457 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003458 */
3459 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003460 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003461 this->code = code;
3462 this->data = &data;
3463 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003464 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003465 // if we've exited, we run the message synchronously right here.
3466 // note (JH): as far as I can tell from looking at the code, this
3467 // never actually happens. if it does, i'm not sure if it happens
3468 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003469 handleMessage(Message(MSG_API_CALL));
3470 } else {
3471 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003472 // Prevent stores to this->{code, data, reply} from being
3473 // reordered later than the construction of Message.
3474 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003475 looper->sendMessage(this, Message(MSG_API_CALL));
3476 barrier.wait();
3477 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003478 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003479 }
3480
3481 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003482 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003483 * call the real BpGraphicBufferProducer.
3484 */
3485 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003486 int what = message.what;
3487 // Prevent reads below from happening before the read from Message
3488 atomic_thread_fence(memory_order_acquire);
3489 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003490 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003491 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003492 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003493 exitRequested = true;
3494 }
3495 }
3496
3497public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003498 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003499 : impl(impl),
3500 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003501 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003502 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003503 exitRequested(false),
3504 code(0),
3505 data(NULL),
3506 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003507 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003508
Jesse Hallb154c422014-07-13 12:47:02 -07003509 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003510 status_t waitForResponse() {
3511 do {
3512 looper->pollOnce(-1);
3513 } while (!exitRequested);
3514 return result;
3515 }
3516
Jesse Hallb154c422014-07-13 12:47:02 -07003517 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003518 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003519 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003520 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003521 // Ensure this->result is visible to the binder thread before it
3522 // handles the message.
3523 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003524 looper->sendMessage(this, Message(MSG_EXIT));
3525 }
3526};
3527
3528
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003529status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3530 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003531 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003532 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003533 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003534
3535 if (CC_UNLIKELY(display == 0))
3536 return BAD_VALUE;
3537
3538 if (CC_UNLIKELY(producer == 0))
3539 return BAD_VALUE;
3540
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003541 // if we have secure windows on this display, never allow the screen capture
3542 // unless the producer interface is local (i.e.: we can take a screenshot for
3543 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003544 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003545
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003546 // Convert to surfaceflinger's internal rotation type.
3547 Transform::orientation_flags rotationFlags;
3548 switch (rotation) {
3549 case ISurfaceComposer::eRotateNone:
3550 rotationFlags = Transform::ROT_0;
3551 break;
3552 case ISurfaceComposer::eRotate90:
3553 rotationFlags = Transform::ROT_90;
3554 break;
3555 case ISurfaceComposer::eRotate180:
3556 rotationFlags = Transform::ROT_180;
3557 break;
3558 case ISurfaceComposer::eRotate270:
3559 rotationFlags = Transform::ROT_270;
3560 break;
3561 default:
3562 rotationFlags = Transform::ROT_0;
3563 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3564 break;
3565 }
3566
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003567 class MessageCaptureScreen : public MessageBase {
3568 SurfaceFlinger* flinger;
3569 sp<IBinder> display;
3570 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003571 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003572 uint32_t reqWidth, reqHeight;
3573 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003574 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003575 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003576 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003577 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003578 public:
3579 MessageCaptureScreen(SurfaceFlinger* flinger,
3580 const sp<IBinder>& display,
3581 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003582 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003583 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003584 bool useIdentityTransform,
3585 Transform::orientation_flags rotation,
3586 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003587 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003588 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003589 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003590 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003591 rotation(rotation), result(PERMISSION_DENIED),
3592 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003593 {
3594 }
3595 status_t getResult() const {
3596 return result;
3597 }
3598 virtual bool handler() {
3599 Mutex::Autolock _l(flinger->mStateLock);
3600 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003601 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003602 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003603 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003604 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003605 return true;
3606 }
3607 };
3608
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003609 // this creates a "fake" BBinder which will serve as a "fake" remote
3610 // binder to receive the marshaled calls and forward them to the
3611 // real remote (a BpGraphicBufferProducer)
3612 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3613
3614 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3615 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003616 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003617 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003618 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003619 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003620
3621 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003622 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003623 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003624 }
3625 return res;
3626}
3627
Mathias Agopian180f10d2013-04-10 22:55:41 -07003628
3629void SurfaceFlinger::renderScreenImplLocked(
3630 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003631 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003632 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003633 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003634{
3635 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003636 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003637
3638 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003639 const int32_t hw_w = hw->getWidth();
3640 const int32_t hw_h = hw->getHeight();
3641 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003642 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003643
Dan Stozac1879002014-05-22 15:59:05 -07003644 // if a default or invalid sourceCrop is passed in, set reasonable values
3645 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3646 !sourceCrop.isValid()) {
3647 sourceCrop.setLeftTop(Point(0, 0));
3648 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3649 }
3650
3651 // ensure that sourceCrop is inside screen
3652 if (sourceCrop.left < 0) {
3653 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3654 }
Dan Stozabe31f442014-06-11 11:20:54 -07003655 if (sourceCrop.right > hw_w) {
3656 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003657 }
3658 if (sourceCrop.top < 0) {
3659 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3660 }
Dan Stozabe31f442014-06-11 11:20:54 -07003661 if (sourceCrop.bottom > hw_h) {
3662 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003663 }
3664
Mathias Agopian180f10d2013-04-10 22:55:41 -07003665 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003666 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003667
3668 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003669 engine.setViewportAndProjection(
3670 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003671 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003672
3673 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003674 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003675
3676 const LayerVector& layers( mDrawingState.layersSortedByZ );
3677 const size_t count = layers.size();
3678 for (size_t i=0 ; i<count ; ++i) {
3679 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003680 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003681 if (state.layerStack == hw->getLayerStack()) {
3682 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3683 if (layer->isVisible()) {
3684 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003685 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003686 if (filtering) layer->setFiltering(false);
3687 }
3688 }
3689 }
3690 }
3691
Mathias Agopian931bda12013-08-28 18:11:46 -07003692 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003693}
3694
3695
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003696status_t SurfaceFlinger::captureScreenImplLocked(
3697 const sp<const DisplayDevice>& hw,
3698 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003699 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003700 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003701 bool useIdentityTransform, Transform::orientation_flags rotation,
3702 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003703{
3704 ATRACE_CALL();
3705
Mathias Agopian180f10d2013-04-10 22:55:41 -07003706 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003707 uint32_t hw_w = hw->getWidth();
3708 uint32_t hw_h = hw->getHeight();
3709
3710 if (rotation & Transform::ROT_90) {
3711 std::swap(hw_w, hw_h);
3712 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003713
Mathias Agopian180f10d2013-04-10 22:55:41 -07003714 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3715 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3716 reqWidth, reqHeight, hw_w, hw_h);
3717 return BAD_VALUE;
3718 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003719
Mathias Agopian180f10d2013-04-10 22:55:41 -07003720 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3721 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3722
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003723 bool secureLayerIsVisible = false;
3724 const LayerVector& layers(mDrawingState.layersSortedByZ);
3725 const size_t count = layers.size();
3726 for (size_t i = 0 ; i < count ; ++i) {
3727 const sp<Layer>& layer(layers[i]);
3728 const Layer::State& state(layer->getDrawingState());
3729 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3730 state.z <= maxLayerZ && layer->isVisible() &&
3731 layer->isSecure()) {
3732 secureLayerIsVisible = true;
3733 }
3734 }
3735
3736 if (!isLocalScreenshot && secureLayerIsVisible) {
3737 ALOGW("FB is protected: PERMISSION_DENIED");
3738 return PERMISSION_DENIED;
3739 }
3740
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003741 // create a surface (because we're a producer, and we need to
3742 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003743 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003744
3745 // Put the screenshot Surface into async mode so that
3746 // Layer::headFenceHasSignaled will always return true and we'll latch the
3747 // first buffer regardless of whether or not its acquire fence has
3748 // signaled. This is needed to avoid a race condition in the rotation
3749 // animation. See b/30209608
3750 sur->setAsyncMode(true);
3751
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003752 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003753
Michael Lentine5a16a622015-05-21 13:48:24 -07003754 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3755 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003756 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3757 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003758
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003759 int err = 0;
3760 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003761 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003762 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3763 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003764
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003765 if (err == NO_ERROR) {
3766 ANativeWindowBuffer* buffer;
3767 /* TODO: Once we have the sync framework everywhere this can use
3768 * server-side waits on the fence that dequeueBuffer returns.
3769 */
3770 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3771 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003772 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003773 // create an EGLImage from the buffer so we can later
3774 // turn it into a texture
3775 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3776 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3777 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003778 // this binds the given EGLImage as a framebuffer for the
3779 // duration of this scope.
3780 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3781 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003782 // this will in fact render into our dequeued buffer
3783 // via an FBO, which means we didn't have to create
3784 // an EGLSurface and therefore we're not
3785 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003786 renderScreenImplLocked(
3787 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3788 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003789
Riley Andrews86639902014-08-15 12:27:24 -07003790 // Attempt to create a sync khr object that can produce a sync point. If that
3791 // isn't available, create a non-dupable sync object in the fallback path and
3792 // wait on it directly.
3793 EGLSyncKHR sync;
3794 if (!DEBUG_SCREENSHOTS) {
3795 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003796 // native fence fd will not be populated until flush() is done.
3797 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003798 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003799 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003800 }
Riley Andrews86639902014-08-15 12:27:24 -07003801 if (sync != EGL_NO_SYNC_KHR) {
3802 // get the sync fd
3803 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3804 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3805 ALOGW("captureScreen: failed to dup sync khr object");
3806 syncFd = -1;
3807 }
3808 eglDestroySyncKHR(mEGLDisplay, sync);
3809 } else {
3810 // fallback path
3811 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3812 if (sync != EGL_NO_SYNC_KHR) {
3813 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3814 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3815 EGLint eglErr = eglGetError();
3816 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3817 ALOGW("captureScreen: fence wait timed out");
3818 } else {
3819 ALOGW_IF(eglErr != EGL_SUCCESS,
3820 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3821 }
3822 eglDestroySyncKHR(mEGLDisplay, sync);
3823 } else {
3824 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3825 }
3826 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003827 if (DEBUG_SCREENSHOTS) {
3828 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3829 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3830 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3831 hw, minLayerZ, maxLayerZ);
3832 delete [] pixels;
3833 }
3834
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003835 } else {
3836 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3837 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003838 window->cancelBuffer(window, buffer, syncFd);
3839 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003840 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003841 // destroy our image
3842 eglDestroyImageKHR(mEGLDisplay, image);
3843 } else {
3844 result = BAD_VALUE;
3845 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003846 if (buffer) {
3847 // queueBuffer takes ownership of syncFd
3848 result = window->queueBuffer(window, buffer, syncFd);
3849 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003850 }
3851 } else {
3852 result = BAD_VALUE;
3853 }
3854 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3855 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003856
Mathias Agopian74c40c02010-09-29 13:02:36 -07003857 return result;
3858}
3859
Mathias Agopiand5556842013-09-19 17:08:37 -07003860void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3861 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003862 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003863 for (size_t y=0 ; y<h ; y++) {
3864 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3865 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003866 if (p[x] != 0xFF000000) return;
3867 }
3868 }
3869 ALOGE("*** we just took a black screenshot ***\n"
3870 "requested minz=%d, maxz=%d, layerStack=%d",
3871 minLayerZ, maxLayerZ, hw->getLayerStack());
3872 const LayerVector& layers( mDrawingState.layersSortedByZ );
3873 const size_t count = layers.size();
3874 for (size_t i=0 ; i<count ; ++i) {
3875 const sp<Layer>& layer(layers[i]);
3876 const Layer::State& state(layer->getDrawingState());
3877 const bool visible = (state.layerStack == hw->getLayerStack())
3878 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3879 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003880 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003881 visible ? '+' : '-',
3882 i, layer->getName().string(), state.layerStack, state.z,
3883 layer->isVisible(), state.flags, state.alpha);
3884 }
3885 }
3886}
3887
Pablo Ceballosce796e72016-02-04 19:10:51 -08003888bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3889 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3890 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3891}
3892
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003893// ---------------------------------------------------------------------------
3894
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003895SurfaceFlinger::LayerVector::LayerVector() {
3896}
3897
3898SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003899 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003900}
3901
3902int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3903 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003904{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003905 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003906 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3907 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003908
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003909 uint32_t ls = l->getCurrentState().layerStack;
3910 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003911 if (ls != rs)
3912 return ls - rs;
3913
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003914 uint32_t lz = l->getCurrentState().z;
3915 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003916 if (lz != rz)
3917 return lz - rz;
3918
3919 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003920}
3921
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003923
3924
3925#if defined(__gl_h_)
3926#error "don't include gl/gl.h in this file"
3927#endif
3928
3929#if defined(__gl2_h_)
3930#error "don't include gl2/gl2.h in this file"
3931#endif