blob: 2f273ae9097dfeb75480c2bc87c7dedeae63a21d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096// This is the phase offset in nanoseconds of the software vsync event
97// relative to the vsync event reported by HWComposer. The software vsync
98// event is when SurfaceFlinger and Choreographer-based applications run each
99// frame.
100//
101// This phase offset allows adjustment of the minimum latency from application
102// wake-up (by Choregographer) time to the time at which the resulting window
103// image is displayed. This value may be either positive (after the HW vsync)
104// or negative (before the HW vsync). Setting it to 0 will result in a
105// minimum latency of two vsync periods because the app and SurfaceFlinger
106// will run just after the HW vsync. Setting it to a positive number will
107// result in the minimum latency being:
108//
109// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
110//
111// Note that reducing this latency makes it more likely for the applications
112// to not have their window content image ready in time. When this happens
113// the latency will end up being an additional vsync period, and animations
114// will hiccup. Therefore, this latency should be tuned somewhat
115// conservatively (or at least with awareness of the trade-off being made).
116static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
117
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700118// This is the phase offset at which SurfaceFlinger's composition runs.
119static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121// ---------------------------------------------------------------------------
122
Mathias Agopian99b49842011-06-27 16:05:52 -0700123const String16 sHardwareTest("android.permission.HARDWARE_TEST");
124const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
125const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
126const String16 sDump("android.permission.DUMP");
127
128// ---------------------------------------------------------------------------
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700131 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700133 mTransactionPending(false),
134 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700136 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700137 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700153 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800157 mHasColorMatrix(false),
158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Steve Blocka19954a2012-01-04 20:05:49 +0000163 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164
165 // debugging stuff...
166 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700167
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700169 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 property_get("debug.sf.showupdates", value, "0");
172 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174 property_get("debug.sf.ddms", value, "0");
175 mDebugDDMS = atoi(value);
176 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700177 if (!startDdmConnection()) {
178 // start failed, and DDMS debugging not enabled
179 mDebugDDMS = 0;
180 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700181 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700182 ALOGI_IF(mDebugRegion, "showupdates enabled");
183 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700184
185 property_get("debug.sf.disable_backpressure", value, "0");
186 mPropagateBackpressure = !atoi(value);
187 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700188
189 property_get("debug.sf.disable_hwc_vds", value, "0");
190 mUseHwcVirtualDisplays = !atoi(value);
191 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192}
193
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800194void SurfaceFlinger::onFirstRef()
195{
196 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197}
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199SurfaceFlinger::~SurfaceFlinger()
200{
Mathias Agopiana4912602012-07-12 14:25:33 -0700201 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
202 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
203 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204}
205
Dan Stozac7014012014-02-14 15:03:43 -0800206void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207{
208 // the window manager died on us. prepare its eulogy.
209
Andy McFadden13a082e2012-08-24 10:16:42 -0700210 // restore initial conditions (default device unblank, etc)
211 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800212
213 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700214 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800215}
216
Mathias Agopian7e27f052010-05-28 14:22:23 -0700217sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218{
Mathias Agopian96f08192010-06-02 23:28:45 -0700219 sp<ISurfaceComposerClient> bclient;
220 sp<Client> client(new Client(this));
221 status_t err = client->initCheck();
222 if (err == NO_ERROR) {
223 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 return bclient;
226}
227
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700228sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
229 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700230{
231 class DisplayToken : public BBinder {
232 sp<SurfaceFlinger> flinger;
233 virtual ~DisplayToken() {
234 // no more references, this display must be terminated
235 Mutex::Autolock _l(flinger->mStateLock);
236 flinger->mCurrentState.displays.removeItem(this);
237 flinger->setTransactionFlags(eDisplayTransactionNeeded);
238 }
239 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700240 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241 : flinger(flinger) {
242 }
243 };
244
245 sp<BBinder> token = new DisplayToken(this);
246
247 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700248 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700249 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700250 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700251 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700252 return token;
253}
254
Jesse Hall6c913be2013-08-08 12:15:49 -0700255void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
256 Mutex::Autolock _l(mStateLock);
257
258 ssize_t idx = mCurrentState.displays.indexOfKey(display);
259 if (idx < 0) {
260 ALOGW("destroyDisplay: invalid display token");
261 return;
262 }
263
264 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
265 if (!info.isVirtualDisplay()) {
266 ALOGE("destroyDisplay called for non-virtual display");
267 return;
268 }
Irvelffc9efc2016-07-27 15:16:37 -0700269 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700270 mCurrentState.displays.removeItemsAt(idx);
271 setTransactionFlags(eDisplayTransactionNeeded);
272}
273
Jesse Hall692c7232012-11-08 15:41:56 -0800274void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800275 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800276 ALOGW_IF(mBuiltinDisplays[type],
277 "Overwriting display token for display type %d", type);
278 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800279 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700280 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800281 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700282 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800283}
284
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700286 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700287 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
288 return NULL;
289 }
Jesse Hall692c7232012-11-08 15:41:56 -0800290 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291}
292
Jamie Gennis9a78c902011-01-12 18:30:40 -0800293sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
294{
295 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
296 return gba;
297}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299void SurfaceFlinger::bootFinished()
300{
301 const nsecs_t now = systemTime();
302 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000303 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700304 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700305
306 // wait patiently for the window manager death
307 const String16 name("window");
308 sp<IBinder> window(defaultServiceManager()->getService(name));
309 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700310 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700311 }
312
313 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700314 // formerly we would just kill the process, but we now ask it to exit so it
315 // can choose where to stop the animation.
316 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700317
318 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
319 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
320 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Mathias Agopian3f844832013-08-07 21:24:32 -0700323void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700324 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 RenderEngine& engine;
326 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700327 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700328 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
329 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330 }
331 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700332 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700333 return true;
334 }
335 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700336 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337}
338
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700339class DispSyncSource : public VSyncSource, private DispSync::Callback {
340public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700341 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000342 const char* name) :
343 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700344 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700345 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
347 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700348 mDispSync(dispSync),
349 mCallbackMutex(),
350 mCallback(),
351 mVsyncMutex(),
352 mPhaseOffset(phaseOffset),
353 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700354
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700355 virtual ~DispSyncSource() {}
356
357 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700358 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700359 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000360 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 static_cast<DispSync::Callback*>(this));
362 if (err != NO_ERROR) {
363 ALOGE("error registering vsync callback: %s (%d)",
364 strerror(-err), err);
365 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700366 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 } else {
368 status_t err = mDispSync->removeEventListener(
369 static_cast<DispSync::Callback*>(this));
370 if (err != NO_ERROR) {
371 ALOGE("error unregistering vsync callback: %s (%d)",
372 strerror(-err), err);
373 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700374 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700376 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 }
378
379 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 mCallback = callback;
382 }
383
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700384 virtual void setPhaseOffset(nsecs_t phaseOffset) {
385 Mutex::Autolock lock(mVsyncMutex);
386
387 // Normalize phaseOffset to [0, period)
388 auto period = mDispSync->getPeriod();
389 phaseOffset %= period;
390 if (phaseOffset < 0) {
391 // If we're here, then phaseOffset is in (-period, 0). After this
392 // operation, it will be in (0, period)
393 phaseOffset += period;
394 }
395 mPhaseOffset = phaseOffset;
396
397 // If we're not enabled, we don't need to mess with the listeners
398 if (!mEnabled) {
399 return;
400 }
401
402 // Remove the listener with the old offset
403 status_t err = mDispSync->removeEventListener(
404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error unregistering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
409
410 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error registering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
417 }
418
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419private:
420 virtual void onDispSyncEvent(nsecs_t when) {
421 sp<VSyncSource::Callback> callback;
422 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 callback = mCallback;
425
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700426 if (mTraceVsync) {
427 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700429 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
431
432 if (callback != NULL) {
433 callback->onVSyncEvent(when);
434 }
435 }
436
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 const char* const mName;
438
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 int mValue;
440
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700441 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700442 const String8 mVsyncOnLabel;
443 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700444
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446
447 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449
450 Mutex mVsyncMutex; // Protects the following
451 nsecs_t mPhaseOffset;
452 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453};
454
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700455class InjectVSyncSource : public VSyncSource {
456public:
457 InjectVSyncSource() {}
458
459 virtual ~InjectVSyncSource() {}
460
461 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
462 std::lock_guard<std::mutex> lock(mCallbackMutex);
463 mCallback = callback;
464 }
465
466 virtual void onInjectSyncEvent(nsecs_t when) {
467 std::lock_guard<std::mutex> lock(mCallbackMutex);
468 mCallback->onVSyncEvent(when);
469 }
470
471 virtual void setVSyncEnabled(bool) {}
472 virtual void setPhaseOffset(nsecs_t) {}
473
474private:
475 std::mutex mCallbackMutex; // Protects the following
476 sp<VSyncSource::Callback> mCallback;
477};
478
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700480 ALOGI( "SurfaceFlinger's main thread ready to run. "
481 "Initializing graphics H/W...");
482
Dan Stoza9e56aa02015-11-02 13:00:03 -0800483 { // Autolock scope
484 Mutex::Autolock _l(mStateLock);
485
486 // initialize EGL for the default display
487 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
488 eglInitialize(mEGLDisplay, NULL, NULL);
489
490 // start the EventThread
491 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
492 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700493 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800494 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
495 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700496 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800497 mEventQueue.setEventThread(mSFEventThread);
498
Tim Murrayacff43d2016-07-29 13:57:24 -0700499 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700500 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700501 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700502 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
503 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
504 }
505
Dan Stoza9e56aa02015-11-02 13:00:03 -0800506 // Get a RenderEngine for the given display / config (can't fail)
507 mRenderEngine = RenderEngine::create(mEGLDisplay,
508 HAL_PIXEL_FORMAT_RGBA_8888);
509 }
510
511 // Drop the state lock while we initialize the hardware composer. We drop
512 // the lock because on creation, it will call back into SurfaceFlinger to
513 // initialize the primary display.
514 mHwc = new HWComposer(this);
515 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
516
Jesse Hall692c7232012-11-08 15:41:56 -0800517 Mutex::Autolock _l(mStateLock);
518
Mathias Agopian875d8e12013-06-07 15:35:48 -0700519 // retrieve the EGL context that was selected/created
520 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700521
Mathias Agopianda27af92012-09-13 18:17:13 -0700522 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
523 "couldn't create EGLContext");
524
Dan Stoza9e56aa02015-11-02 13:00:03 -0800525 // make the GLContext current so that we can create textures when creating
526 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700527 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
528
Jamie Gennisd1700752013-10-14 12:22:52 -0700529 mEventControlThread = new EventControlThread(this);
530 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
531
Mathias Agopian92a979a2012-08-02 18:32:23 -0700532 // initialize our drawing state
533 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700534
Andy McFadden13a082e2012-08-24 10:16:42 -0700535 // set initial conditions (e.g. unblank default device)
536 initializeDisplays();
537
Dan Stoza4e637772016-07-28 13:31:51 -0700538 mRenderEngine->primeCache();
539
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700540 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700541 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542
Dan Stoza9e56aa02015-11-02 13:00:03 -0800543 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700544}
545
Mathias Agopiana67e4182012-06-19 17:26:12 -0700546void SurfaceFlinger::startBootAnim() {
547 // start boot animation
548 property_set("service.bootanim.exit", "0");
549 property_set("ctl.start", "bootanim");
550}
551
Mathias Agopian875d8e12013-06-07 15:35:48 -0700552size_t SurfaceFlinger::getMaxTextureSize() const {
553 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700554}
555
Mathias Agopian875d8e12013-06-07 15:35:48 -0700556size_t SurfaceFlinger::getMaxViewportDims() const {
557 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700558}
559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800561
Jamie Gennis582270d2011-08-17 18:19:00 -0700562bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800563 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800564 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800565 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700566 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800567}
568
Brian Anderson069b3652016-07-22 10:32:47 -0700569status_t SurfaceFlinger::getSupportedFrameTimestamps(
570 std::vector<SupportableFrameTimestamps>* outSupported) const {
571 *outSupported = {
572 SupportableFrameTimestamps::REQUESTED_PRESENT,
573 SupportableFrameTimestamps::ACQUIRE,
574 SupportableFrameTimestamps::REFRESH_START,
575 SupportableFrameTimestamps::GL_COMPOSITION_DONE_TIME,
576 getHwComposer().retireFenceRepresentsStartOfScanout() ?
577 SupportableFrameTimestamps::DISPLAY_PRESENT_TIME :
578 SupportableFrameTimestamps::DISPLAY_RETIRE_TIME,
579 SupportableFrameTimestamps::RELEASE_TIME,
580 };
581 return NO_ERROR;
582}
583
Dan Stoza7f7da322014-05-02 15:26:25 -0700584status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
585 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700586 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700587 return BAD_VALUE;
588 }
589
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500590 if (!display.get())
591 return NAME_NOT_FOUND;
592
Jesse Hall692c7232012-11-08 15:41:56 -0800593 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700594 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800595 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700596 type = i;
597 break;
598 }
599 }
600
601 if (type < 0) {
602 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700603 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700604
Mathias Agopian8b736f12012-08-13 17:54:26 -0700605 // TODO: Not sure if display density should handled by SF any longer
606 class Density {
607 static int getDensityFromProperty(char const* propName) {
608 char property[PROPERTY_VALUE_MAX];
609 int density = 0;
610 if (property_get(propName, property, NULL) > 0) {
611 density = atoi(property);
612 }
613 return density;
614 }
615 public:
616 static int getEmuDensity() {
617 return getDensityFromProperty("qemu.sf.lcd_density"); }
618 static int getBuildDensity() {
619 return getDensityFromProperty("ro.sf.lcd_density"); }
620 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700621
Dan Stoza7f7da322014-05-02 15:26:25 -0700622 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700623
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700625 DisplayInfo info = DisplayInfo();
626
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627 float xdpi = hwConfig->getDpiX();
628 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700629
630 if (type == DisplayDevice::DISPLAY_PRIMARY) {
631 // The density of the device is provided by a build property
632 float density = Density::getBuildDensity() / 160.0f;
633 if (density == 0) {
634 // the build doesn't provide a density -- this is wrong!
635 // use xdpi instead
636 ALOGE("ro.sf.lcd_density must be defined as a build property");
637 density = xdpi / 160.0f;
638 }
639 if (Density::getEmuDensity()) {
640 // if "qemu.sf.lcd_density" is specified, it overrides everything
641 xdpi = ydpi = density = Density::getEmuDensity();
642 density /= 160.0f;
643 }
644 info.density = density;
645
646 // TODO: this needs to go away (currently needed only by webkit)
647 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
648 info.orientation = hw->getOrientation();
649 } else {
650 // TODO: where should this value come from?
651 static const int TV_DENSITY = 213;
652 info.density = TV_DENSITY / 160.0f;
653 info.orientation = 0;
654 }
655
Dan Stoza9e56aa02015-11-02 13:00:03 -0800656 info.w = hwConfig->getWidth();
657 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700658 info.xdpi = xdpi;
659 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700661 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662
Andy McFadden91b2ca82014-06-13 14:04:23 -0700663 // This is how far in advance a buffer must be queued for
664 // presentation at a given time. If you want a buffer to appear
665 // on the screen at time N, you must submit the buffer before
666 // (N - presentationDeadline).
667 //
668 // Normally it's one full refresh period (to give SF a chance to
669 // latch the buffer), but this can be reduced by configuring a
670 // DispSync offset. Any additional delays introduced by the hardware
671 // composer or panel must be accounted for here.
672 //
673 // We add an additional 1ms to allow for processing time and
674 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800675 info.presentationDeadline = hwConfig->getVsyncPeriod() -
676 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700677
678 // All non-virtual displays are currently considered secure.
679 info.secure = true;
680
Michael Wright28f24d02016-07-12 13:30:53 -0700681 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700682 }
683
Dan Stoza7f7da322014-05-02 15:26:25 -0700684 return NO_ERROR;
685}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700686
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800687status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700688 DisplayStatInfo* stats) {
689 if (stats == NULL) {
690 return BAD_VALUE;
691 }
692
693 // FIXME for now we always return stats for the primary display
694 memset(stats, 0, sizeof(*stats));
695 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
696 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
697 return NO_ERROR;
698}
699
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700700int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700701 sp<DisplayDevice> device(getDisplayDevice(display));
702 if (device != NULL) {
703 return device->getActiveConfig();
704 }
705 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700706}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700707
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700708void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
709 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
710 this);
711 int32_t type = hw->getDisplayType();
712 int currentMode = hw->getActiveConfig();
713
714 if (mode == currentMode) {
715 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
716 return;
717 }
718
719 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
720 ALOGW("Trying to set config for virtual display");
721 return;
722 }
723
724 hw->setActiveConfig(mode);
725 getHwComposer().setActiveConfig(type, mode);
726}
727
728status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
729 class MessageSetActiveConfig: public MessageBase {
730 SurfaceFlinger& mFlinger;
731 sp<IBinder> mDisplay;
732 int mMode;
733 public:
734 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
735 int mode) :
736 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
737 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700738 Vector<DisplayInfo> configs;
739 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700740 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700741 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700742 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700743 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700744 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700745 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
746 if (hw == NULL) {
747 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700748 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700749 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
750 ALOGW("Attempt to set active config = %d for virtual display",
751 mMode);
752 } else {
753 mFlinger.setActiveConfigInternal(hw, mMode);
754 }
755 return true;
756 }
757 };
758 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
759 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700760 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700761}
Michael Wright28f24d02016-07-12 13:30:53 -0700762status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
763 Vector<android_color_mode_t>* outColorModes) {
764 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
765 return BAD_VALUE;
766 }
767
768 if (!display.get()) {
769 return NAME_NOT_FOUND;
770 }
771
772 int32_t type = NAME_NOT_FOUND;
773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
774 if (display == mBuiltinDisplays[i]) {
775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
782 }
783
784 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
785 outColorModes->clear();
786 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
787
788 return NO_ERROR;
789}
790
791android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
792 sp<DisplayDevice> device(getDisplayDevice(display));
793 if (device != nullptr) {
794 return device->getActiveColorMode();
795 }
796 return static_cast<android_color_mode_t>(BAD_VALUE);
797}
798
799void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
800 android_color_mode_t mode) {
801 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
802 this);
803 int32_t type = hw->getDisplayType();
804 android_color_mode_t currentMode = hw->getActiveColorMode();
805
806 if (mode == currentMode) {
807 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
808 return;
809 }
810
811 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
812 ALOGW("Trying to set config for virtual display");
813 return;
814 }
815
816 hw->setActiveColorMode(mode);
817 getHwComposer().setActiveColorMode(type, mode);
818}
819
820
821status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
822 android_color_mode_t colorMode) {
823 class MessageSetActiveColorMode: public MessageBase {
824 SurfaceFlinger& mFlinger;
825 sp<IBinder> mDisplay;
826 android_color_mode_t mMode;
827 public:
828 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
829 android_color_mode_t mode) :
830 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
831 virtual bool handler() {
832 Vector<android_color_mode_t> modes;
833 mFlinger.getDisplayColorModes(mDisplay, &modes);
834 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
835 if (mMode < 0 || !exists) {
836 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
837 mDisplay.get());
838 return true;
839 }
840 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
841 if (hw == nullptr) {
842 ALOGE("Attempt to set active color mode = %d for null display %p",
843 mMode, mDisplay.get());
844 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
845 ALOGW("Attempt to set active color mode= %d for virtual display",
846 mMode);
847 } else {
848 mFlinger.setActiveColorModeInternal(hw, mMode);
849 }
850 return true;
851 }
852 };
853 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
854 postMessageSync(msg);
855 return NO_ERROR;
856}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700857
Svetoslavd85084b2014-03-20 10:28:31 -0700858status_t SurfaceFlinger::clearAnimationFrameStats() {
859 Mutex::Autolock _l(mStateLock);
860 mAnimFrameTracker.clearStats();
861 return NO_ERROR;
862}
863
864status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
865 Mutex::Autolock _l(mStateLock);
866 mAnimFrameTracker.getStats(outStats);
867 return NO_ERROR;
868}
869
Dan Stozac4f471e2016-03-24 09:31:08 -0700870status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
871 HdrCapabilities* outCapabilities) const {
872 Mutex::Autolock _l(mStateLock);
873
874 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
875 if (displayDevice == nullptr) {
876 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
877 return BAD_VALUE;
878 }
879
880 std::unique_ptr<HdrCapabilities> capabilities =
881 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
882 if (capabilities) {
883 std::swap(*outCapabilities, *capabilities);
884 } else {
885 return BAD_VALUE;
886 }
887
888 return NO_ERROR;
889}
890
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700891status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
892 if (enable == mInjectVSyncs) {
893 return NO_ERROR;
894 }
895
896 if (enable) {
897 mInjectVSyncs = enable;
898 ALOGV("VSync Injections enabled");
899 if (mVSyncInjector.get() == nullptr) {
900 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700901 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700902 }
903 mEventQueue.setEventThread(mInjectorEventThread);
904 } else {
905 mInjectVSyncs = enable;
906 ALOGV("VSync Injections disabled");
907 mEventQueue.setEventThread(mSFEventThread);
908 mVSyncInjector.clear();
909 }
910 return NO_ERROR;
911}
912
913status_t SurfaceFlinger::injectVSync(nsecs_t when) {
914 if (!mInjectVSyncs) {
915 ALOGE("VSync Injections not enabled");
916 return BAD_VALUE;
917 }
918 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
919 ALOGV("Injecting VSync inside SurfaceFlinger");
920 mVSyncInjector->onInjectSyncEvent(when);
921 }
922 return NO_ERROR;
923}
924
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800925// ----------------------------------------------------------------------------
926
927sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800928 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700929}
930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800931// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800932
933void SurfaceFlinger::waitForEvent() {
934 mEventQueue.waitMessage();
935}
936
937void SurfaceFlinger::signalTransaction() {
938 mEventQueue.invalidate();
939}
940
941void SurfaceFlinger::signalLayerUpdate() {
942 mEventQueue.invalidate();
943}
944
945void SurfaceFlinger::signalRefresh() {
946 mEventQueue.refresh();
947}
948
949status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800950 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800951 return mEventQueue.postMessage(msg, reltime);
952}
953
954status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800955 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800956 status_t res = mEventQueue.postMessage(msg, reltime);
957 if (res == NO_ERROR) {
958 msg->wait();
959 }
960 return res;
961}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800962
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700963void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700964 do {
965 waitForEvent();
966 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800967}
968
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700969void SurfaceFlinger::enableHardwareVsync() {
970 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700971 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700972 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700973 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
974 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700975 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700976 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700977}
978
Jesse Hall948fe0c2013-10-14 12:56:09 -0700979void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700980 Mutex::Autolock _l(mHWVsyncLock);
981
Jesse Hall948fe0c2013-10-14 12:56:09 -0700982 if (makeAvailable) {
983 mHWVsyncAvailable = true;
984 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700985 // Hardware vsync is not currently available, so abort the resync
986 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700987 return;
988 }
989
Dan Stoza9e56aa02015-11-02 13:00:03 -0800990 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
991 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700992
993 mPrimaryDispSync.reset();
994 mPrimaryDispSync.setPeriod(period);
995
996 if (!mPrimaryHWVsyncEnabled) {
997 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700998 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
999 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001000 mPrimaryHWVsyncEnabled = true;
1001 }
1002}
1003
Jesse Hall948fe0c2013-10-14 12:56:09 -07001004void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001005 Mutex::Autolock _l(mHWVsyncLock);
1006 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001007 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1008 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001009 mPrimaryDispSync.endResync();
1010 mPrimaryHWVsyncEnabled = false;
1011 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001012 if (makeUnavailable) {
1013 mHWVsyncAvailable = false;
1014 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001015}
1016
Tim Murray4a4e4a22016-04-19 16:29:23 +00001017void SurfaceFlinger::resyncWithRateLimit() {
1018 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1019 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001020 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001021 }
1022}
1023
Dan Stoza9e56aa02015-11-02 13:00:03 -08001024void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001025 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001026
Jamie Gennisd1700752013-10-14 12:22:52 -07001027 { // Scope for the lock
1028 Mutex::Autolock _l(mHWVsyncLock);
1029 if (type == 0 && mPrimaryHWVsyncEnabled) {
1030 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001031 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001032 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001033
1034 if (needsHwVsync) {
1035 enableHardwareVsync();
1036 } else {
1037 disableHardwareVsync(false);
1038 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001039}
1040
Dan Stoza9e56aa02015-11-02 13:00:03 -08001041void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1042 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1043 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1044 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001045
Dan Stoza9e56aa02015-11-02 13:00:03 -08001046 // All non-virtual displays are currently considered secure.
1047 bool isSecure = true;
1048
1049 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1050 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1051 wp<IBinder> token = mBuiltinDisplays[type];
1052
1053 sp<IGraphicBufferProducer> producer;
1054 sp<IGraphicBufferConsumer> consumer;
1055 BufferQueue::createBufferQueue(&producer, &consumer,
1056 new GraphicBufferAlloc());
1057
1058 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1059 DisplayDevice::DISPLAY_PRIMARY, consumer);
1060 sp<DisplayDevice> hw = new DisplayDevice(this,
1061 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1062 producer, mRenderEngine->getEGLConfig());
1063 mDisplays.add(token, hw);
1064 } else {
1065 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001066 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001067 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001068 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001069 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001070 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1071 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001072 }
1073 setTransactionFlags(eDisplayTransactionNeeded);
1074
Andy McFadden9e9689c2012-10-10 18:17:51 -07001075 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001076 }
Mathias Agopian86303202012-07-24 22:46:10 -07001077}
1078
Dan Stoza9e56aa02015-11-02 13:00:03 -08001079void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001081 getHwComposer().setVsyncEnabled(disp,
1082 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001083}
1084
Mathias Agopian4fec8732012-06-29 14:12:52 -07001085void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001086 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001087 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001088 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001089 bool frameMissed = !mHadClientComposition &&
1090 mPreviousPresentFence != Fence::NO_FENCE &&
1091 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1092 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001093 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001094 signalLayerUpdate();
1095 break;
1096 }
1097
Dan Stoza6b9454d2014-11-07 16:00:59 -08001098 bool refreshNeeded = handleMessageTransaction();
1099 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001100 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001101 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001102 // Signal a refresh if a transaction modified the window state,
1103 // a new buffer was latched, or if HWC has requested a full
1104 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001105 signalRefresh();
1106 }
1107 break;
1108 }
1109 case MessageQueue::REFRESH: {
1110 handleMessageRefresh();
1111 break;
1112 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001113 }
1114}
1115
Dan Stoza6b9454d2014-11-07 16:00:59 -08001116bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001117 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001118 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001119 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001120 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001121 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001122 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001123}
1124
Dan Stoza6b9454d2014-11-07 16:00:59 -08001125bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001126 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001127 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001128}
1129
1130void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001131 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001132
Pablo Ceballos40845df2016-01-25 17:41:15 -08001133 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001134
Dan Stoza05dacfb2016-07-01 13:33:38 -07001135 preComposition();
1136 rebuildLayerStacks();
1137 setUpHWComposer();
1138 doDebugFlashRegions();
1139 doComposition();
1140 postComposition(refreshStartTime);
1141
1142 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001143
1144 mHadClientComposition = false;
1145 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1146 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1147 mHadClientComposition = mHadClientComposition ||
1148 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1149 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001150
Dan Stoza9e56aa02015-11-02 13:00:03 -08001151 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001152}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001153
Mathias Agopiancd60f992012-08-16 16:28:27 -07001154void SurfaceFlinger::doDebugFlashRegions()
1155{
1156 // is debugging enabled
1157 if (CC_LIKELY(!mDebugRegion))
1158 return;
1159
1160 const bool repaintEverything = mRepaintEverything;
1161 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1162 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001163 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001164 // transform the dirty region into this screen's coordinate space
1165 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1166 if (!dirtyRegion.isEmpty()) {
1167 // redraw the whole screen
1168 doComposeSurfaces(hw, Region(hw->bounds()));
1169
1170 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001171 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001172 RenderEngine& engine(getRenderEngine());
1173 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1174
Mathias Agopianda27af92012-09-13 18:17:13 -07001175 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001176 }
1177 }
1178 }
1179
1180 postFramebuffer();
1181
1182 if (mDebugRegion > 1) {
1183 usleep(mDebugRegion * 1000);
1184 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001185
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001187 auto& displayDevice = mDisplays[displayId];
1188 if (!displayDevice->isDisplayOn()) {
1189 continue;
1190 }
1191
1192 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1194 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001195 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001196}
1197
1198void SurfaceFlinger::preComposition()
1199{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 ATRACE_CALL();
1201 ALOGV("preComposition");
1202
Mathias Agopiancd60f992012-08-16 16:28:27 -07001203 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001204 const LayerVector& layers(mDrawingState.layersSortedByZ);
1205 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001206 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001207 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001208 needExtraInvalidate = true;
1209 }
1210 }
1211 if (needExtraInvalidate) {
1212 signalLayerUpdate();
1213 }
1214}
1215
Pablo Ceballos40845df2016-01-25 17:41:15 -08001216void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001217{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001218 ATRACE_CALL();
1219 ALOGV("postComposition");
1220
Brian Anderson3546a3f2016-07-14 11:51:14 -07001221 // Release any buffers which were replaced this frame
1222 for (auto& layer : mLayersWithQueuedFrames) {
1223 layer->releasePendingBuffer();
1224 }
1225
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001226 const LayerVector& layers(mDrawingState.layersSortedByZ);
1227 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001228 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001229 bool frameLatched = layers[i]->onPostComposition();
1230 if (frameLatched) {
1231 recordBufferingStats(layers[i]->getName().string(),
1232 layers[i]->getOccupancyHistory(false));
1233 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001234 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001235
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
1238 if (presentFence->isValid()) {
1239 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1240 enableHardwareVsync();
1241 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001242 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 }
1244 }
1245
Dan Stozab90cf072015-03-05 11:05:59 -08001246 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001247 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001248 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 enableHardwareVsync();
1250 }
1251 }
1252
Brian Anderson069b3652016-07-22 10:32:47 -07001253 sp<Fence> fenceTrackerPresentFence;
1254 sp<Fence> fenceTrackerRetireFence;
1255 if (mHwc->retireFenceRepresentsStartOfScanout()) {
1256 fenceTrackerPresentFence = presentFence;
1257 fenceTrackerRetireFence = Fence::NO_FENCE;
1258 } else {
1259 fenceTrackerPresentFence = Fence::NO_FENCE;
1260 fenceTrackerRetireFence = presentFence;
1261 }
1262 mFenceTracker.addFrame(refreshStartTime,
1263 fenceTrackerPresentFence, fenceTrackerRetireFence,
Pablo Ceballos40845df2016-01-25 17:41:15 -08001264 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1265
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001266 if (mAnimCompositionPending) {
1267 mAnimCompositionPending = false;
1268
Jesse Halla9a1b002013-02-27 16:39:25 -08001269 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001270 mAnimFrameTracker.setActualPresentFence(presentFence);
1271 } else {
1272 // The HWC doesn't support present fences, so use the refresh
1273 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 nsecs_t presentTime =
1275 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001276 mAnimFrameTracker.setActualPresentTime(presentTime);
1277 }
1278 mAnimFrameTracker.advanceFrame();
1279 }
Dan Stozab90cf072015-03-05 11:05:59 -08001280
1281 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1282 return;
1283 }
1284
1285 nsecs_t currentTime = systemTime();
1286 if (mHasPoweredOff) {
1287 mHasPoweredOff = false;
1288 } else {
1289 nsecs_t period = mPrimaryDispSync.getPeriod();
1290 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1291 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1292 if (numPeriods < NUM_BUCKETS - 1) {
1293 mFrameBuckets[numPeriods] += elapsedTime;
1294 } else {
1295 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1296 }
1297 mTotalTime += elapsedTime;
1298 }
1299 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001300}
1301
1302void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 ATRACE_CALL();
1304 ALOGV("rebuildLayerStacks");
1305
Mathias Agopiancd60f992012-08-16 16:28:27 -07001306 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001307 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001308 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001309 mVisibleRegionsDirty = false;
1310 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001311
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001312 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001313 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001314 Region opaqueRegion;
1315 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316 Vector<sp<Layer>> layersSortedByZ;
1317 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1318 const Transform& tr(displayDevice->getTransform());
1319 const Rect bounds(displayDevice->getBounds());
1320 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001321 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001322 displayDevice->getLayerStack(), dirtyRegion,
1323 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001324
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001325 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001326 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001327 const sp<Layer>& layer(layers[i]);
1328 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001329 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001330 Region drawRegion(tr.transform(
1331 layer->visibleNonTransparentRegion));
1332 drawRegion.andSelf(bounds);
1333 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001334 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001335 } else {
1336 // Clear out the HWC layer if this layer was
1337 // previously visible, but no longer is
1338 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1339 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001340 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001341 }
1342 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001343 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1345 displayDevice->undefinedRegion.set(bounds);
1346 displayDevice->undefinedRegion.subtractSelf(
1347 tr.transform(opaqueRegion));
1348 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001349 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001350 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001351}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001352
Mathias Agopiancd60f992012-08-16 16:28:27 -07001353void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001354 ATRACE_CALL();
1355 ALOGV("setUpHWComposer");
1356
Jesse Hall028dc8f2013-08-20 16:35:32 -07001357 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001358 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1359 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1360 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1361
1362 // If nothing has changed (!dirty), don't recompose.
1363 // If something changed, but we don't currently have any visible layers,
1364 // and didn't when we last did a composition, then skip it this time.
1365 // The second rule does two things:
1366 // - When all layers are removed from a display, we'll emit one black
1367 // frame, then nothing more until we get new layers.
1368 // - When a display is created with a private layer stack, we won't
1369 // emit any black frames until a layer is added to the layer stack.
1370 bool mustRecompose = dirty && !(empty && wasEmpty);
1371
1372 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1373 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1374 mustRecompose ? "doing" : "skipping",
1375 dirty ? "+" : "-",
1376 empty ? "+" : "-",
1377 wasEmpty ? "+" : "-");
1378
Dan Stoza71433162014-02-04 16:22:36 -08001379 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001380
1381 if (mustRecompose) {
1382 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1383 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001384 }
1385
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 // build the h/w work list
1387 if (CC_UNLIKELY(mGeometryInvalid)) {
1388 mGeometryInvalid = false;
1389 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1390 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1391 const auto hwcId = displayDevice->getHwcDisplayId();
1392 if (hwcId >= 0) {
1393 const Vector<sp<Layer>>& currentLayers(
1394 displayDevice->getVisibleLayersSortedByZ());
1395 bool foundLayerWithoutHwc = false;
1396 for (auto& layer : currentLayers) {
1397 if (!layer->hasHwcLayer(hwcId)) {
1398 auto hwcLayer = mHwc->createLayer(hwcId);
1399 if (hwcLayer) {
1400 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1401 } else {
1402 layer->forceClientComposition(hwcId);
1403 foundLayerWithoutHwc = true;
1404 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001405 }
1406 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001407
Dan Stoza9e56aa02015-11-02 13:00:03 -08001408 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001409 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001410 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001411 }
1412 }
1413 }
1414 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001415 }
Riley Andrews03414a12014-07-01 14:22:59 -07001416
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001417
1418 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1419
Dan Stoza9e56aa02015-11-02 13:00:03 -08001420 // Set the per-frame data
1421 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1422 auto& displayDevice = mDisplays[displayId];
1423 const auto hwcId = displayDevice->getHwcDisplayId();
1424 if (hwcId < 0) {
1425 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001426 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001427 if (colorMatrix != mPreviousColorMatrix) {
1428 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1429 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1430 "display %zd: %d", displayId, result);
1431 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001432 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1433 layer->setPerFrameData(displayDevice);
1434 }
1435 }
1436
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001437 mPreviousColorMatrix = colorMatrix;
1438
Dan Stoza9e56aa02015-11-02 13:00:03 -08001439 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001440 auto& displayDevice = mDisplays[displayId];
1441 if (!displayDevice->isDisplayOn()) {
1442 continue;
1443 }
1444
1445 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001446 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1447 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001448 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001450
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451void SurfaceFlinger::doComposition() {
1452 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 ALOGV("doComposition");
1454
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001455 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001456 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001457 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001458 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001459 // transform the dirty region into this screen's coordinate space
1460 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001461
1462 // repaint the framebuffer (if needed)
1463 doDisplayComposition(hw, dirtyRegion);
1464
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465 hw->dirtyRegion.clear();
1466 hw->flip(hw->swapRegion);
1467 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001468 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001470 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471}
1472
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001473void SurfaceFlinger::postFramebuffer()
1474{
Mathias Agopian841cde52012-03-01 15:44:37 -08001475 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001476 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001477
Mathias Agopiana44b0412011-10-16 18:46:35 -07001478 const nsecs_t now = systemTime();
1479 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001480
Dan Stoza9e56aa02015-11-02 13:00:03 -08001481 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1482 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001483 if (!displayDevice->isDisplayOn()) {
1484 continue;
1485 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001486 const auto hwcId = displayDevice->getHwcDisplayId();
1487 if (hwcId >= 0) {
1488 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001489 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001490 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001491 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1493 sp<Fence> releaseFence = Fence::NO_FENCE;
1494 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1495 releaseFence = displayDevice->getClientTargetAcquireFence();
1496 } else {
1497 auto hwcLayer = layer->getHwcLayer(hwcId);
1498 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001499 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 layer->onLayerDisplayed(releaseFence);
1501 }
1502 if (hwcId >= 0) {
1503 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001504 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001505 }
1506
Mathias Agopiana44b0412011-10-16 18:46:35 -07001507 mLastSwapBufferTime = systemTime() - now;
1508 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001509
1510 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1511 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1512 logFrameStats();
1513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001514}
1515
Mathias Agopian87baae12012-07-31 12:38:26 -07001516void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001517{
Mathias Agopian841cde52012-03-01 15:44:37 -08001518 ATRACE_CALL();
1519
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001520 // here we keep a copy of the drawing state (that is the state that's
1521 // going to be overwritten by handleTransactionLocked()) outside of
1522 // mStateLock so that the side-effects of the State assignment
1523 // don't happen with mStateLock held (which can cause deadlocks).
1524 State drawingState(mDrawingState);
1525
Mathias Agopianca4d3602011-05-19 15:38:14 -07001526 Mutex::Autolock _l(mStateLock);
1527 const nsecs_t now = systemTime();
1528 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001529
Mathias Agopianca4d3602011-05-19 15:38:14 -07001530 // Here we're guaranteed that some transaction flags are set
1531 // so we can call handleTransactionLocked() unconditionally.
1532 // We call getTransactionFlags(), which will also clear the flags,
1533 // with mStateLock held to guarantee that mCurrentState won't change
1534 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001535
Mathias Agopiane57f2922012-08-09 16:29:12 -07001536 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001537 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001538
Mathias Agopianca4d3602011-05-19 15:38:14 -07001539 mLastTransactionTime = systemTime() - now;
1540 mDebugInTransaction = 0;
1541 invalidateHwcGeometry();
1542 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001543}
1544
Mathias Agopian87baae12012-07-31 12:38:26 -07001545void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001546{
1547 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548 const size_t count = currentLayers.size();
1549
Dan Stoza7dde5992015-05-22 09:51:44 -07001550 // Notify all layers of available frames
1551 for (size_t i = 0; i < count; ++i) {
1552 currentLayers[i]->notifyAvailableFrames();
1553 }
1554
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001555 /*
1556 * Traversal of the children
1557 * (perform the transaction for each of them if needed)
1558 */
1559
Mathias Agopian3559b072012-08-15 13:46:03 -07001560 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001561 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001562 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001563 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1564 if (!trFlags) continue;
1565
1566 const uint32_t flags = layer->doTransaction(0);
1567 if (flags & Layer::eVisibleRegion)
1568 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001569 }
1570 }
1571
1572 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001573 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001574 */
1575
Mathias Agopiane57f2922012-08-09 16:29:12 -07001576 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001577 // here we take advantage of Vector's copy-on-write semantics to
1578 // improve performance by skipping the transaction entirely when
1579 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001580 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1581 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001582 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001584 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001585 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001586
1587 // find the displays that were removed
1588 // (ie: in drawing state but not in current state)
1589 // also handle displays that changed
1590 // (ie: displays that are in both lists)
1591 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001592 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1593 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001594 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001595 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001596 // Call makeCurrent() on the primary display so we can
1597 // be sure that nothing associated with this display
1598 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001599 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001600 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001601 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1602 if (hw != NULL)
1603 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001604 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001605 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001606 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001607 } else {
1608 ALOGW("trying to remove the main display");
1609 }
1610 } else {
1611 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001612 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001613 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001614 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1615 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001616 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001617 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001618 // recreating the DisplayDevice, so we just remove it
1619 // from the drawing state, so that it get re-added
1620 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001621 sp<DisplayDevice> hw(getDisplayDevice(display));
1622 if (hw != NULL)
1623 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001624 mDisplays.removeItem(display);
1625 mDrawingState.displays.removeItemsAt(i);
1626 dc--; i--;
1627 // at this point we must loop to the next item
1628 continue;
1629 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001630
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001631 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001632 if (disp != NULL) {
1633 if (state.layerStack != draw[i].layerStack) {
1634 disp->setLayerStack(state.layerStack);
1635 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001636 if ((state.orientation != draw[i].orientation)
1637 || (state.viewport != draw[i].viewport)
1638 || (state.frame != draw[i].frame))
1639 {
1640 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001641 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001642 }
Michael Lentine47e45402014-07-18 15:34:25 -07001643 if (state.width != draw[i].width || state.height != draw[i].height) {
1644 disp->setDisplaySize(state.width, state.height);
1645 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001646 }
1647 }
1648 }
1649
1650 // find displays that were added
1651 // (ie: in current state but not in drawing state)
1652 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001653 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001654 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001655
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001656 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001657 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001658 sp<IGraphicBufferProducer> bqProducer;
1659 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001660 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1661 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001662
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001664 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001665 // Virtual displays without a surface are dormant:
1666 // they have external state (layer stack, projection,
1667 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001668 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001669
Dan Stoza8cf150a2016-08-02 10:27:31 -07001670 if (mUseHwcVirtualDisplays) {
1671 int width = 0;
1672 int status = state.surface->query(
1673 NATIVE_WINDOW_WIDTH, &width);
1674 ALOGE_IF(status != NO_ERROR,
1675 "Unable to query width (%d)", status);
1676 int height = 0;
1677 status = state.surface->query(
1678 NATIVE_WINDOW_HEIGHT, &height);
1679 ALOGE_IF(status != NO_ERROR,
1680 "Unable to query height (%d)", status);
1681 int intFormat = 0;
1682 status = state.surface->query(
1683 NATIVE_WINDOW_FORMAT, &intFormat);
1684 ALOGE_IF(status != NO_ERROR,
1685 "Unable to query format (%d)", status);
1686 auto format = static_cast<android_pixel_format_t>(
1687 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001688
Dan Stoza8cf150a2016-08-02 10:27:31 -07001689 mHwc->allocateVirtualDisplay(width, height, &format,
1690 &hwcId);
1691 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692
Dan Stoza5cf424b2016-05-20 14:02:39 -07001693 // TODO: Plumb requested format back up to consumer
1694
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 sp<VirtualDisplaySurface> vds =
1696 new VirtualDisplaySurface(*mHwc,
1697 hwcId, state.surface, bqProducer,
1698 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001699
1700 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001701 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001702 }
1703 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001704 ALOGE_IF(state.surface!=NULL,
1705 "adding a supported display, but rendering "
1706 "surface is provided (%p), ignoring it",
1707 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1709 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1710 dispSurface = new FramebufferSurface(*mHwc,
1711 DisplayDevice::DISPLAY_EXTERNAL,
1712 bqConsumer);
1713 producer = bqProducer;
1714 } else {
1715 ALOGE("Attempted to add non-external non-virtual"
1716 " display");
1717 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001718 }
1719
1720 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001721 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001722 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 state.type, hwcId, state.isSecure, display,
1724 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001725 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001726 hw->setLayerStack(state.layerStack);
1727 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001728 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001729 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001730 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001731 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001732 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001733 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001734 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001735 }
1736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001737 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001739
Mathias Agopian84300952012-11-21 16:02:13 -08001740 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1741 // The transform hint might have changed for some layers
1742 // (either because a display has changed, or because a layer
1743 // as changed).
1744 //
1745 // Walk through all the layers in currentLayers,
1746 // and update their transform hint.
1747 //
1748 // If a layer is visible only on a single display, then that
1749 // display is used to calculate the hint, otherwise we use the
1750 // default display.
1751 //
1752 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1753 // the hint is set before we acquire a buffer from the surface texture.
1754 //
1755 // NOTE: layer transactions have taken place already, so we use their
1756 // drawing state. However, SurfaceFlinger's own transaction has not
1757 // happened yet, so we must use the current state layer list
1758 // (soon to become the drawing state list).
1759 //
1760 sp<const DisplayDevice> disp;
1761 uint32_t currentlayerStack = 0;
1762 for (size_t i=0; i<count; i++) {
1763 // NOTE: we rely on the fact that layers are sorted by
1764 // layerStack first (so we don't have to traverse the list
1765 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001766 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001767 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001768 if (i==0 || currentlayerStack != layerStack) {
1769 currentlayerStack = layerStack;
1770 // figure out if this layerstack is mirrored
1771 // (more than one display) if so, pick the default display,
1772 // if not, pick the only display it's on.
1773 disp.clear();
1774 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1775 sp<const DisplayDevice> hw(mDisplays[dpy]);
1776 if (hw->getLayerStack() == currentlayerStack) {
1777 if (disp == NULL) {
1778 disp = hw;
1779 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001780 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001781 break;
1782 }
1783 }
1784 }
1785 }
Chet Haase91d25932013-04-11 15:24:55 -07001786 if (disp == NULL) {
1787 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1788 // redraw after transform hint changes. See bug 8508397.
1789
1790 // could be null when this layer is using a layerStack
1791 // that is not visible on any display. Also can occur at
1792 // screen off/on times.
1793 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001794 }
Chet Haase91d25932013-04-11 15:24:55 -07001795 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001796 }
1797 }
1798
1799
Mathias Agopian3559b072012-08-15 13:46:03 -07001800 /*
1801 * Perform our own transaction if needed
1802 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001803
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001804 const LayerVector& layers(mDrawingState.layersSortedByZ);
1805 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001806 // layers have been added
1807 mVisibleRegionsDirty = true;
1808 }
1809
1810 // some layers might have been removed, so
1811 // we need to update the regions they're exposing.
1812 if (mLayersRemoved) {
1813 mLayersRemoved = false;
1814 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001815 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001816 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001817 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001818 if (currentLayers.indexOf(layer) < 0) {
1819 // this layer is not visible anymore
1820 // TODO: we could traverse the tree from front to back and
1821 // compute the actual visible region
1822 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001823 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001824 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001825 Region(Rect(s.active.w, s.active.h)));
1826 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001829 }
1830
1831 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001832
1833 updateCursorAsync();
1834}
1835
1836void SurfaceFlinger::updateCursorAsync()
1837{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1839 auto& displayDevice = mDisplays[displayId];
1840 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001841 continue;
1842 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843
1844 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1845 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001846 }
1847 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001848}
1849
1850void SurfaceFlinger::commitTransaction()
1851{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001852 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001853 // Notify removed layers now that they can't be drawn from
1854 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001855 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1856 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001857 mLayersPendingRemoval[i]->onRemoved();
1858 }
1859 mLayersPendingRemoval.clear();
1860 }
1861
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001862 // If this transaction is part of a window animation then the next frame
1863 // we composite should be considered an animation as well.
1864 mAnimCompositionPending = mAnimTransactionPending;
1865
Mathias Agopian4fec8732012-06-29 14:12:52 -07001866 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001867 mTransactionPending = false;
1868 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001869 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001870}
1871
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001872void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001873 const LayerVector& currentLayers, uint32_t layerStack,
1874 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875{
Mathias Agopian841cde52012-03-01 15:44:37 -08001876 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001878
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001879 Region aboveOpaqueLayers;
1880 Region aboveCoveredLayers;
1881 Region dirty;
1882
Mathias Agopian87baae12012-07-31 12:38:26 -07001883 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001884
1885 size_t i = currentLayers.size();
1886 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001887 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001888
1889 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001890 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891
Jesse Hall01e29052013-02-19 16:13:35 -08001892 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001893 if (s.layerStack != layerStack)
1894 continue;
1895
Mathias Agopianab028732010-03-16 16:41:46 -07001896 /*
1897 * opaqueRegion: area of a surface that is fully opaque.
1898 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001900
1901 /*
1902 * visibleRegion: area of a surface that is visible on screen
1903 * and not fully transparent. This is essentially the layer's
1904 * footprint minus the opaque regions above it.
1905 * Areas covered by a translucent surface are considered visible.
1906 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001907 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001908
1909 /*
1910 * coveredRegion: area of a surface that is covered by all
1911 * visible regions above it (which includes the translucent areas).
1912 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001913 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001914
Jesse Halla8026d22012-09-25 13:25:04 -07001915 /*
1916 * transparentRegion: area of a surface that is hinted to be completely
1917 * transparent. This is only used to tell when the layer has no visible
1918 * non-transparent regions and can be removed from the layer list. It
1919 * does not affect the visibleRegion of this layer or any layers
1920 * beneath it. The hint may not be correct if apps don't respect the
1921 * SurfaceView restrictions (which, sadly, some don't).
1922 */
1923 Region transparentRegion;
1924
Mathias Agopianab028732010-03-16 16:41:46 -07001925
1926 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001927 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001928 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001929 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001931 if (!visibleRegion.isEmpty()) {
1932 // Remove the transparent area from the visible region
1933 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001934 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001935 if (tr.preserveRects()) {
1936 // transform the transparent region
1937 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001938 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001939 // transformation too complex, can't do the
1940 // transparent region optimization.
1941 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001942 }
Mathias Agopianab028732010-03-16 16:41:46 -07001943 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001944
Mathias Agopianab028732010-03-16 16:41:46 -07001945 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001946 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001948 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1949 // the opaque region is the layer's footprint
1950 opaqueRegion = visibleRegion;
1951 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001952 }
1953 }
1954
Mathias Agopianab028732010-03-16 16:41:46 -07001955 // Clip the covered region to the visible region
1956 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1957
1958 // Update aboveCoveredLayers for next (lower) layer
1959 aboveCoveredLayers.orSelf(visibleRegion);
1960
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001961 // subtract the opaque region covered by the layers above us
1962 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963
1964 // compute this layer's dirty region
1965 if (layer->contentDirty) {
1966 // we need to invalidate the whole region
1967 dirty = visibleRegion;
1968 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001969 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970 layer->contentDirty = false;
1971 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001972 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001973 * the exposed region consists of two components:
1974 * 1) what's VISIBLE now and was COVERED before
1975 * 2) what's EXPOSED now less what was EXPOSED before
1976 *
1977 * note that (1) is conservative, we start with the whole
1978 * visible region but only keep what used to be covered by
1979 * something -- which mean it may have been exposed.
1980 *
1981 * (2) handles areas that were not covered by anything but got
1982 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001983 */
Mathias Agopianab028732010-03-16 16:41:46 -07001984 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001985 const Region oldVisibleRegion = layer->visibleRegion;
1986 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001987 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1988 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989 }
1990 dirty.subtractSelf(aboveOpaqueLayers);
1991
1992 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001993 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994
Mathias Agopianab028732010-03-16 16:41:46 -07001995 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001996 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001997
Jesse Halla8026d22012-09-25 13:25:04 -07001998 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999 layer->setVisibleRegion(visibleRegion);
2000 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002001 layer->setVisibleNonTransparentRegion(
2002 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003 }
2004
Mathias Agopian87baae12012-07-31 12:38:26 -07002005 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006}
2007
Mathias Agopian87baae12012-07-31 12:38:26 -07002008void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2009 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002010 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002011 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2012 if (hw->getLayerStack() == layerStack) {
2013 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002014 }
2015 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002016}
2017
Dan Stoza6b9454d2014-11-07 16:00:59 -08002018bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002019{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 ALOGV("handlePageFlip");
2021
Mathias Agopian4fec8732012-06-29 14:12:52 -07002022 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002025 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002026 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002027
2028 // Store the set of layers that need updates. This set must not change as
2029 // buffers are being latched, as this could result in a deadlock.
2030 // Example: Two producers share the same command stream and:
2031 // 1.) Layer 0 is latched
2032 // 2.) Layer 0 gets a new frame
2033 // 2.) Layer 1 gets a new frame
2034 // 3.) Layer 1 is latched.
2035 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2036 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002037 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002038 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002039 if (layer->hasQueuedFrame()) {
2040 frameQueued = true;
2041 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002043 } else {
2044 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002045 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002046 } else {
2047 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002048 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002049 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002051 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002052 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002053 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002054 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002055 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002056
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002057 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002058
2059 // If we will need to wake up at some time in the future to deal with a
2060 // queued frame that shouldn't be displayed during this vsync period, wake
2061 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002063 signalLayerUpdate();
2064 }
2065
2066 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068}
2069
Mathias Agopianad456f92011-01-13 17:53:01 -08002070void SurfaceFlinger::invalidateHwcGeometry()
2071{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002073}
2074
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002075
Mathias Agopiancd60f992012-08-16 16:28:27 -07002076void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002077 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078{
Dan Stoza71433162014-02-04 16:22:36 -08002079 // We only need to actually compose the display if:
2080 // 1) It is being handled by hardware composer, which may need this to
2081 // keep its virtual display state machine in sync, or
2082 // 2) There is work to be done (the dirty region isn't empty)
2083 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2084 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002086 return;
2087 }
2088
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 ALOGV("doDisplayComposition");
2090
Mathias Agopian87baae12012-07-31 12:38:26 -07002091 Region dirtyRegion(inDirtyRegion);
2092
Mathias Agopianb8a55602009-06-26 19:06:36 -07002093 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002094 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095
Mathias Agopian42977342012-08-05 00:40:46 -07002096 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002097 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002098 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2099 // takes a rectangle, we must make sure to update that whole
2100 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002101 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002102 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002103 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002104 // We need to redraw the rectangle that will be updated
2105 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002106 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002107 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002108 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002109 } else {
2110 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002111 dirtyRegion.set(hw->bounds());
2112 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 }
2114 }
2115
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002116 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002118 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002119 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002120
2121 // swap buffers (presentation)
2122 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123}
2124
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125bool SurfaceFlinger::doComposeSurfaces(
2126 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002127{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002129
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002131
2132 mat4 oldColorMatrix;
2133 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2134 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2135 if (applyColorMatrix) {
2136 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2137 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2138 }
2139
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2141 if (hasClientComposition) {
2142 ALOGV("hasClientComposition");
2143
2144 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002145 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002146 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002147 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2148 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2149 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2150 }
2151 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002152 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002153
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002154 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2156 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002157 // when using overlays, we assume a fully transparent framebuffer
2158 // NOTE: we could reduce how much we need to clear, for instance
2159 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002160 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002161 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002163 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002164 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002166
2167 // we remove the scissor part
2168 // we're left with the letterbox region
2169 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002171
2172 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002174
2175 // but limit it to the dirty region
2176 region.andSelf(dirty);
2177
Mathias Agopianb9494d52012-04-18 02:28:45 -07002178 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002179 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002180 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002182 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002183 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002184
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002186 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002187 // scissor on the main display. It should never be needed
2188 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 const Rect& bounds(displayDevice->getBounds());
2190 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002191 if (scissor != bounds) {
2192 // scissor doesn't match the screen's dimensions, so we
2193 // need to clear everything outside of it and enable
2194 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002195
Mathias Agopianf45c5102012-10-24 16:29:17 -07002196 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 const uint32_t height = displayDevice->getHeight();
2198 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002199 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002200 }
2201 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002202 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002203
Mathias Agopian85d751c2012-08-29 16:59:24 -07002204 /*
2205 * and then, render the layers targeted at the framebuffer
2206 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002207
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 ALOGV("Rendering client layers");
2209 const Transform& displayTransform = displayDevice->getTransform();
2210 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002211 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 bool firstLayer = true;
2213 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2214 const Region clip(dirty.intersect(
2215 displayTransform.transform(layer->visibleRegion)));
2216 ALOGV("Layer: %s", layer->getName().string());
2217 ALOGV(" Composition type: %s",
2218 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002219 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 switch (layer->getCompositionType(hwcId)) {
2221 case HWC2::Composition::Cursor:
2222 case HWC2::Composition::Device:
2223 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002224 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2226 layer->isOpaque(state) && (state.alpha == 1.0f)
2227 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002228 // never clear the very first layer since we're
2229 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002231 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002232 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002233 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 case HWC2::Composition::Client: {
2235 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002236 break;
2237 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002238 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002239 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002240 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 } else {
2242 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002243 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002245 }
2246 } else {
2247 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002248 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002249 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002250 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002251 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002252 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002253 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002254 }
2255 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002256
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002257 if (applyColorMatrix) {
2258 getRenderEngine().setupColorTransform(oldColorMatrix);
2259 }
2260
Mathias Agopianf45c5102012-10-24 16:29:17 -07002261 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002263 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002264}
2265
Mathias Agopian3f844832013-08-07 21:24:32 -07002266void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002267 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002268 RenderEngine& engine(getRenderEngine());
2269 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002270}
2271
Dan Stoza7d89d062015-04-30 13:29:25 -07002272status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002273 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002274 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002275 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002276{
Dan Stoza7d89d062015-04-30 13:29:25 -07002277 // add this layer to the current state list
2278 {
2279 Mutex::Autolock _l(mStateLock);
2280 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2281 return NO_MEMORY;
2282 }
2283 mCurrentState.layersSortedByZ.add(lbc);
2284 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2285 }
2286
Mathias Agopian96f08192010-06-02 23:28:45 -07002287 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002288 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002289
Dan Stoza7d89d062015-04-30 13:29:25 -07002290 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002291}
2292
Dan Stoza22851c32016-08-09 13:21:03 -07002293status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002295 sp<Layer> layer = weakLayer.promote();
2296 if (layer == nullptr) {
2297 // The layer has already been removed, carry on
2298 return NO_ERROR;
2299 }
2300
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002301 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2302 if (index >= 0) {
2303 mLayersPendingRemoval.push(layer);
2304 mLayersRemoved = true;
2305 setTransactionFlags(eTransactionNeeded);
2306 return NO_ERROR;
2307 }
2308 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309}
2310
Dan Stozac7014012014-02-14 15:03:43 -08002311uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002312 return android_atomic_release_load(&mTransactionFlags);
2313}
2314
Mathias Agopian3f844832013-08-07 21:24:32 -07002315uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2317}
2318
Mathias Agopian3f844832013-08-07 21:24:32 -07002319uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2321 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002322 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323 }
2324 return old;
2325}
2326
Mathias Agopian8b33f032012-07-24 20:43:54 -07002327void SurfaceFlinger::setTransactionState(
2328 const Vector<ComposerState>& state,
2329 const Vector<DisplayState>& displays,
2330 uint32_t flags)
2331{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002332 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002333 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002334 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002335
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002336 if (flags & eAnimation) {
2337 // For window updates that are part of an animation we must wait for
2338 // previous animation "frames" to be handled.
2339 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002340 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002341 if (CC_UNLIKELY(err != NO_ERROR)) {
2342 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002343 // caller after a few seconds.
2344 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2345 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002346 mAnimTransactionPending = false;
2347 break;
2348 }
2349 }
2350 }
2351
Mathias Agopiane57f2922012-08-09 16:29:12 -07002352 size_t count = displays.size();
2353 for (size_t i=0 ; i<count ; i++) {
2354 const DisplayState& s(displays[i]);
2355 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002356 }
2357
Mathias Agopiane57f2922012-08-09 16:29:12 -07002358 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002359 for (size_t i=0 ; i<count ; i++) {
2360 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002361 // Here we need to check that the interface we're given is indeed
2362 // one of our own. A malicious client could give us a NULL
2363 // IInterface, or one of its own or even one of our own but a
2364 // different type. All these situations would cause us to crash.
2365 //
2366 // NOTE: it would be better to use RTTI as we could directly check
2367 // that we have a Client*. however, RTTI is disabled in Android.
2368 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002369 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002370 if (binder != NULL) {
2371 String16 desc(binder->getInterfaceDescriptor());
2372 if (desc == ISurfaceComposerClient::descriptor) {
2373 sp<Client> client( static_cast<Client *>(s.client.get()) );
2374 transactionFlags |= setClientStateLocked(client, s.state);
2375 }
2376 }
2377 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002378 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002379
Robert Carr2a7dbb42016-05-24 11:41:28 -07002380 // If a synchronous transaction is explicitly requested without any changes,
2381 // force a transaction anyway. This can be used as a flush mechanism for
2382 // previous async transactions.
2383 if (transactionFlags == 0 && (flags & eSynchronous)) {
2384 transactionFlags = eTransactionNeeded;
2385 }
2386
Mathias Agopian386aa982011-11-07 21:58:03 -08002387 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002388 if (mInterceptor.isEnabled()) {
2389 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2390 }
Irvel468051e2016-06-13 16:44:44 -07002391
Mathias Agopian386aa982011-11-07 21:58:03 -08002392 // this triggers the transaction
2393 setTransactionFlags(transactionFlags);
2394
2395 // if this is a synchronous transaction, wait for it to take effect
2396 // before returning.
2397 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002398 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002399 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002400 if (flags & eAnimation) {
2401 mAnimTransactionPending = true;
2402 }
2403 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002404 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2405 if (CC_UNLIKELY(err != NO_ERROR)) {
2406 // just in case something goes wrong in SF, return to the
2407 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002408 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2409 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002410 break;
2411 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413 }
2414}
2415
Mathias Agopiane57f2922012-08-09 16:29:12 -07002416uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2417{
Jesse Hall9a143922012-10-04 16:29:19 -07002418 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2419 if (dpyIdx < 0)
2420 return 0;
2421
Mathias Agopiane57f2922012-08-09 16:29:12 -07002422 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002423 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002424 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002425 const uint32_t what = s.what;
2426 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002427 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002428 disp.surface = s.surface;
2429 flags |= eDisplayTransactionNeeded;
2430 }
2431 }
2432 if (what & DisplayState::eLayerStackChanged) {
2433 if (disp.layerStack != s.layerStack) {
2434 disp.layerStack = s.layerStack;
2435 flags |= eDisplayTransactionNeeded;
2436 }
2437 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002438 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002439 if (disp.orientation != s.orientation) {
2440 disp.orientation = s.orientation;
2441 flags |= eDisplayTransactionNeeded;
2442 }
2443 if (disp.frame != s.frame) {
2444 disp.frame = s.frame;
2445 flags |= eDisplayTransactionNeeded;
2446 }
2447 if (disp.viewport != s.viewport) {
2448 disp.viewport = s.viewport;
2449 flags |= eDisplayTransactionNeeded;
2450 }
2451 }
Michael Lentine47e45402014-07-18 15:34:25 -07002452 if (what & DisplayState::eDisplaySizeChanged) {
2453 if (disp.width != s.width) {
2454 disp.width = s.width;
2455 flags |= eDisplayTransactionNeeded;
2456 }
2457 if (disp.height != s.height) {
2458 disp.height = s.height;
2459 flags |= eDisplayTransactionNeeded;
2460 }
2461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002462 }
2463 return flags;
2464}
2465
2466uint32_t SurfaceFlinger::setClientStateLocked(
2467 const sp<Client>& client,
2468 const layer_state_t& s)
2469{
2470 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002471 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002472 if (layer != 0) {
2473 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002474 bool geometryAppliesWithResize =
2475 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002476 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002477 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002478 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002479 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002480 }
2481 if (what & layer_state_t::eLayerChanged) {
2482 // NOTE: index needs to be calculated before we update the state
2483 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002484 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002485 mCurrentState.layersSortedByZ.removeAt(idx);
2486 mCurrentState.layersSortedByZ.add(layer);
2487 // we need traversal (state changed)
2488 // AND transaction (list changed)
2489 flags |= eTransactionNeeded|eTraversalNeeded;
2490 }
2491 }
2492 if (what & layer_state_t::eSizeChanged) {
2493 if (layer->setSize(s.w, s.h)) {
2494 flags |= eTraversalNeeded;
2495 }
2496 }
2497 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 flags |= eTraversalNeeded;
2500 }
2501 if (what & layer_state_t::eMatrixChanged) {
2502 if (layer->setMatrix(s.matrix))
2503 flags |= eTraversalNeeded;
2504 }
2505 if (what & layer_state_t::eTransparentRegionChanged) {
2506 if (layer->setTransparentRegionHint(s.transparentRegion))
2507 flags |= eTraversalNeeded;
2508 }
Dan Stoza23116082015-06-18 14:58:39 -07002509 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002510 if (layer->setFlags(s.flags, s.mask))
2511 flags |= eTraversalNeeded;
2512 }
2513 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002514 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002515 flags |= eTraversalNeeded;
2516 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002517 if (what & layer_state_t::eFinalCropChanged) {
2518 if (layer->setFinalCrop(s.finalCrop))
2519 flags |= eTraversalNeeded;
2520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002521 if (what & layer_state_t::eLayerStackChanged) {
2522 // NOTE: index needs to be calculated before we update the state
2523 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002524 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002525 mCurrentState.layersSortedByZ.removeAt(idx);
2526 mCurrentState.layersSortedByZ.add(layer);
2527 // we need traversal (state changed)
2528 // AND transaction (list changed)
2529 flags |= eTransactionNeeded|eTraversalNeeded;
2530 }
2531 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002532 if (what & layer_state_t::eDeferTransaction) {
2533 layer->deferTransactionUntil(s.handle, s.frameNumber);
2534 // We don't trigger a traversal here because if no other state is
2535 // changed, we don't want this to cause any more work
2536 }
Robert Carrc3574f72016-03-24 12:19:32 -07002537 if (what & layer_state_t::eOverrideScalingModeChanged) {
2538 layer->setOverrideScalingMode(s.overrideScalingMode);
2539 // We don't trigger a traversal here because if no other state is
2540 // changed, we don't want this to cause any more work
2541 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002542 }
2543 return flags;
2544}
2545
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002546status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002547 const String8& name,
2548 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002549 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2550 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002552 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002553 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002554 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002555 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002556 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002557
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002558 status_t result = NO_ERROR;
2559
2560 sp<Layer> layer;
2561
Mathias Agopian3165cc22012-08-08 19:42:09 -07002562 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2563 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002564 result = createNormalLayer(client,
2565 name, w, h, flags, format,
2566 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002568 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002569 result = createDimLayer(client,
2570 name, w, h, flags,
2571 handle, gbp, &layer);
2572 break;
2573 default:
2574 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 break;
2576 }
2577
Dan Stoza7d89d062015-04-30 13:29:25 -07002578 if (result != NO_ERROR) {
2579 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002581
2582 result = addClientLayer(client, *handle, *gbp, layer);
2583 if (result != NO_ERROR) {
2584 return result;
2585 }
Irvelffc9efc2016-07-27 15:16:37 -07002586 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002587
2588 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002589 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002592status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2593 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595{
2596 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002597 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 case PIXEL_FORMAT_TRANSPARENT:
2599 case PIXEL_FORMAT_TRANSLUCENT:
2600 format = PIXEL_FORMAT_RGBA_8888;
2601 break;
2602 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002603 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 break;
2605 }
2606
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002607 *outLayer = new Layer(this, client, name, w, h, flags);
2608 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2609 if (err == NO_ERROR) {
2610 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002611 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002613
2614 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2615 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616}
2617
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002618status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2619 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2620 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002622 *outLayer = new LayerDim(this, client, name, w, h, flags);
2623 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002624 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002625 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002626}
2627
Mathias Agopianac9fa422013-02-11 16:40:36 -08002628status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629{
Mathias Agopian67106042013-03-14 19:18:13 -07002630 // called by the window manager when it wants to remove a Layer
2631 status_t err = NO_ERROR;
2632 sp<Layer> l(client->getLayerUser(handle));
2633 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002634 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002635 err = removeLayer(l);
2636 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2637 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002638 }
2639 return err;
2640}
2641
Mathias Agopian13127d82013-03-05 17:47:11 -08002642status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002643{
Mathias Agopian67106042013-03-14 19:18:13 -07002644 // called by ~LayerCleaner() when all references to the IBinder (handle)
2645 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002646 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647}
2648
Mathias Agopianb60314a2012-04-10 22:09:54 -07002649// ---------------------------------------------------------------------------
2650
Andy McFadden13a082e2012-08-24 10:16:42 -07002651void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002652 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002653 Vector<ComposerState> state;
2654 Vector<DisplayState> displays;
2655 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002656 d.what = DisplayState::eDisplayProjectionChanged |
2657 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002658 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002659 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002660 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002661 d.frame.makeInvalid();
2662 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002663 d.width = 0;
2664 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002665 displays.add(d);
2666 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002667 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002668
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2670 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002671 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002672}
2673
2674void SurfaceFlinger::initializeDisplays() {
2675 class MessageScreenInitialized : public MessageBase {
2676 SurfaceFlinger* flinger;
2677 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002678 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002679 virtual bool handler() {
2680 flinger->onInitializeDisplays();
2681 return true;
2682 }
2683 };
2684 sp<MessageBase> msg = new MessageScreenInitialized(this);
2685 postMessageAsync(msg); // we may be called from main thread, use async message
2686}
2687
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002688void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2689 int mode) {
2690 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2691 this);
2692 int32_t type = hw->getDisplayType();
2693 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002695 if (mode == currentMode) {
2696 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002697 return;
2698 }
2699
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002700 hw->setPowerMode(mode);
2701 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2702 ALOGW("Trying to set power mode for virtual display");
2703 return;
2704 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002705
Irvelffc9efc2016-07-27 15:16:37 -07002706 if (mInterceptor.isEnabled()) {
2707 Mutex::Autolock _l(mStateLock);
2708 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2709 if (idx < 0) {
2710 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2711 return;
2712 }
2713 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2714 }
2715
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002716 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002717 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002718 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002719 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2720 // FIXME: eventthread only knows about the main display right now
2721 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002722 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002725 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002726 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002727 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002728
2729 struct sched_param param = {0};
2730 param.sched_priority = 1;
2731 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2732 ALOGW("Couldn't set SCHED_FIFO on display on");
2733 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002734 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002735 // Turn off the display
2736 struct sched_param param = {0};
2737 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2738 ALOGW("Couldn't set SCHED_OTHER on display off");
2739 }
2740
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002741 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002742 disableHardwareVsync(true); // also cancels any in-progress resync
2743
Mathias Agopiancde87a32012-09-13 14:09:01 -07002744 // FIXME: eventthread only knows about the main display right now
2745 mEventThread->onScreenReleased();
2746 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002747
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002748 getHwComposer().setPowerMode(type, mode);
2749 mVisibleRegionsDirty = true;
2750 // from this point on, SF will stop drawing on this display
2751 } else {
2752 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002753 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002754}
2755
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002756void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2757 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002758 SurfaceFlinger& mFlinger;
2759 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002760 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002761 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002762 MessageSetPowerMode(SurfaceFlinger& flinger,
2763 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2764 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002765 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002766 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002767 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002768 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002769 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002770 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002771 ALOGW("Attempt to set power mode = %d for virtual display",
2772 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002773 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002774 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002775 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002776 return true;
2777 }
2778 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002779 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002780 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002781}
2782
2783// ---------------------------------------------------------------------------
2784
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2786{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002788
Mathias Agopianbd115332013-04-18 16:41:04 -07002789 IPCThreadState* ipc = IPCThreadState::self();
2790 const int pid = ipc->getCallingPid();
2791 const int uid = ipc->getCallingUid();
2792 if ((uid != AID_SHELL) &&
2793 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002794 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002795 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002797 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002798 // (this would indicate SF is stuck, but we want to be able to
2799 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002800 status_t err = mStateLock.timedLock(s2ns(1));
2801 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002802 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002803 result.appendFormat(
2804 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2805 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002806 }
2807
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002808 bool dumpAll = true;
2809 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002810 size_t numArgs = args.size();
2811 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002812 if ((index < numArgs) &&
2813 (args[index] == String16("--list"))) {
2814 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002815 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002816 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002817 }
2818
2819 if ((index < numArgs) &&
2820 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002821 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002822 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002823 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002824 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002825
2826 if ((index < numArgs) &&
2827 (args[index] == String16("--latency-clear"))) {
2828 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002829 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002830 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002831 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002832
2833 if ((index < numArgs) &&
2834 (args[index] == String16("--dispsync"))) {
2835 index++;
2836 mPrimaryDispSync.dump(result);
2837 dumpAll = false;
2838 }
Dan Stozab90cf072015-03-05 11:05:59 -08002839
2840 if ((index < numArgs) &&
2841 (args[index] == String16("--static-screen"))) {
2842 index++;
2843 dumpStaticScreenStats(result);
2844 dumpAll = false;
2845 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002846
2847 if ((index < numArgs) &&
2848 (args[index] == String16("--fences"))) {
2849 index++;
2850 mFenceTracker.dump(&result);
2851 dumpAll = false;
2852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002854
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002855 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002856 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002857 }
2858
Mathias Agopian9795c422009-08-26 16:36:26 -07002859 if (locked) {
2860 mStateLock.unlock();
2861 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 }
2863 write(fd, result.string(), result.size());
2864 return NO_ERROR;
2865}
2866
Dan Stozac7014012014-02-14 15:03:43 -08002867void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2868 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002869{
2870 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2871 const size_t count = currentLayers.size();
2872 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002873 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002874 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002875 }
2876}
2877
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002878void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002879 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002880{
2881 String8 name;
2882 if (index < args.size()) {
2883 name = String8(args[index]);
2884 index++;
2885 }
2886
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2888 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002889 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002890
2891 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002892 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002893 } else {
2894 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2895 const size_t count = currentLayers.size();
2896 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002897 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002898 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002899 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002900 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002901 }
2902 }
2903}
2904
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002905void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002906 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002907{
2908 String8 name;
2909 if (index < args.size()) {
2910 name = String8(args[index]);
2911 index++;
2912 }
2913
2914 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2915 const size_t count = currentLayers.size();
2916 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002917 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002918 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002919 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002920 }
2921 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002922
Svetoslavd85084b2014-03-20 10:28:31 -07002923 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002924}
2925
Jamie Gennis6547ff42013-07-16 20:12:42 -07002926// This should only be called from the main thread. Otherwise it would need
2927// the lock and should use mCurrentState rather than mDrawingState.
2928void SurfaceFlinger::logFrameStats() {
2929 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2930 const size_t count = drawingLayers.size();
2931 for (size_t i=0 ; i<count ; i++) {
2932 const sp<Layer>& layer(drawingLayers[i]);
2933 layer->logFrameStats();
2934 }
2935
2936 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2937}
2938
Andy McFadden4803b742012-09-24 19:07:20 -07002939/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2940{
2941 static const char* config =
2942 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002943#ifdef HAS_CONTEXT_PRIORITY
2944 " HAS_CONTEXT_PRIORITY"
2945#endif
2946#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2947 " NEVER_DEFAULT_TO_ASYNC_MODE"
2948#endif
2949#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2950 " TARGET_DISABLE_TRIPLE_BUFFERING"
2951#endif
2952 "]";
2953 result.append(config);
2954}
2955
Dan Stozab90cf072015-03-05 11:05:59 -08002956void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2957{
2958 result.appendFormat("Static screen stats:\n");
2959 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2960 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2961 float percent = 100.0f *
2962 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2963 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2964 b + 1, bucketTimeSec, percent);
2965 }
2966 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2967 float percent = 100.0f *
2968 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2969 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2970 NUM_BUCKETS - 1, bucketTimeSec, percent);
2971}
2972
Dan Stozae77c7662016-05-13 11:37:28 -07002973void SurfaceFlinger::recordBufferingStats(const char* layerName,
2974 std::vector<OccupancyTracker::Segment>&& history) {
2975 Mutex::Autolock lock(mBufferingStatsMutex);
2976 auto& stats = mBufferingStats[layerName];
2977 for (const auto& segment : history) {
2978 if (!segment.usedThirdBuffer) {
2979 stats.twoBufferTime += segment.totalTime;
2980 }
2981 if (segment.occupancyAverage < 1.0f) {
2982 stats.doubleBufferedTime += segment.totalTime;
2983 } else if (segment.occupancyAverage < 2.0f) {
2984 stats.tripleBufferedTime += segment.totalTime;
2985 }
2986 ++stats.numSegments;
2987 stats.totalTime += segment.totalTime;
2988 }
2989}
2990
2991void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2992 result.append("Buffering stats:\n");
2993 result.append(" [Layer name] <Active time> <Two buffer> "
2994 "<Double buffered> <Triple buffered>\n");
2995 Mutex::Autolock lock(mBufferingStatsMutex);
2996 typedef std::tuple<std::string, float, float, float> BufferTuple;
2997 std::map<float, BufferTuple, std::greater<float>> sorted;
2998 for (const auto& statsPair : mBufferingStats) {
2999 const char* name = statsPair.first.c_str();
3000 const BufferingStats& stats = statsPair.second;
3001 if (stats.numSegments == 0) {
3002 continue;
3003 }
3004 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3005 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3006 stats.totalTime;
3007 float doubleBufferRatio = static_cast<float>(
3008 stats.doubleBufferedTime) / stats.totalTime;
3009 float tripleBufferRatio = static_cast<float>(
3010 stats.tripleBufferedTime) / stats.totalTime;
3011 sorted.insert({activeTime, {name, twoBufferRatio,
3012 doubleBufferRatio, tripleBufferRatio}});
3013 }
3014 for (const auto& sortedPair : sorted) {
3015 float activeTime = sortedPair.first;
3016 const BufferTuple& values = sortedPair.second;
3017 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3018 std::get<0>(values).c_str(), activeTime,
3019 std::get<1>(values), std::get<2>(values),
3020 std::get<3>(values));
3021 }
3022 result.append("\n");
3023}
3024
3025
Mathias Agopian74d211a2013-04-22 16:55:35 +02003026void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3027 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003028{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003029 bool colorize = false;
3030 if (index < args.size()
3031 && (args[index] == String16("--color"))) {
3032 colorize = true;
3033 index++;
3034 }
3035
3036 Colorizer colorizer(colorize);
3037
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003038 // figure out if we're stuck somewhere
3039 const nsecs_t now = systemTime();
3040 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3041 const nsecs_t inTransaction(mDebugInTransaction);
3042 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3043 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3044
3045 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003046 * Dump library configuration.
3047 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003048
3049 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003050 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003051 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003052 appendSfConfigString(result);
3053 appendUiConfigString(result);
3054 appendGuiConfigString(result);
3055 result.append("\n");
3056
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003057 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003058 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003059 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003060 result.append(SyncFeatures::getInstance().toString());
3061 result.append("\n");
3062
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3064
Andy McFadden41d67d72014-04-25 16:58:34 -07003065 colorizer.bold(result);
3066 result.append("DispSync configuration: ");
3067 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003068 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3069 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3071 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003072 result.append("\n");
3073
Dan Stozab90cf072015-03-05 11:05:59 -08003074 // Dump static screen stats
3075 result.append("\n");
3076 dumpStaticScreenStats(result);
3077 result.append("\n");
3078
Dan Stozae77c7662016-05-13 11:37:28 -07003079 dumpBufferingStats(result);
3080
Andy McFadden4803b742012-09-24 19:07:20 -07003081 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003082 * Dump the visible layer list
3083 */
3084 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3085 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003086 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003087 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003088 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003089 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003090 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003092 }
3093
3094 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003095 * Dump Display state
3096 */
3097
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003098 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003099 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003100 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003101 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3102 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003104 }
3105
3106 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003107 * Dump SurfaceFlinger global state
3108 */
3109
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003110 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003111 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003112 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003113
Mathias Agopian888c8222012-08-04 21:10:38 -07003114 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003115 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003116
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003117 colorizer.bold(result);
3118 result.appendFormat("EGL implementation : %s\n",
3119 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3120 colorizer.reset(result);
3121 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003122 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003123
Mathias Agopian875d8e12013-06-07 15:35:48 -07003124 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125
Mathias Agopian42977342012-08-05 00:40:46 -07003126 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003127 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3128 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003129 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003130 " last eglSwapBuffers() time: %f us\n"
3131 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003132 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003133 " refresh-rate : %f fps\n"
3134 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003135 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003136 " gpu_to_cpu_unsupported : %d\n"
3137 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003138 mLastSwapBufferTime/1000.0,
3139 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003140 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003141 1e9 / activeConfig->getVsyncPeriod(),
3142 activeConfig->getDpiX(),
3143 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003144 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003145
Mathias Agopian74d211a2013-04-22 16:55:35 +02003146 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003147 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003148
Mathias Agopian74d211a2013-04-22 16:55:35 +02003149 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003151
3152 /*
3153 * VSYNC state
3154 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003155 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003156 result.append("\n");
3157
3158 /*
3159 * HWC layer minidump
3160 */
3161 for (size_t d = 0; d < mDisplays.size(); d++) {
3162 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3163 int32_t hwcId = displayDevice->getHwcDisplayId();
3164 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3165 continue;
3166 }
3167
3168 result.appendFormat("Display %d HWC layers:\n", hwcId);
3169 Layer::miniDumpHeader(result);
3170 for (size_t l = 0; l < count; l++) {
3171 const sp<Layer>& layer(currentLayers[l]);
3172 layer->miniDump(result, hwcId);
3173 }
3174 result.append("\n");
3175 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003176
3177 /*
3178 * Dump HWComposer state
3179 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003180 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003181 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003182 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003183 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003184 result.appendFormat(" h/w composer %s\n",
3185 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003187
3188 /*
3189 * Dump gralloc state
3190 */
3191 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3192 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003193}
3194
Mathias Agopian13127d82013-03-05 17:47:11 -08003195const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003196SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003197 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003198 wp<IBinder> dpy;
3199 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3200 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3201 dpy = mDisplays.keyAt(i);
3202 break;
3203 }
3204 }
3205 if (dpy == NULL) {
3206 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3207 // Just use the primary display so we have something to return
3208 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3209 }
3210 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003211}
3212
Keun young Park63f165f2012-08-31 10:53:36 -07003213bool SurfaceFlinger::startDdmConnection()
3214{
3215 void* libddmconnection_dso =
3216 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3217 if (!libddmconnection_dso) {
3218 return false;
3219 }
3220 void (*DdmConnection_start)(const char* name);
3221 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003222 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003223 if (!DdmConnection_start) {
3224 dlclose(libddmconnection_dso);
3225 return false;
3226 }
3227 (*DdmConnection_start)(getServiceName());
3228 return true;
3229}
3230
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003231status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 switch (code) {
3233 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003234 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003235 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003237 case CLEAR_ANIMATION_FRAME_STATS:
3238 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003239 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003240 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 {
3242 // codes that require permission check
3243 IPCThreadState* ipc = IPCThreadState::self();
3244 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003245 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003246 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003247 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003248 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003249 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003251 break;
3252 }
3253 case CAPTURE_SCREEN:
3254 {
3255 // codes that require permission check
3256 IPCThreadState* ipc = IPCThreadState::self();
3257 const int pid = ipc->getCallingPid();
3258 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003259 if ((uid != AID_GRAPHICS) &&
3260 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003261 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003262 return PERMISSION_DENIED;
3263 }
3264 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 }
3266 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003267 return OK;
3268}
3269
3270status_t SurfaceFlinger::onTransact(
3271 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3272{
3273 status_t credentialCheck = CheckTransactCodeCredentials(code);
3274 if (credentialCheck != OK) {
3275 return credentialCheck;
3276 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003277
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3279 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003280 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003281 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003282 IPCThreadState* ipc = IPCThreadState::self();
3283 const int pid = ipc->getCallingPid();
3284 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003285 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003286 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 return PERMISSION_DENIED;
3288 }
3289 int n;
3290 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003291 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003292 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293 return NO_ERROR;
3294 case 1002: // SHOW_UPDATES
3295 n = data.readInt32();
3296 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003297 invalidateHwcGeometry();
3298 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003301 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003302 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003304 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003305 setTransactionFlags(
3306 eTransactionNeeded|
3307 eDisplayTransactionNeeded|
3308 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003309 return NO_ERROR;
3310 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003311 case 1006:{ // send empty update
3312 signalRefresh();
3313 return NO_ERROR;
3314 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003315 case 1008: // toggle use of hw composer
3316 n = data.readInt32();
3317 mDebugDisableHWC = n ? 1 : 0;
3318 invalidateHwcGeometry();
3319 repaintEverything();
3320 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003321 case 1009: // toggle use of transform hint
3322 n = data.readInt32();
3323 mDebugDisableTransformHint = n ? 1 : 0;
3324 invalidateHwcGeometry();
3325 repaintEverything();
3326 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003328 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 reply->writeInt32(0);
3330 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003331 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003332 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003333 return NO_ERROR;
3334 case 1013: {
3335 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003336 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3337 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003338 return NO_ERROR;
3339 }
3340 case 1014: {
3341 // daltonize
3342 n = data.readInt32();
3343 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003344 case 1:
3345 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3346 break;
3347 case 2:
3348 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3349 break;
3350 case 3:
3351 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3352 break;
3353 default:
3354 mDaltonizer.setType(ColorBlindnessType::None);
3355 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003356 }
3357 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003358 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003359 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003360 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003361 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003362 invalidateHwcGeometry();
3363 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003364 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003366 case 1015: {
3367 // apply a color matrix
3368 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003369 if (n) {
3370 // color matrix is sent as mat3 matrix followed by vec3
3371 // offset, then packed into a mat4 where the last row is
3372 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003373 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003374 for (size_t j = 0; j < 4; j++) {
3375 mColorMatrix[i][j] = data.readFloat();
3376 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003377 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003378 } else {
3379 mColorMatrix = mat4();
3380 }
3381 invalidateHwcGeometry();
3382 repaintEverything();
3383 return NO_ERROR;
3384 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003385 // This is an experimental interface
3386 // Needs to be shifted to proper binder interface when we productize
3387 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003388 n = data.readInt32();
3389 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003390 return NO_ERROR;
3391 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003392 case 1017: {
3393 n = data.readInt32();
3394 mForceFullDamage = static_cast<bool>(n);
3395 return NO_ERROR;
3396 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003397 case 1018: { // Modify Choreographer's phase offset
3398 n = data.readInt32();
3399 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3400 return NO_ERROR;
3401 }
3402 case 1019: { // Modify SurfaceFlinger's phase offset
3403 n = data.readInt32();
3404 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3405 return NO_ERROR;
3406 }
Irvel468051e2016-06-13 16:44:44 -07003407 case 1020: { // Layer updates interceptor
3408 n = data.readInt32();
3409 if (n) {
3410 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003411 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003412 }
3413 else{
3414 ALOGV("Interceptor disabled");
3415 mInterceptor.disable();
3416 }
3417 return NO_ERROR;
3418 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003419 case 1021: { // Disable HWC virtual displays
3420 n = data.readInt32();
3421 mUseHwcVirtualDisplays = !n;
3422 return NO_ERROR;
3423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424 }
3425 }
3426 return err;
3427}
3428
Mathias Agopian53331da2011-08-22 21:44:41 -07003429void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003430 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003431 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003432}
3433
Mathias Agopian59119e62010-10-11 12:37:43 -07003434// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003435// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003436// ---------------------------------------------------------------------------
3437
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003438/* The code below is here to handle b/8734824
3439 *
3440 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003441 * from the surfaceflinger thread to the calling binder thread, where they
3442 * are executed. This allows the calling thread in the calling process to be
3443 * reused and not depend on having "enough" binder threads to handle the
3444 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003445 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003446class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003447 /* Parts of GraphicProducerWrapper are run on two different threads,
3448 * communicating by sending messages via Looper but also by shared member
3449 * data. Coherence maintenance is subtle and in places implicit (ugh).
3450 *
3451 * Don't rely on Looper's sendMessage/handleMessage providing
3452 * release/acquire semantics for any data not actually in the Message.
3453 * Data going from surfaceflinger to binder threads needs to be
3454 * synchronized explicitly.
3455 *
3456 * Barrier open/wait do provide release/acquire semantics. This provides
3457 * implicit synchronization for data coming back from binder to
3458 * surfaceflinger threads.
3459 */
3460
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003461 sp<IGraphicBufferProducer> impl;
3462 sp<Looper> looper;
3463 status_t result;
3464 bool exitPending;
3465 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003466 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003467 uint32_t code;
3468 Parcel const* data;
3469 Parcel* reply;
3470
3471 enum {
3472 MSG_API_CALL,
3473 MSG_EXIT
3474 };
3475
3476 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003477 * Called on surfaceflinger thread. This is called by our "fake"
3478 * BpGraphicBufferProducer. We package the data and reply Parcel and
3479 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003480 */
3481 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003482 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003483 this->code = code;
3484 this->data = &data;
3485 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003486 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003487 // if we've exited, we run the message synchronously right here.
3488 // note (JH): as far as I can tell from looking at the code, this
3489 // never actually happens. if it does, i'm not sure if it happens
3490 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003491 handleMessage(Message(MSG_API_CALL));
3492 } else {
3493 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003494 // Prevent stores to this->{code, data, reply} from being
3495 // reordered later than the construction of Message.
3496 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003497 looper->sendMessage(this, Message(MSG_API_CALL));
3498 barrier.wait();
3499 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003500 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003501 }
3502
3503 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003504 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003505 * call the real BpGraphicBufferProducer.
3506 */
3507 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003508 int what = message.what;
3509 // Prevent reads below from happening before the read from Message
3510 atomic_thread_fence(memory_order_acquire);
3511 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003512 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003513 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003514 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003515 exitRequested = true;
3516 }
3517 }
3518
3519public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003520 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003521 : impl(impl),
3522 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003523 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003524 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003525 exitRequested(false),
3526 code(0),
3527 data(NULL),
3528 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003529 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003530
Jesse Hallb154c422014-07-13 12:47:02 -07003531 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003532 status_t waitForResponse() {
3533 do {
3534 looper->pollOnce(-1);
3535 } while (!exitRequested);
3536 return result;
3537 }
3538
Jesse Hallb154c422014-07-13 12:47:02 -07003539 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003540 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003541 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003542 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003543 // Ensure this->result is visible to the binder thread before it
3544 // handles the message.
3545 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003546 looper->sendMessage(this, Message(MSG_EXIT));
3547 }
3548};
3549
3550
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003551status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3552 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003553 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003554 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003555 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003556
3557 if (CC_UNLIKELY(display == 0))
3558 return BAD_VALUE;
3559
3560 if (CC_UNLIKELY(producer == 0))
3561 return BAD_VALUE;
3562
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003563 // if we have secure windows on this display, never allow the screen capture
3564 // unless the producer interface is local (i.e.: we can take a screenshot for
3565 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003566 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003567
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003568 // Convert to surfaceflinger's internal rotation type.
3569 Transform::orientation_flags rotationFlags;
3570 switch (rotation) {
3571 case ISurfaceComposer::eRotateNone:
3572 rotationFlags = Transform::ROT_0;
3573 break;
3574 case ISurfaceComposer::eRotate90:
3575 rotationFlags = Transform::ROT_90;
3576 break;
3577 case ISurfaceComposer::eRotate180:
3578 rotationFlags = Transform::ROT_180;
3579 break;
3580 case ISurfaceComposer::eRotate270:
3581 rotationFlags = Transform::ROT_270;
3582 break;
3583 default:
3584 rotationFlags = Transform::ROT_0;
3585 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3586 break;
3587 }
3588
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003589 class MessageCaptureScreen : public MessageBase {
3590 SurfaceFlinger* flinger;
3591 sp<IBinder> display;
3592 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003593 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003594 uint32_t reqWidth, reqHeight;
3595 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003596 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003597 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003598 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003599 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003600 public:
3601 MessageCaptureScreen(SurfaceFlinger* flinger,
3602 const sp<IBinder>& display,
3603 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003604 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003605 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003606 bool useIdentityTransform,
3607 Transform::orientation_flags rotation,
3608 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003609 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003610 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003611 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003612 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003613 rotation(rotation), result(PERMISSION_DENIED),
3614 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003615 {
3616 }
3617 status_t getResult() const {
3618 return result;
3619 }
3620 virtual bool handler() {
3621 Mutex::Autolock _l(flinger->mStateLock);
3622 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003623 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003624 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003625 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003626 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003627 return true;
3628 }
3629 };
3630
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003631 // this creates a "fake" BBinder which will serve as a "fake" remote
3632 // binder to receive the marshaled calls and forward them to the
3633 // real remote (a BpGraphicBufferProducer)
3634 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3635
3636 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3637 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003638 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003639 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003640 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003641 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003642
3643 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003644 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003645 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003646 }
3647 return res;
3648}
3649
Mathias Agopian180f10d2013-04-10 22:55:41 -07003650
3651void SurfaceFlinger::renderScreenImplLocked(
3652 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003653 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003654 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003655 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003656{
3657 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003658 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003659
3660 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003661 const int32_t hw_w = hw->getWidth();
3662 const int32_t hw_h = hw->getHeight();
3663 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003664 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003665
Dan Stozac1879002014-05-22 15:59:05 -07003666 // if a default or invalid sourceCrop is passed in, set reasonable values
3667 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3668 !sourceCrop.isValid()) {
3669 sourceCrop.setLeftTop(Point(0, 0));
3670 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3671 }
3672
3673 // ensure that sourceCrop is inside screen
3674 if (sourceCrop.left < 0) {
3675 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3676 }
Dan Stozabe31f442014-06-11 11:20:54 -07003677 if (sourceCrop.right > hw_w) {
3678 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003679 }
3680 if (sourceCrop.top < 0) {
3681 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3682 }
Dan Stozabe31f442014-06-11 11:20:54 -07003683 if (sourceCrop.bottom > hw_h) {
3684 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003685 }
3686
Mathias Agopian180f10d2013-04-10 22:55:41 -07003687 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003688 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003689
3690 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003691 engine.setViewportAndProjection(
3692 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003693 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003694
3695 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003696 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003697
3698 const LayerVector& layers( mDrawingState.layersSortedByZ );
3699 const size_t count = layers.size();
3700 for (size_t i=0 ; i<count ; ++i) {
3701 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003702 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003703 if (state.layerStack == hw->getLayerStack()) {
3704 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3705 if (layer->isVisible()) {
3706 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003707 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003708 if (filtering) layer->setFiltering(false);
3709 }
3710 }
3711 }
3712 }
3713
Mathias Agopian931bda12013-08-28 18:11:46 -07003714 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003715}
3716
3717
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003718status_t SurfaceFlinger::captureScreenImplLocked(
3719 const sp<const DisplayDevice>& hw,
3720 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003721 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003722 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003723 bool useIdentityTransform, Transform::orientation_flags rotation,
3724 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003725{
3726 ATRACE_CALL();
3727
Mathias Agopian180f10d2013-04-10 22:55:41 -07003728 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003729 uint32_t hw_w = hw->getWidth();
3730 uint32_t hw_h = hw->getHeight();
3731
3732 if (rotation & Transform::ROT_90) {
3733 std::swap(hw_w, hw_h);
3734 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003735
Mathias Agopian180f10d2013-04-10 22:55:41 -07003736 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3737 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3738 reqWidth, reqHeight, hw_w, hw_h);
3739 return BAD_VALUE;
3740 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003741
Mathias Agopian180f10d2013-04-10 22:55:41 -07003742 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3743 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3744
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003745 bool secureLayerIsVisible = false;
3746 const LayerVector& layers(mDrawingState.layersSortedByZ);
3747 const size_t count = layers.size();
3748 for (size_t i = 0 ; i < count ; ++i) {
3749 const sp<Layer>& layer(layers[i]);
3750 const Layer::State& state(layer->getDrawingState());
3751 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3752 state.z <= maxLayerZ && layer->isVisible() &&
3753 layer->isSecure()) {
3754 secureLayerIsVisible = true;
3755 }
3756 }
3757
3758 if (!isLocalScreenshot && secureLayerIsVisible) {
3759 ALOGW("FB is protected: PERMISSION_DENIED");
3760 return PERMISSION_DENIED;
3761 }
3762
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003763 // create a surface (because we're a producer, and we need to
3764 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003765 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003766
3767 // Put the screenshot Surface into async mode so that
3768 // Layer::headFenceHasSignaled will always return true and we'll latch the
3769 // first buffer regardless of whether or not its acquire fence has
3770 // signaled. This is needed to avoid a race condition in the rotation
3771 // animation. See b/30209608
3772 sur->setAsyncMode(true);
3773
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003774 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003775
Michael Lentine5a16a622015-05-21 13:48:24 -07003776 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3777 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003778 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3779 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003780
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003781 int err = 0;
3782 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003783 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003784 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3785 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003786
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003787 if (err == NO_ERROR) {
3788 ANativeWindowBuffer* buffer;
3789 /* TODO: Once we have the sync framework everywhere this can use
3790 * server-side waits on the fence that dequeueBuffer returns.
3791 */
3792 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3793 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003794 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003795 // create an EGLImage from the buffer so we can later
3796 // turn it into a texture
3797 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3798 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3799 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003800 // this binds the given EGLImage as a framebuffer for the
3801 // duration of this scope.
3802 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3803 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003804 // this will in fact render into our dequeued buffer
3805 // via an FBO, which means we didn't have to create
3806 // an EGLSurface and therefore we're not
3807 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003808 renderScreenImplLocked(
3809 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3810 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003811
Riley Andrews86639902014-08-15 12:27:24 -07003812 // Attempt to create a sync khr object that can produce a sync point. If that
3813 // isn't available, create a non-dupable sync object in the fallback path and
3814 // wait on it directly.
3815 EGLSyncKHR sync;
3816 if (!DEBUG_SCREENSHOTS) {
3817 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003818 // native fence fd will not be populated until flush() is done.
3819 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003820 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003821 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003822 }
Riley Andrews86639902014-08-15 12:27:24 -07003823 if (sync != EGL_NO_SYNC_KHR) {
3824 // get the sync fd
3825 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3826 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3827 ALOGW("captureScreen: failed to dup sync khr object");
3828 syncFd = -1;
3829 }
3830 eglDestroySyncKHR(mEGLDisplay, sync);
3831 } else {
3832 // fallback path
3833 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3834 if (sync != EGL_NO_SYNC_KHR) {
3835 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3836 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3837 EGLint eglErr = eglGetError();
3838 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3839 ALOGW("captureScreen: fence wait timed out");
3840 } else {
3841 ALOGW_IF(eglErr != EGL_SUCCESS,
3842 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3843 }
3844 eglDestroySyncKHR(mEGLDisplay, sync);
3845 } else {
3846 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3847 }
3848 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003849 if (DEBUG_SCREENSHOTS) {
3850 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3851 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3852 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3853 hw, minLayerZ, maxLayerZ);
3854 delete [] pixels;
3855 }
3856
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003857 } else {
3858 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3859 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003860 window->cancelBuffer(window, buffer, syncFd);
3861 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003862 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003863 // destroy our image
3864 eglDestroyImageKHR(mEGLDisplay, image);
3865 } else {
3866 result = BAD_VALUE;
3867 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003868 if (buffer) {
3869 // queueBuffer takes ownership of syncFd
3870 result = window->queueBuffer(window, buffer, syncFd);
3871 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003872 }
3873 } else {
3874 result = BAD_VALUE;
3875 }
3876 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3877 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003878
Mathias Agopian74c40c02010-09-29 13:02:36 -07003879 return result;
3880}
3881
Mathias Agopiand5556842013-09-19 17:08:37 -07003882void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3883 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003884 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003885 for (size_t y=0 ; y<h ; y++) {
3886 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3887 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003888 if (p[x] != 0xFF000000) return;
3889 }
3890 }
3891 ALOGE("*** we just took a black screenshot ***\n"
3892 "requested minz=%d, maxz=%d, layerStack=%d",
3893 minLayerZ, maxLayerZ, hw->getLayerStack());
3894 const LayerVector& layers( mDrawingState.layersSortedByZ );
3895 const size_t count = layers.size();
3896 for (size_t i=0 ; i<count ; ++i) {
3897 const sp<Layer>& layer(layers[i]);
3898 const Layer::State& state(layer->getDrawingState());
3899 const bool visible = (state.layerStack == hw->getLayerStack())
3900 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3901 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003902 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003903 visible ? '+' : '-',
3904 i, layer->getName().string(), state.layerStack, state.z,
3905 layer->isVisible(), state.flags, state.alpha);
3906 }
3907 }
3908}
3909
Pablo Ceballosce796e72016-02-04 19:10:51 -08003910bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3911 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3912 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3913}
3914
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003915// ---------------------------------------------------------------------------
3916
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003917SurfaceFlinger::LayerVector::LayerVector() {
3918}
3919
3920SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003921 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003922}
3923
3924int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3925 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003926{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003927 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003928 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3929 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003930
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003931 uint32_t ls = l->getCurrentState().layerStack;
3932 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003933 if (ls != rs)
3934 return ls - rs;
3935
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003936 uint32_t lz = l->getCurrentState().z;
3937 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003938 if (lz != rz)
3939 return lz - rz;
3940
3941 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003942}
3943
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003945
3946
3947#if defined(__gl_h_)
3948#error "don't include gl/gl.h in this file"
3949#endif
3950
3951#if defined(__gl2_h_)
3952#error "don't include gl2/gl2.h in this file"
3953#endif