blob: 37fd70d8afe7270520deb528c997ec63c3473525 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096// This is the phase offset in nanoseconds of the software vsync event
97// relative to the vsync event reported by HWComposer. The software vsync
98// event is when SurfaceFlinger and Choreographer-based applications run each
99// frame.
100//
101// This phase offset allows adjustment of the minimum latency from application
102// wake-up (by Choregographer) time to the time at which the resulting window
103// image is displayed. This value may be either positive (after the HW vsync)
104// or negative (before the HW vsync). Setting it to 0 will result in a
105// minimum latency of two vsync periods because the app and SurfaceFlinger
106// will run just after the HW vsync. Setting it to a positive number will
107// result in the minimum latency being:
108//
109// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
110//
111// Note that reducing this latency makes it more likely for the applications
112// to not have their window content image ready in time. When this happens
113// the latency will end up being an additional vsync period, and animations
114// will hiccup. Therefore, this latency should be tuned somewhat
115// conservatively (or at least with awareness of the trade-off being made).
116static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
117
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700118// This is the phase offset at which SurfaceFlinger's composition runs.
119static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121// ---------------------------------------------------------------------------
122
Mathias Agopian99b49842011-06-27 16:05:52 -0700123const String16 sHardwareTest("android.permission.HARDWARE_TEST");
124const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
125const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
126const String16 sDump("android.permission.DUMP");
127
128// ---------------------------------------------------------------------------
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700131 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700133 mTransactionPending(false),
134 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700136 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700137 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700153 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800157 mHasColorMatrix(false),
158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Steve Blocka19954a2012-01-04 20:05:49 +0000163 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164
165 // debugging stuff...
166 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700167
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700169 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 property_get("debug.sf.showupdates", value, "0");
172 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174 property_get("debug.sf.ddms", value, "0");
175 mDebugDDMS = atoi(value);
176 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700177 if (!startDdmConnection()) {
178 // start failed, and DDMS debugging not enabled
179 mDebugDDMS = 0;
180 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700181 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700182 ALOGI_IF(mDebugRegion, "showupdates enabled");
183 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700184
185 property_get("debug.sf.disable_backpressure", value, "0");
186 mPropagateBackpressure = !atoi(value);
187 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700188
189 property_get("debug.sf.disable_hwc_vds", value, "0");
190 mUseHwcVirtualDisplays = !atoi(value);
191 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192}
193
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800194void SurfaceFlinger::onFirstRef()
195{
196 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197}
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199SurfaceFlinger::~SurfaceFlinger()
200{
Mathias Agopiana4912602012-07-12 14:25:33 -0700201 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
202 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
203 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204}
205
Dan Stozac7014012014-02-14 15:03:43 -0800206void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207{
208 // the window manager died on us. prepare its eulogy.
209
Andy McFadden13a082e2012-08-24 10:16:42 -0700210 // restore initial conditions (default device unblank, etc)
211 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800212
213 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700214 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800215}
216
Mathias Agopian7e27f052010-05-28 14:22:23 -0700217sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218{
Mathias Agopian96f08192010-06-02 23:28:45 -0700219 sp<ISurfaceComposerClient> bclient;
220 sp<Client> client(new Client(this));
221 status_t err = client->initCheck();
222 if (err == NO_ERROR) {
223 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 return bclient;
226}
227
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700228sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
229 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700230{
231 class DisplayToken : public BBinder {
232 sp<SurfaceFlinger> flinger;
233 virtual ~DisplayToken() {
234 // no more references, this display must be terminated
235 Mutex::Autolock _l(flinger->mStateLock);
236 flinger->mCurrentState.displays.removeItem(this);
237 flinger->setTransactionFlags(eDisplayTransactionNeeded);
238 }
239 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700240 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241 : flinger(flinger) {
242 }
243 };
244
245 sp<BBinder> token = new DisplayToken(this);
246
247 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700248 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700249 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700250 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700251 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700252 return token;
253}
254
Jesse Hall6c913be2013-08-08 12:15:49 -0700255void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
256 Mutex::Autolock _l(mStateLock);
257
258 ssize_t idx = mCurrentState.displays.indexOfKey(display);
259 if (idx < 0) {
260 ALOGW("destroyDisplay: invalid display token");
261 return;
262 }
263
264 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
265 if (!info.isVirtualDisplay()) {
266 ALOGE("destroyDisplay called for non-virtual display");
267 return;
268 }
Irvelffc9efc2016-07-27 15:16:37 -0700269 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700270 mCurrentState.displays.removeItemsAt(idx);
271 setTransactionFlags(eDisplayTransactionNeeded);
272}
273
Jesse Hall692c7232012-11-08 15:41:56 -0800274void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800275 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800276 ALOGW_IF(mBuiltinDisplays[type],
277 "Overwriting display token for display type %d", type);
278 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800279 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700280 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800281 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700282 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800283}
284
Mathias Agopiane57f2922012-08-09 16:29:12 -0700285sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700286 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700287 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
288 return NULL;
289 }
Jesse Hall692c7232012-11-08 15:41:56 -0800290 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291}
292
Jamie Gennis9a78c902011-01-12 18:30:40 -0800293sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
294{
295 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
296 return gba;
297}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299void SurfaceFlinger::bootFinished()
300{
301 const nsecs_t now = systemTime();
302 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000303 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700304 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700305
306 // wait patiently for the window manager death
307 const String16 name("window");
308 sp<IBinder> window(defaultServiceManager()->getService(name));
309 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700310 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700311 }
312
313 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700314 // formerly we would just kill the process, but we now ask it to exit so it
315 // can choose where to stop the animation.
316 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700317
318 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
319 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
320 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321}
322
Mathias Agopian3f844832013-08-07 21:24:32 -0700323void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700324 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 RenderEngine& engine;
326 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700327 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700328 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
329 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330 }
331 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700332 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700333 return true;
334 }
335 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700336 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337}
338
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700339class DispSyncSource : public VSyncSource, private DispSync::Callback {
340public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700341 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000342 const char* name) :
343 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700344 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700345 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
347 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700348 mDispSync(dispSync),
349 mCallbackMutex(),
350 mCallback(),
351 mVsyncMutex(),
352 mPhaseOffset(phaseOffset),
353 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700354
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700355 virtual ~DispSyncSource() {}
356
357 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700358 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700359 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000360 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 static_cast<DispSync::Callback*>(this));
362 if (err != NO_ERROR) {
363 ALOGE("error registering vsync callback: %s (%d)",
364 strerror(-err), err);
365 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700366 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 } else {
368 status_t err = mDispSync->removeEventListener(
369 static_cast<DispSync::Callback*>(this));
370 if (err != NO_ERROR) {
371 ALOGE("error unregistering vsync callback: %s (%d)",
372 strerror(-err), err);
373 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700374 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700376 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 }
378
379 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 mCallback = callback;
382 }
383
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700384 virtual void setPhaseOffset(nsecs_t phaseOffset) {
385 Mutex::Autolock lock(mVsyncMutex);
386
387 // Normalize phaseOffset to [0, period)
388 auto period = mDispSync->getPeriod();
389 phaseOffset %= period;
390 if (phaseOffset < 0) {
391 // If we're here, then phaseOffset is in (-period, 0). After this
392 // operation, it will be in (0, period)
393 phaseOffset += period;
394 }
395 mPhaseOffset = phaseOffset;
396
397 // If we're not enabled, we don't need to mess with the listeners
398 if (!mEnabled) {
399 return;
400 }
401
402 // Remove the listener with the old offset
403 status_t err = mDispSync->removeEventListener(
404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error unregistering vsync callback: %s (%d)",
407 strerror(-err), err);
408 }
409
410 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error registering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
417 }
418
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419private:
420 virtual void onDispSyncEvent(nsecs_t when) {
421 sp<VSyncSource::Callback> callback;
422 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700423 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 callback = mCallback;
425
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700426 if (mTraceVsync) {
427 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700429 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
431
432 if (callback != NULL) {
433 callback->onVSyncEvent(when);
434 }
435 }
436
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 const char* const mName;
438
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 int mValue;
440
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700441 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700442 const String8 mVsyncOnLabel;
443 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700444
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446
447 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449
450 Mutex mVsyncMutex; // Protects the following
451 nsecs_t mPhaseOffset;
452 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453};
454
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700455class InjectVSyncSource : public VSyncSource {
456public:
457 InjectVSyncSource() {}
458
459 virtual ~InjectVSyncSource() {}
460
461 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
462 std::lock_guard<std::mutex> lock(mCallbackMutex);
463 mCallback = callback;
464 }
465
466 virtual void onInjectSyncEvent(nsecs_t when) {
467 std::lock_guard<std::mutex> lock(mCallbackMutex);
468 mCallback->onVSyncEvent(when);
469 }
470
471 virtual void setVSyncEnabled(bool) {}
472 virtual void setPhaseOffset(nsecs_t) {}
473
474private:
475 std::mutex mCallbackMutex; // Protects the following
476 sp<VSyncSource::Callback> mCallback;
477};
478
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700480 ALOGI( "SurfaceFlinger's main thread ready to run. "
481 "Initializing graphics H/W...");
482
Dan Stoza9e56aa02015-11-02 13:00:03 -0800483 { // Autolock scope
484 Mutex::Autolock _l(mStateLock);
485
486 // initialize EGL for the default display
487 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
488 eglInitialize(mEGLDisplay, NULL, NULL);
489
490 // start the EventThread
491 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
492 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700493 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800494 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
495 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700496 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800497 mEventQueue.setEventThread(mSFEventThread);
498
Tim Murrayacff43d2016-07-29 13:57:24 -0700499 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700500 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700501 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700502 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
503 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
504 }
505
Dan Stoza9e56aa02015-11-02 13:00:03 -0800506 // Get a RenderEngine for the given display / config (can't fail)
507 mRenderEngine = RenderEngine::create(mEGLDisplay,
508 HAL_PIXEL_FORMAT_RGBA_8888);
509 }
510
511 // Drop the state lock while we initialize the hardware composer. We drop
512 // the lock because on creation, it will call back into SurfaceFlinger to
513 // initialize the primary display.
514 mHwc = new HWComposer(this);
515 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
516
Jesse Hall692c7232012-11-08 15:41:56 -0800517 Mutex::Autolock _l(mStateLock);
518
Mathias Agopian875d8e12013-06-07 15:35:48 -0700519 // retrieve the EGL context that was selected/created
520 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700521
Mathias Agopianda27af92012-09-13 18:17:13 -0700522 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
523 "couldn't create EGLContext");
524
Dan Stoza9e56aa02015-11-02 13:00:03 -0800525 // make the GLContext current so that we can create textures when creating
526 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700527 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
528
Jamie Gennisd1700752013-10-14 12:22:52 -0700529 mEventControlThread = new EventControlThread(this);
530 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
531
Mathias Agopian92a979a2012-08-02 18:32:23 -0700532 // initialize our drawing state
533 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700534
Andy McFadden13a082e2012-08-24 10:16:42 -0700535 // set initial conditions (e.g. unblank default device)
536 initializeDisplays();
537
Dan Stoza4e637772016-07-28 13:31:51 -0700538 mRenderEngine->primeCache();
539
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700540 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700541 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542
Dan Stoza9e56aa02015-11-02 13:00:03 -0800543 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700544}
545
Mathias Agopiana67e4182012-06-19 17:26:12 -0700546void SurfaceFlinger::startBootAnim() {
547 // start boot animation
548 property_set("service.bootanim.exit", "0");
549 property_set("ctl.start", "bootanim");
550}
551
Mathias Agopian875d8e12013-06-07 15:35:48 -0700552size_t SurfaceFlinger::getMaxTextureSize() const {
553 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700554}
555
Mathias Agopian875d8e12013-06-07 15:35:48 -0700556size_t SurfaceFlinger::getMaxViewportDims() const {
557 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700558}
559
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800561
Jamie Gennis582270d2011-08-17 18:19:00 -0700562bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800563 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800564 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800565 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700566 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800567}
568
Dan Stoza7f7da322014-05-02 15:26:25 -0700569status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
570 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700571 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700572 return BAD_VALUE;
573 }
574
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500575 if (!display.get())
576 return NAME_NOT_FOUND;
577
Jesse Hall692c7232012-11-08 15:41:56 -0800578 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700579 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800580 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700581 type = i;
582 break;
583 }
584 }
585
586 if (type < 0) {
587 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700588 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700589
Mathias Agopian8b736f12012-08-13 17:54:26 -0700590 // TODO: Not sure if display density should handled by SF any longer
591 class Density {
592 static int getDensityFromProperty(char const* propName) {
593 char property[PROPERTY_VALUE_MAX];
594 int density = 0;
595 if (property_get(propName, property, NULL) > 0) {
596 density = atoi(property);
597 }
598 return density;
599 }
600 public:
601 static int getEmuDensity() {
602 return getDensityFromProperty("qemu.sf.lcd_density"); }
603 static int getBuildDensity() {
604 return getDensityFromProperty("ro.sf.lcd_density"); }
605 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700606
Dan Stoza7f7da322014-05-02 15:26:25 -0700607 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700608
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700610 DisplayInfo info = DisplayInfo();
611
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612 float xdpi = hwConfig->getDpiX();
613 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700614
615 if (type == DisplayDevice::DISPLAY_PRIMARY) {
616 // The density of the device is provided by a build property
617 float density = Density::getBuildDensity() / 160.0f;
618 if (density == 0) {
619 // the build doesn't provide a density -- this is wrong!
620 // use xdpi instead
621 ALOGE("ro.sf.lcd_density must be defined as a build property");
622 density = xdpi / 160.0f;
623 }
624 if (Density::getEmuDensity()) {
625 // if "qemu.sf.lcd_density" is specified, it overrides everything
626 xdpi = ydpi = density = Density::getEmuDensity();
627 density /= 160.0f;
628 }
629 info.density = density;
630
631 // TODO: this needs to go away (currently needed only by webkit)
632 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
633 info.orientation = hw->getOrientation();
634 } else {
635 // TODO: where should this value come from?
636 static const int TV_DENSITY = 213;
637 info.density = TV_DENSITY / 160.0f;
638 info.orientation = 0;
639 }
640
Dan Stoza9e56aa02015-11-02 13:00:03 -0800641 info.w = hwConfig->getWidth();
642 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700643 info.xdpi = xdpi;
644 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800645 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700646 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647
Andy McFadden91b2ca82014-06-13 14:04:23 -0700648 // This is how far in advance a buffer must be queued for
649 // presentation at a given time. If you want a buffer to appear
650 // on the screen at time N, you must submit the buffer before
651 // (N - presentationDeadline).
652 //
653 // Normally it's one full refresh period (to give SF a chance to
654 // latch the buffer), but this can be reduced by configuring a
655 // DispSync offset. Any additional delays introduced by the hardware
656 // composer or panel must be accounted for here.
657 //
658 // We add an additional 1ms to allow for processing time and
659 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660 info.presentationDeadline = hwConfig->getVsyncPeriod() -
661 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700662
663 // All non-virtual displays are currently considered secure.
664 info.secure = true;
665
Michael Wright28f24d02016-07-12 13:30:53 -0700666 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700667 }
668
Dan Stoza7f7da322014-05-02 15:26:25 -0700669 return NO_ERROR;
670}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700671
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800672status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700673 DisplayStatInfo* stats) {
674 if (stats == NULL) {
675 return BAD_VALUE;
676 }
677
678 // FIXME for now we always return stats for the primary display
679 memset(stats, 0, sizeof(*stats));
680 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
681 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
682 return NO_ERROR;
683}
684
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700685int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700686 sp<DisplayDevice> device(getDisplayDevice(display));
687 if (device != NULL) {
688 return device->getActiveConfig();
689 }
690 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700691}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700692
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700693void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
694 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
695 this);
696 int32_t type = hw->getDisplayType();
697 int currentMode = hw->getActiveConfig();
698
699 if (mode == currentMode) {
700 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
701 return;
702 }
703
704 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
705 ALOGW("Trying to set config for virtual display");
706 return;
707 }
708
709 hw->setActiveConfig(mode);
710 getHwComposer().setActiveConfig(type, mode);
711}
712
713status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
714 class MessageSetActiveConfig: public MessageBase {
715 SurfaceFlinger& mFlinger;
716 sp<IBinder> mDisplay;
717 int mMode;
718 public:
719 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
720 int mode) :
721 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
722 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700723 Vector<DisplayInfo> configs;
724 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700725 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700726 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700727 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700728 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700729 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700730 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
731 if (hw == NULL) {
732 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700733 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700734 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
735 ALOGW("Attempt to set active config = %d for virtual display",
736 mMode);
737 } else {
738 mFlinger.setActiveConfigInternal(hw, mMode);
739 }
740 return true;
741 }
742 };
743 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
744 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700745 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700746}
Michael Wright28f24d02016-07-12 13:30:53 -0700747status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
748 Vector<android_color_mode_t>* outColorModes) {
749 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
750 return BAD_VALUE;
751 }
752
753 if (!display.get()) {
754 return NAME_NOT_FOUND;
755 }
756
757 int32_t type = NAME_NOT_FOUND;
758 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
759 if (display == mBuiltinDisplays[i]) {
760 type = i;
761 break;
762 }
763 }
764
765 if (type < 0) {
766 return type;
767 }
768
769 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
770 outColorModes->clear();
771 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
772
773 return NO_ERROR;
774}
775
776android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
777 sp<DisplayDevice> device(getDisplayDevice(display));
778 if (device != nullptr) {
779 return device->getActiveColorMode();
780 }
781 return static_cast<android_color_mode_t>(BAD_VALUE);
782}
783
784void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
785 android_color_mode_t mode) {
786 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
787 this);
788 int32_t type = hw->getDisplayType();
789 android_color_mode_t currentMode = hw->getActiveColorMode();
790
791 if (mode == currentMode) {
792 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
793 return;
794 }
795
796 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
797 ALOGW("Trying to set config for virtual display");
798 return;
799 }
800
801 hw->setActiveColorMode(mode);
802 getHwComposer().setActiveColorMode(type, mode);
803}
804
805
806status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
807 android_color_mode_t colorMode) {
808 class MessageSetActiveColorMode: public MessageBase {
809 SurfaceFlinger& mFlinger;
810 sp<IBinder> mDisplay;
811 android_color_mode_t mMode;
812 public:
813 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
814 android_color_mode_t mode) :
815 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
816 virtual bool handler() {
817 Vector<android_color_mode_t> modes;
818 mFlinger.getDisplayColorModes(mDisplay, &modes);
819 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
820 if (mMode < 0 || !exists) {
821 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
822 mDisplay.get());
823 return true;
824 }
825 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
826 if (hw == nullptr) {
827 ALOGE("Attempt to set active color mode = %d for null display %p",
828 mMode, mDisplay.get());
829 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
830 ALOGW("Attempt to set active color mode= %d for virtual display",
831 mMode);
832 } else {
833 mFlinger.setActiveColorModeInternal(hw, mMode);
834 }
835 return true;
836 }
837 };
838 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
839 postMessageSync(msg);
840 return NO_ERROR;
841}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700842
Svetoslavd85084b2014-03-20 10:28:31 -0700843status_t SurfaceFlinger::clearAnimationFrameStats() {
844 Mutex::Autolock _l(mStateLock);
845 mAnimFrameTracker.clearStats();
846 return NO_ERROR;
847}
848
849status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
850 Mutex::Autolock _l(mStateLock);
851 mAnimFrameTracker.getStats(outStats);
852 return NO_ERROR;
853}
854
Dan Stozac4f471e2016-03-24 09:31:08 -0700855status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
856 HdrCapabilities* outCapabilities) const {
857 Mutex::Autolock _l(mStateLock);
858
859 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
860 if (displayDevice == nullptr) {
861 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
862 return BAD_VALUE;
863 }
864
865 std::unique_ptr<HdrCapabilities> capabilities =
866 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
867 if (capabilities) {
868 std::swap(*outCapabilities, *capabilities);
869 } else {
870 return BAD_VALUE;
871 }
872
873 return NO_ERROR;
874}
875
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700876status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
877 if (enable == mInjectVSyncs) {
878 return NO_ERROR;
879 }
880
881 if (enable) {
882 mInjectVSyncs = enable;
883 ALOGV("VSync Injections enabled");
884 if (mVSyncInjector.get() == nullptr) {
885 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700886 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700887 }
888 mEventQueue.setEventThread(mInjectorEventThread);
889 } else {
890 mInjectVSyncs = enable;
891 ALOGV("VSync Injections disabled");
892 mEventQueue.setEventThread(mSFEventThread);
893 mVSyncInjector.clear();
894 }
895 return NO_ERROR;
896}
897
898status_t SurfaceFlinger::injectVSync(nsecs_t when) {
899 if (!mInjectVSyncs) {
900 ALOGE("VSync Injections not enabled");
901 return BAD_VALUE;
902 }
903 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
904 ALOGV("Injecting VSync inside SurfaceFlinger");
905 mVSyncInjector->onInjectSyncEvent(when);
906 }
907 return NO_ERROR;
908}
909
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800910// ----------------------------------------------------------------------------
911
912sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800913 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700914}
915
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800916// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800917
918void SurfaceFlinger::waitForEvent() {
919 mEventQueue.waitMessage();
920}
921
922void SurfaceFlinger::signalTransaction() {
923 mEventQueue.invalidate();
924}
925
926void SurfaceFlinger::signalLayerUpdate() {
927 mEventQueue.invalidate();
928}
929
930void SurfaceFlinger::signalRefresh() {
931 mEventQueue.refresh();
932}
933
934status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800935 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800936 return mEventQueue.postMessage(msg, reltime);
937}
938
939status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800940 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800941 status_t res = mEventQueue.postMessage(msg, reltime);
942 if (res == NO_ERROR) {
943 msg->wait();
944 }
945 return res;
946}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800947
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700948void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700949 do {
950 waitForEvent();
951 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800952}
953
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700954void SurfaceFlinger::enableHardwareVsync() {
955 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700956 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700957 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700958 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
959 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700960 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700961 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700962}
963
Jesse Hall948fe0c2013-10-14 12:56:09 -0700964void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700965 Mutex::Autolock _l(mHWVsyncLock);
966
Jesse Hall948fe0c2013-10-14 12:56:09 -0700967 if (makeAvailable) {
968 mHWVsyncAvailable = true;
969 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700970 // Hardware vsync is not currently available, so abort the resync
971 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700972 return;
973 }
974
Dan Stoza9e56aa02015-11-02 13:00:03 -0800975 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
976 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700977
978 mPrimaryDispSync.reset();
979 mPrimaryDispSync.setPeriod(period);
980
981 if (!mPrimaryHWVsyncEnabled) {
982 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700983 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
984 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700985 mPrimaryHWVsyncEnabled = true;
986 }
987}
988
Jesse Hall948fe0c2013-10-14 12:56:09 -0700989void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700990 Mutex::Autolock _l(mHWVsyncLock);
991 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700992 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
993 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700994 mPrimaryDispSync.endResync();
995 mPrimaryHWVsyncEnabled = false;
996 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700997 if (makeUnavailable) {
998 mHWVsyncAvailable = false;
999 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001000}
1001
Tim Murray4a4e4a22016-04-19 16:29:23 +00001002void SurfaceFlinger::resyncWithRateLimit() {
1003 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1004 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001005 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001006 }
1007}
1008
Dan Stoza9e56aa02015-11-02 13:00:03 -08001009void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001010 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001011
Jamie Gennisd1700752013-10-14 12:22:52 -07001012 { // Scope for the lock
1013 Mutex::Autolock _l(mHWVsyncLock);
1014 if (type == 0 && mPrimaryHWVsyncEnabled) {
1015 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001016 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001017 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001018
1019 if (needsHwVsync) {
1020 enableHardwareVsync();
1021 } else {
1022 disableHardwareVsync(false);
1023 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001024}
1025
Dan Stoza9e56aa02015-11-02 13:00:03 -08001026void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1027 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1028 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1029 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001030
Dan Stoza9e56aa02015-11-02 13:00:03 -08001031 // All non-virtual displays are currently considered secure.
1032 bool isSecure = true;
1033
1034 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1035 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1036 wp<IBinder> token = mBuiltinDisplays[type];
1037
1038 sp<IGraphicBufferProducer> producer;
1039 sp<IGraphicBufferConsumer> consumer;
1040 BufferQueue::createBufferQueue(&producer, &consumer,
1041 new GraphicBufferAlloc());
1042
1043 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1044 DisplayDevice::DISPLAY_PRIMARY, consumer);
1045 sp<DisplayDevice> hw = new DisplayDevice(this,
1046 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1047 producer, mRenderEngine->getEGLConfig());
1048 mDisplays.add(token, hw);
1049 } else {
1050 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001051 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001052 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001053 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001054 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001055 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1056 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001057 }
1058 setTransactionFlags(eDisplayTransactionNeeded);
1059
Andy McFadden9e9689c2012-10-10 18:17:51 -07001060 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001061 }
Mathias Agopian86303202012-07-24 22:46:10 -07001062}
1063
Dan Stoza9e56aa02015-11-02 13:00:03 -08001064void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001066 getHwComposer().setVsyncEnabled(disp,
1067 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001068}
1069
Mathias Agopian4fec8732012-06-29 14:12:52 -07001070void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001071 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001072 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001073 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001074 bool frameMissed = !mHadClientComposition &&
1075 mPreviousPresentFence != Fence::NO_FENCE &&
1076 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1077 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001078 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001079 signalLayerUpdate();
1080 break;
1081 }
1082
Dan Stoza6b9454d2014-11-07 16:00:59 -08001083 bool refreshNeeded = handleMessageTransaction();
1084 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001085 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001086 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001087 // Signal a refresh if a transaction modified the window state,
1088 // a new buffer was latched, or if HWC has requested a full
1089 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001090 signalRefresh();
1091 }
1092 break;
1093 }
1094 case MessageQueue::REFRESH: {
1095 handleMessageRefresh();
1096 break;
1097 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001098 }
1099}
1100
Dan Stoza6b9454d2014-11-07 16:00:59 -08001101bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001102 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001103 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001104 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001105 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001106 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001107 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001108}
1109
Dan Stoza6b9454d2014-11-07 16:00:59 -08001110bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001111 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001112 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001113}
1114
1115void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001116 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001117
Pablo Ceballos40845df2016-01-25 17:41:15 -08001118 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001119
Dan Stoza05dacfb2016-07-01 13:33:38 -07001120 preComposition();
1121 rebuildLayerStacks();
1122 setUpHWComposer();
1123 doDebugFlashRegions();
1124 doComposition();
1125 postComposition(refreshStartTime);
1126
1127 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001128
1129 mHadClientComposition = false;
1130 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1131 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1132 mHadClientComposition = mHadClientComposition ||
1133 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1134 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001135
Dan Stoza9e56aa02015-11-02 13:00:03 -08001136 // Release any buffers which were replaced this frame
1137 for (auto& layer : mLayersWithQueuedFrames) {
1138 layer->releasePendingBuffer();
1139 }
1140 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001141}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001142
Mathias Agopiancd60f992012-08-16 16:28:27 -07001143void SurfaceFlinger::doDebugFlashRegions()
1144{
1145 // is debugging enabled
1146 if (CC_LIKELY(!mDebugRegion))
1147 return;
1148
1149 const bool repaintEverything = mRepaintEverything;
1150 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1151 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001152 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001153 // transform the dirty region into this screen's coordinate space
1154 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1155 if (!dirtyRegion.isEmpty()) {
1156 // redraw the whole screen
1157 doComposeSurfaces(hw, Region(hw->bounds()));
1158
1159 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001160 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001161 RenderEngine& engine(getRenderEngine());
1162 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1163
Mathias Agopianda27af92012-09-13 18:17:13 -07001164 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001165 }
1166 }
1167 }
1168
1169 postFramebuffer();
1170
1171 if (mDebugRegion > 1) {
1172 usleep(mDebugRegion * 1000);
1173 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001174
Dan Stoza9e56aa02015-11-02 13:00:03 -08001175 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001176 auto& displayDevice = mDisplays[displayId];
1177 if (!displayDevice->isDisplayOn()) {
1178 continue;
1179 }
1180
1181 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001182 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1183 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001184 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001185}
1186
1187void SurfaceFlinger::preComposition()
1188{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001189 ATRACE_CALL();
1190 ALOGV("preComposition");
1191
Mathias Agopiancd60f992012-08-16 16:28:27 -07001192 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001193 const LayerVector& layers(mDrawingState.layersSortedByZ);
1194 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001195 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001196 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001197 needExtraInvalidate = true;
1198 }
1199 }
1200 if (needExtraInvalidate) {
1201 signalLayerUpdate();
1202 }
1203}
1204
Pablo Ceballos40845df2016-01-25 17:41:15 -08001205void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001206{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 ATRACE_CALL();
1208 ALOGV("postComposition");
1209
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001210 const LayerVector& layers(mDrawingState.layersSortedByZ);
1211 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001212 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001213 bool frameLatched = layers[i]->onPostComposition();
1214 if (frameLatched) {
1215 recordBufferingStats(layers[i]->getName().string(),
1216 layers[i]->getOccupancyHistory(false));
1217 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001218 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001219
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221
1222 if (presentFence->isValid()) {
1223 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1224 enableHardwareVsync();
1225 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227 }
1228 }
1229
Dan Stozab90cf072015-03-05 11:05:59 -08001230 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001231 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001232 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 enableHardwareVsync();
1234 }
1235 }
1236
Pablo Ceballos40845df2016-01-25 17:41:15 -08001237 mFenceTracker.addFrame(refreshStartTime, presentFence,
1238 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1239
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001240 if (mAnimCompositionPending) {
1241 mAnimCompositionPending = false;
1242
Jesse Halla9a1b002013-02-27 16:39:25 -08001243 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001244 mAnimFrameTracker.setActualPresentFence(presentFence);
1245 } else {
1246 // The HWC doesn't support present fences, so use the refresh
1247 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001248 nsecs_t presentTime =
1249 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001250 mAnimFrameTracker.setActualPresentTime(presentTime);
1251 }
1252 mAnimFrameTracker.advanceFrame();
1253 }
Dan Stozab90cf072015-03-05 11:05:59 -08001254
1255 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1256 return;
1257 }
1258
1259 nsecs_t currentTime = systemTime();
1260 if (mHasPoweredOff) {
1261 mHasPoweredOff = false;
1262 } else {
1263 nsecs_t period = mPrimaryDispSync.getPeriod();
1264 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1265 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1266 if (numPeriods < NUM_BUCKETS - 1) {
1267 mFrameBuckets[numPeriods] += elapsedTime;
1268 } else {
1269 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1270 }
1271 mTotalTime += elapsedTime;
1272 }
1273 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001274}
1275
1276void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001277 ATRACE_CALL();
1278 ALOGV("rebuildLayerStacks");
1279
Mathias Agopiancd60f992012-08-16 16:28:27 -07001280 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001281 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001282 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001283 mVisibleRegionsDirty = false;
1284 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001285
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001286 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001287 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001288 Region opaqueRegion;
1289 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001290 Vector<sp<Layer>> layersSortedByZ;
1291 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1292 const Transform& tr(displayDevice->getTransform());
1293 const Rect bounds(displayDevice->getBounds());
1294 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001295 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296 displayDevice->getLayerStack(), dirtyRegion,
1297 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001298
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001299 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001300 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001301 const sp<Layer>& layer(layers[i]);
1302 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001304 Region drawRegion(tr.transform(
1305 layer->visibleNonTransparentRegion));
1306 drawRegion.andSelf(bounds);
1307 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001308 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001309 } else {
1310 // Clear out the HWC layer if this layer was
1311 // previously visible, but no longer is
1312 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1313 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001314 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001315 }
1316 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001317 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1319 displayDevice->undefinedRegion.set(bounds);
1320 displayDevice->undefinedRegion.subtractSelf(
1321 tr.transform(opaqueRegion));
1322 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001323 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001324 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001325}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001326
Mathias Agopiancd60f992012-08-16 16:28:27 -07001327void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001328 ATRACE_CALL();
1329 ALOGV("setUpHWComposer");
1330
Jesse Hall028dc8f2013-08-20 16:35:32 -07001331 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001332 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1333 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1334 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1335
1336 // If nothing has changed (!dirty), don't recompose.
1337 // If something changed, but we don't currently have any visible layers,
1338 // and didn't when we last did a composition, then skip it this time.
1339 // The second rule does two things:
1340 // - When all layers are removed from a display, we'll emit one black
1341 // frame, then nothing more until we get new layers.
1342 // - When a display is created with a private layer stack, we won't
1343 // emit any black frames until a layer is added to the layer stack.
1344 bool mustRecompose = dirty && !(empty && wasEmpty);
1345
1346 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1347 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1348 mustRecompose ? "doing" : "skipping",
1349 dirty ? "+" : "-",
1350 empty ? "+" : "-",
1351 wasEmpty ? "+" : "-");
1352
Dan Stoza71433162014-02-04 16:22:36 -08001353 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001354
1355 if (mustRecompose) {
1356 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1357 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001358 }
1359
Dan Stoza9e56aa02015-11-02 13:00:03 -08001360 // build the h/w work list
1361 if (CC_UNLIKELY(mGeometryInvalid)) {
1362 mGeometryInvalid = false;
1363 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1364 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1365 const auto hwcId = displayDevice->getHwcDisplayId();
1366 if (hwcId >= 0) {
1367 const Vector<sp<Layer>>& currentLayers(
1368 displayDevice->getVisibleLayersSortedByZ());
1369 bool foundLayerWithoutHwc = false;
1370 for (auto& layer : currentLayers) {
1371 if (!layer->hasHwcLayer(hwcId)) {
1372 auto hwcLayer = mHwc->createLayer(hwcId);
1373 if (hwcLayer) {
1374 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1375 } else {
1376 layer->forceClientComposition(hwcId);
1377 foundLayerWithoutHwc = true;
1378 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001379 }
1380 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001381
Dan Stoza9e56aa02015-11-02 13:00:03 -08001382 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001383 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001385 }
1386 }
1387 }
1388 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001389 }
Riley Andrews03414a12014-07-01 14:22:59 -07001390
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001391
1392 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 // Set the per-frame data
1395 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1396 auto& displayDevice = mDisplays[displayId];
1397 const auto hwcId = displayDevice->getHwcDisplayId();
1398 if (hwcId < 0) {
1399 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001400 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001401 if (colorMatrix != mPreviousColorMatrix) {
1402 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1403 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1404 "display %zd: %d", displayId, result);
1405 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001406 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1407 layer->setPerFrameData(displayDevice);
1408 }
1409 }
1410
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001411 mPreviousColorMatrix = colorMatrix;
1412
Dan Stoza9e56aa02015-11-02 13:00:03 -08001413 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001414 auto& displayDevice = mDisplays[displayId];
1415 if (!displayDevice->isDisplayOn()) {
1416 continue;
1417 }
1418
1419 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001420 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1421 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001422 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001423}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001424
Mathias Agopiancd60f992012-08-16 16:28:27 -07001425void SurfaceFlinger::doComposition() {
1426 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427 ALOGV("doComposition");
1428
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001429 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001430 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001431 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001432 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433 // transform the dirty region into this screen's coordinate space
1434 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001435
1436 // repaint the framebuffer (if needed)
1437 doDisplayComposition(hw, dirtyRegion);
1438
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439 hw->dirtyRegion.clear();
1440 hw->flip(hw->swapRegion);
1441 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001442 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001443 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001444 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445}
1446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001447void SurfaceFlinger::postFramebuffer()
1448{
Mathias Agopian841cde52012-03-01 15:44:37 -08001449 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001451
Mathias Agopiana44b0412011-10-16 18:46:35 -07001452 const nsecs_t now = systemTime();
1453 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001454
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1456 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001457 if (!displayDevice->isDisplayOn()) {
1458 continue;
1459 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001460 const auto hwcId = displayDevice->getHwcDisplayId();
1461 if (hwcId >= 0) {
1462 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001463 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001464 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001465 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1467 sp<Fence> releaseFence = Fence::NO_FENCE;
1468 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1469 releaseFence = displayDevice->getClientTargetAcquireFence();
1470 } else {
1471 auto hwcLayer = layer->getHwcLayer(hwcId);
1472 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001473 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001474 layer->onLayerDisplayed(releaseFence);
1475 }
1476 if (hwcId >= 0) {
1477 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001478 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001479 }
1480
Mathias Agopiana44b0412011-10-16 18:46:35 -07001481 mLastSwapBufferTime = systemTime() - now;
1482 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001483
1484 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1485 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1486 logFrameStats();
1487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488}
1489
Mathias Agopian87baae12012-07-31 12:38:26 -07001490void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001491{
Mathias Agopian841cde52012-03-01 15:44:37 -08001492 ATRACE_CALL();
1493
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001494 // here we keep a copy of the drawing state (that is the state that's
1495 // going to be overwritten by handleTransactionLocked()) outside of
1496 // mStateLock so that the side-effects of the State assignment
1497 // don't happen with mStateLock held (which can cause deadlocks).
1498 State drawingState(mDrawingState);
1499
Mathias Agopianca4d3602011-05-19 15:38:14 -07001500 Mutex::Autolock _l(mStateLock);
1501 const nsecs_t now = systemTime();
1502 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001503
Mathias Agopianca4d3602011-05-19 15:38:14 -07001504 // Here we're guaranteed that some transaction flags are set
1505 // so we can call handleTransactionLocked() unconditionally.
1506 // We call getTransactionFlags(), which will also clear the flags,
1507 // with mStateLock held to guarantee that mCurrentState won't change
1508 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001509
Mathias Agopiane57f2922012-08-09 16:29:12 -07001510 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001511 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001512
Mathias Agopianca4d3602011-05-19 15:38:14 -07001513 mLastTransactionTime = systemTime() - now;
1514 mDebugInTransaction = 0;
1515 invalidateHwcGeometry();
1516 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001517}
1518
Mathias Agopian87baae12012-07-31 12:38:26 -07001519void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001520{
1521 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522 const size_t count = currentLayers.size();
1523
Dan Stoza7dde5992015-05-22 09:51:44 -07001524 // Notify all layers of available frames
1525 for (size_t i = 0; i < count; ++i) {
1526 currentLayers[i]->notifyAvailableFrames();
1527 }
1528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001529 /*
1530 * Traversal of the children
1531 * (perform the transaction for each of them if needed)
1532 */
1533
Mathias Agopian3559b072012-08-15 13:46:03 -07001534 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001536 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001537 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1538 if (!trFlags) continue;
1539
1540 const uint32_t flags = layer->doTransaction(0);
1541 if (flags & Layer::eVisibleRegion)
1542 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001543 }
1544 }
1545
1546 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001547 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548 */
1549
Mathias Agopiane57f2922012-08-09 16:29:12 -07001550 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001551 // here we take advantage of Vector's copy-on-write semantics to
1552 // improve performance by skipping the transaction entirely when
1553 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001554 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1555 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001556 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001558 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001559 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001560
1561 // find the displays that were removed
1562 // (ie: in drawing state but not in current state)
1563 // also handle displays that changed
1564 // (ie: displays that are in both lists)
1565 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001566 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1567 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001568 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001569 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001570 // Call makeCurrent() on the primary display so we can
1571 // be sure that nothing associated with this display
1572 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001573 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001574 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001575 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1576 if (hw != NULL)
1577 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001578 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001579 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001580 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001581 } else {
1582 ALOGW("trying to remove the main display");
1583 }
1584 } else {
1585 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001586 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001587 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001588 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1589 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001590 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001591 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001592 // recreating the DisplayDevice, so we just remove it
1593 // from the drawing state, so that it get re-added
1594 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001595 sp<DisplayDevice> hw(getDisplayDevice(display));
1596 if (hw != NULL)
1597 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001598 mDisplays.removeItem(display);
1599 mDrawingState.displays.removeItemsAt(i);
1600 dc--; i--;
1601 // at this point we must loop to the next item
1602 continue;
1603 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001604
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001605 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001606 if (disp != NULL) {
1607 if (state.layerStack != draw[i].layerStack) {
1608 disp->setLayerStack(state.layerStack);
1609 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001610 if ((state.orientation != draw[i].orientation)
1611 || (state.viewport != draw[i].viewport)
1612 || (state.frame != draw[i].frame))
1613 {
1614 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001615 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001616 }
Michael Lentine47e45402014-07-18 15:34:25 -07001617 if (state.width != draw[i].width || state.height != draw[i].height) {
1618 disp->setDisplaySize(state.width, state.height);
1619 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001620 }
1621 }
1622 }
1623
1624 // find displays that were added
1625 // (ie: in current state but not in drawing state)
1626 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001627 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001628 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001629
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001630 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001631 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001632 sp<IGraphicBufferProducer> bqProducer;
1633 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001634 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1635 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001636
Dan Stoza9e56aa02015-11-02 13:00:03 -08001637 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001638 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001639 // Virtual displays without a surface are dormant:
1640 // they have external state (layer stack, projection,
1641 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001642 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001643
Dan Stoza8cf150a2016-08-02 10:27:31 -07001644 if (mUseHwcVirtualDisplays) {
1645 int width = 0;
1646 int status = state.surface->query(
1647 NATIVE_WINDOW_WIDTH, &width);
1648 ALOGE_IF(status != NO_ERROR,
1649 "Unable to query width (%d)", status);
1650 int height = 0;
1651 status = state.surface->query(
1652 NATIVE_WINDOW_HEIGHT, &height);
1653 ALOGE_IF(status != NO_ERROR,
1654 "Unable to query height (%d)", status);
1655 int intFormat = 0;
1656 status = state.surface->query(
1657 NATIVE_WINDOW_FORMAT, &intFormat);
1658 ALOGE_IF(status != NO_ERROR,
1659 "Unable to query format (%d)", status);
1660 auto format = static_cast<android_pixel_format_t>(
1661 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001662
Dan Stoza8cf150a2016-08-02 10:27:31 -07001663 mHwc->allocateVirtualDisplay(width, height, &format,
1664 &hwcId);
1665 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001666
Dan Stoza5cf424b2016-05-20 14:02:39 -07001667 // TODO: Plumb requested format back up to consumer
1668
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 sp<VirtualDisplaySurface> vds =
1670 new VirtualDisplaySurface(*mHwc,
1671 hwcId, state.surface, bqProducer,
1672 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001673
1674 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001675 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001676 }
1677 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001678 ALOGE_IF(state.surface!=NULL,
1679 "adding a supported display, but rendering "
1680 "surface is provided (%p), ignoring it",
1681 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1683 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1684 dispSurface = new FramebufferSurface(*mHwc,
1685 DisplayDevice::DISPLAY_EXTERNAL,
1686 bqConsumer);
1687 producer = bqProducer;
1688 } else {
1689 ALOGE("Attempted to add non-external non-virtual"
1690 " display");
1691 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001692 }
1693
1694 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001695 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001696 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 state.type, hwcId, state.isSecure, display,
1698 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001699 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001700 hw->setLayerStack(state.layerStack);
1701 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001702 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001703 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001704 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001706 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001707 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001708 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001709 }
1710 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001711 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001713
Mathias Agopian84300952012-11-21 16:02:13 -08001714 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1715 // The transform hint might have changed for some layers
1716 // (either because a display has changed, or because a layer
1717 // as changed).
1718 //
1719 // Walk through all the layers in currentLayers,
1720 // and update their transform hint.
1721 //
1722 // If a layer is visible only on a single display, then that
1723 // display is used to calculate the hint, otherwise we use the
1724 // default display.
1725 //
1726 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1727 // the hint is set before we acquire a buffer from the surface texture.
1728 //
1729 // NOTE: layer transactions have taken place already, so we use their
1730 // drawing state. However, SurfaceFlinger's own transaction has not
1731 // happened yet, so we must use the current state layer list
1732 // (soon to become the drawing state list).
1733 //
1734 sp<const DisplayDevice> disp;
1735 uint32_t currentlayerStack = 0;
1736 for (size_t i=0; i<count; i++) {
1737 // NOTE: we rely on the fact that layers are sorted by
1738 // layerStack first (so we don't have to traverse the list
1739 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001740 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001741 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001742 if (i==0 || currentlayerStack != layerStack) {
1743 currentlayerStack = layerStack;
1744 // figure out if this layerstack is mirrored
1745 // (more than one display) if so, pick the default display,
1746 // if not, pick the only display it's on.
1747 disp.clear();
1748 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1749 sp<const DisplayDevice> hw(mDisplays[dpy]);
1750 if (hw->getLayerStack() == currentlayerStack) {
1751 if (disp == NULL) {
1752 disp = hw;
1753 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001754 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001755 break;
1756 }
1757 }
1758 }
1759 }
Chet Haase91d25932013-04-11 15:24:55 -07001760 if (disp == NULL) {
1761 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1762 // redraw after transform hint changes. See bug 8508397.
1763
1764 // could be null when this layer is using a layerStack
1765 // that is not visible on any display. Also can occur at
1766 // screen off/on times.
1767 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001768 }
Chet Haase91d25932013-04-11 15:24:55 -07001769 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001770 }
1771 }
1772
1773
Mathias Agopian3559b072012-08-15 13:46:03 -07001774 /*
1775 * Perform our own transaction if needed
1776 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001777
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001778 const LayerVector& layers(mDrawingState.layersSortedByZ);
1779 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001780 // layers have been added
1781 mVisibleRegionsDirty = true;
1782 }
1783
1784 // some layers might have been removed, so
1785 // we need to update the regions they're exposing.
1786 if (mLayersRemoved) {
1787 mLayersRemoved = false;
1788 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001789 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001790 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001791 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001792 if (currentLayers.indexOf(layer) < 0) {
1793 // this layer is not visible anymore
1794 // TODO: we could traverse the tree from front to back and
1795 // compute the actual visible region
1796 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001797 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001798 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001799 Region(Rect(s.active.w, s.active.h)));
1800 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001801 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001803 }
1804
1805 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001806
1807 updateCursorAsync();
1808}
1809
1810void SurfaceFlinger::updateCursorAsync()
1811{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1813 auto& displayDevice = mDisplays[displayId];
1814 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001815 continue;
1816 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817
1818 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1819 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001820 }
1821 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001822}
1823
1824void SurfaceFlinger::commitTransaction()
1825{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001826 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001827 // Notify removed layers now that they can't be drawn from
1828 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001829 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1830 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001831 mLayersPendingRemoval[i]->onRemoved();
1832 }
1833 mLayersPendingRemoval.clear();
1834 }
1835
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001836 // If this transaction is part of a window animation then the next frame
1837 // we composite should be considered an animation as well.
1838 mAnimCompositionPending = mAnimTransactionPending;
1839
Mathias Agopian4fec8732012-06-29 14:12:52 -07001840 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001841 mTransactionPending = false;
1842 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001843 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001844}
1845
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001846void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001847 const LayerVector& currentLayers, uint32_t layerStack,
1848 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001849{
Mathias Agopian841cde52012-03-01 15:44:37 -08001850 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001851 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001852
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853 Region aboveOpaqueLayers;
1854 Region aboveCoveredLayers;
1855 Region dirty;
1856
Mathias Agopian87baae12012-07-31 12:38:26 -07001857 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001858
1859 size_t i = currentLayers.size();
1860 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001861 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862
1863 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001864 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001865
Jesse Hall01e29052013-02-19 16:13:35 -08001866 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001867 if (s.layerStack != layerStack)
1868 continue;
1869
Mathias Agopianab028732010-03-16 16:41:46 -07001870 /*
1871 * opaqueRegion: area of a surface that is fully opaque.
1872 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001873 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001874
1875 /*
1876 * visibleRegion: area of a surface that is visible on screen
1877 * and not fully transparent. This is essentially the layer's
1878 * footprint minus the opaque regions above it.
1879 * Areas covered by a translucent surface are considered visible.
1880 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001881 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001882
1883 /*
1884 * coveredRegion: area of a surface that is covered by all
1885 * visible regions above it (which includes the translucent areas).
1886 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001887 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001888
Jesse Halla8026d22012-09-25 13:25:04 -07001889 /*
1890 * transparentRegion: area of a surface that is hinted to be completely
1891 * transparent. This is only used to tell when the layer has no visible
1892 * non-transparent regions and can be removed from the layer list. It
1893 * does not affect the visibleRegion of this layer or any layers
1894 * beneath it. The hint may not be correct if apps don't respect the
1895 * SurfaceView restrictions (which, sadly, some don't).
1896 */
1897 Region transparentRegion;
1898
Mathias Agopianab028732010-03-16 16:41:46 -07001899
1900 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001901 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001902 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001903 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001904 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001905 if (!visibleRegion.isEmpty()) {
1906 // Remove the transparent area from the visible region
1907 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001908 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001909 if (tr.preserveRects()) {
1910 // transform the transparent region
1911 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001912 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001913 // transformation too complex, can't do the
1914 // transparent region optimization.
1915 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001916 }
Mathias Agopianab028732010-03-16 16:41:46 -07001917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918
Mathias Agopianab028732010-03-16 16:41:46 -07001919 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001920 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001922 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1923 // the opaque region is the layer's footprint
1924 opaqueRegion = visibleRegion;
1925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926 }
1927 }
1928
Mathias Agopianab028732010-03-16 16:41:46 -07001929 // Clip the covered region to the visible region
1930 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1931
1932 // Update aboveCoveredLayers for next (lower) layer
1933 aboveCoveredLayers.orSelf(visibleRegion);
1934
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001935 // subtract the opaque region covered by the layers above us
1936 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001937
1938 // compute this layer's dirty region
1939 if (layer->contentDirty) {
1940 // we need to invalidate the whole region
1941 dirty = visibleRegion;
1942 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001943 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001944 layer->contentDirty = false;
1945 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001946 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001947 * the exposed region consists of two components:
1948 * 1) what's VISIBLE now and was COVERED before
1949 * 2) what's EXPOSED now less what was EXPOSED before
1950 *
1951 * note that (1) is conservative, we start with the whole
1952 * visible region but only keep what used to be covered by
1953 * something -- which mean it may have been exposed.
1954 *
1955 * (2) handles areas that were not covered by anything but got
1956 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001957 */
Mathias Agopianab028732010-03-16 16:41:46 -07001958 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001959 const Region oldVisibleRegion = layer->visibleRegion;
1960 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001961 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1962 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001963 }
1964 dirty.subtractSelf(aboveOpaqueLayers);
1965
1966 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001967 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968
Mathias Agopianab028732010-03-16 16:41:46 -07001969 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001971
Jesse Halla8026d22012-09-25 13:25:04 -07001972 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973 layer->setVisibleRegion(visibleRegion);
1974 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001975 layer->setVisibleNonTransparentRegion(
1976 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977 }
1978
Mathias Agopian87baae12012-07-31 12:38:26 -07001979 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980}
1981
Mathias Agopian87baae12012-07-31 12:38:26 -07001982void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1983 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001984 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001985 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1986 if (hw->getLayerStack() == layerStack) {
1987 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001988 }
1989 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001990}
1991
Dan Stoza6b9454d2014-11-07 16:00:59 -08001992bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001993{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 ALOGV("handlePageFlip");
1995
Mathias Agopian4fec8732012-06-29 14:12:52 -07001996 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997
Mathias Agopian4fec8732012-06-29 14:12:52 -07001998 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001999 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002000 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002001
2002 // Store the set of layers that need updates. This set must not change as
2003 // buffers are being latched, as this could result in a deadlock.
2004 // Example: Two producers share the same command stream and:
2005 // 1.) Layer 0 is latched
2006 // 2.) Layer 0 gets a new frame
2007 // 2.) Layer 1 gets a new frame
2008 // 3.) Layer 1 is latched.
2009 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2010 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002011 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002012 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002013 if (layer->hasQueuedFrame()) {
2014 frameQueued = true;
2015 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002017 } else {
2018 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002019 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002020 } else {
2021 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002022 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002023 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002025 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002026 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002027 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002028 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002030
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002031 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002032
2033 // If we will need to wake up at some time in the future to deal with a
2034 // queued frame that shouldn't be displayed during this vsync period, wake
2035 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002037 signalLayerUpdate();
2038 }
2039
2040 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042}
2043
Mathias Agopianad456f92011-01-13 17:53:01 -08002044void SurfaceFlinger::invalidateHwcGeometry()
2045{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002047}
2048
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002049
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002051 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052{
Dan Stoza71433162014-02-04 16:22:36 -08002053 // We only need to actually compose the display if:
2054 // 1) It is being handled by hardware composer, which may need this to
2055 // keep its virtual display state machine in sync, or
2056 // 2) There is work to be done (the dirty region isn't empty)
2057 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2058 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002060 return;
2061 }
2062
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 ALOGV("doDisplayComposition");
2064
Mathias Agopian87baae12012-07-31 12:38:26 -07002065 Region dirtyRegion(inDirtyRegion);
2066
Mathias Agopianb8a55602009-06-26 19:06:36 -07002067 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002068 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069
Mathias Agopian42977342012-08-05 00:40:46 -07002070 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002071 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002072 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2073 // takes a rectangle, we must make sure to update that whole
2074 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002075 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002076 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002077 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002078 // We need to redraw the rectangle that will be updated
2079 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002080 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002081 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002082 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002083 } else {
2084 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002085 dirtyRegion.set(hw->bounds());
2086 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087 }
2088 }
2089
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002090 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002092 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002093 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002094
2095 // swap buffers (presentation)
2096 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002097}
2098
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099bool SurfaceFlinger::doComposeSurfaces(
2100 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002101{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002103
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002105
2106 mat4 oldColorMatrix;
2107 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2108 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2109 if (applyColorMatrix) {
2110 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2111 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2112 }
2113
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2115 if (hasClientComposition) {
2116 ALOGV("hasClientComposition");
2117
2118 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002119 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002121 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2122 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2123 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2124 }
2125 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002126 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002127
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002128 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2130 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002131 // when using overlays, we assume a fully transparent framebuffer
2132 // NOTE: we could reduce how much we need to clear, for instance
2133 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002134 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002135 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002137 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002138 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002139 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002140
2141 // we remove the scissor part
2142 // we're left with the letterbox region
2143 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002144 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002145
2146 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002148
2149 // but limit it to the dirty region
2150 region.andSelf(dirty);
2151
Mathias Agopianb9494d52012-04-18 02:28:45 -07002152 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002153 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002154 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002156 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002157 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002158
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002160 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002161 // scissor on the main display. It should never be needed
2162 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 const Rect& bounds(displayDevice->getBounds());
2164 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002165 if (scissor != bounds) {
2166 // scissor doesn't match the screen's dimensions, so we
2167 // need to clear everything outside of it and enable
2168 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002169
Mathias Agopianf45c5102012-10-24 16:29:17 -07002170 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 const uint32_t height = displayDevice->getHeight();
2172 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002173 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002174 }
2175 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002176 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002177
Mathias Agopian85d751c2012-08-29 16:59:24 -07002178 /*
2179 * and then, render the layers targeted at the framebuffer
2180 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002181
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 ALOGV("Rendering client layers");
2183 const Transform& displayTransform = displayDevice->getTransform();
2184 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002185 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 bool firstLayer = true;
2187 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2188 const Region clip(dirty.intersect(
2189 displayTransform.transform(layer->visibleRegion)));
2190 ALOGV("Layer: %s", layer->getName().string());
2191 ALOGV(" Composition type: %s",
2192 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002193 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 switch (layer->getCompositionType(hwcId)) {
2195 case HWC2::Composition::Cursor:
2196 case HWC2::Composition::Device:
2197 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002198 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2200 layer->isOpaque(state) && (state.alpha == 1.0f)
2201 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002202 // never clear the very first layer since we're
2203 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002206 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002207 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 case HWC2::Composition::Client: {
2209 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002210 break;
2211 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002213 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 } else {
2216 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002217 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002218 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002219 }
2220 } else {
2221 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002223 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002224 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002225 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002227 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002228 }
2229 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002230
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002231 if (applyColorMatrix) {
2232 getRenderEngine().setupColorTransform(oldColorMatrix);
2233 }
2234
Mathias Agopianf45c5102012-10-24 16:29:17 -07002235 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002237 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238}
2239
Mathias Agopian3f844832013-08-07 21:24:32 -07002240void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002241 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002242 RenderEngine& engine(getRenderEngine());
2243 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244}
2245
Dan Stoza7d89d062015-04-30 13:29:25 -07002246status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002247 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002248 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002249 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002250{
Dan Stoza7d89d062015-04-30 13:29:25 -07002251 // add this layer to the current state list
2252 {
2253 Mutex::Autolock _l(mStateLock);
2254 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2255 return NO_MEMORY;
2256 }
2257 mCurrentState.layersSortedByZ.add(lbc);
2258 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2259 }
2260
Mathias Agopian96f08192010-06-02 23:28:45 -07002261 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002262 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002263
Dan Stoza7d89d062015-04-30 13:29:25 -07002264 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002265}
2266
Dan Stoza22851c32016-08-09 13:21:03 -07002267status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002269 sp<Layer> layer = weakLayer.promote();
2270 if (layer == nullptr) {
2271 // The layer has already been removed, carry on
2272 return NO_ERROR;
2273 }
2274
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002275 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2276 if (index >= 0) {
2277 mLayersPendingRemoval.push(layer);
2278 mLayersRemoved = true;
2279 setTransactionFlags(eTransactionNeeded);
2280 return NO_ERROR;
2281 }
2282 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283}
2284
Dan Stozac7014012014-02-14 15:03:43 -08002285uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002286 return android_atomic_release_load(&mTransactionFlags);
2287}
2288
Mathias Agopian3f844832013-08-07 21:24:32 -07002289uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2291}
2292
Mathias Agopian3f844832013-08-07 21:24:32 -07002293uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2295 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002296 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297 }
2298 return old;
2299}
2300
Mathias Agopian8b33f032012-07-24 20:43:54 -07002301void SurfaceFlinger::setTransactionState(
2302 const Vector<ComposerState>& state,
2303 const Vector<DisplayState>& displays,
2304 uint32_t flags)
2305{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002306 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002307 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002308 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002309
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002310 if (flags & eAnimation) {
2311 // For window updates that are part of an animation we must wait for
2312 // previous animation "frames" to be handled.
2313 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002314 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002315 if (CC_UNLIKELY(err != NO_ERROR)) {
2316 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002317 // caller after a few seconds.
2318 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2319 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002320 mAnimTransactionPending = false;
2321 break;
2322 }
2323 }
2324 }
2325
Mathias Agopiane57f2922012-08-09 16:29:12 -07002326 size_t count = displays.size();
2327 for (size_t i=0 ; i<count ; i++) {
2328 const DisplayState& s(displays[i]);
2329 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002330 }
2331
Mathias Agopiane57f2922012-08-09 16:29:12 -07002332 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002333 for (size_t i=0 ; i<count ; i++) {
2334 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002335 // Here we need to check that the interface we're given is indeed
2336 // one of our own. A malicious client could give us a NULL
2337 // IInterface, or one of its own or even one of our own but a
2338 // different type. All these situations would cause us to crash.
2339 //
2340 // NOTE: it would be better to use RTTI as we could directly check
2341 // that we have a Client*. however, RTTI is disabled in Android.
2342 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002343 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002344 if (binder != NULL) {
2345 String16 desc(binder->getInterfaceDescriptor());
2346 if (desc == ISurfaceComposerClient::descriptor) {
2347 sp<Client> client( static_cast<Client *>(s.client.get()) );
2348 transactionFlags |= setClientStateLocked(client, s.state);
2349 }
2350 }
2351 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002352 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002353
Robert Carr2a7dbb42016-05-24 11:41:28 -07002354 // If a synchronous transaction is explicitly requested without any changes,
2355 // force a transaction anyway. This can be used as a flush mechanism for
2356 // previous async transactions.
2357 if (transactionFlags == 0 && (flags & eSynchronous)) {
2358 transactionFlags = eTransactionNeeded;
2359 }
2360
Mathias Agopian386aa982011-11-07 21:58:03 -08002361 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002362 if (mInterceptor.isEnabled()) {
2363 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2364 }
Irvel468051e2016-06-13 16:44:44 -07002365
Mathias Agopian386aa982011-11-07 21:58:03 -08002366 // this triggers the transaction
2367 setTransactionFlags(transactionFlags);
2368
2369 // if this is a synchronous transaction, wait for it to take effect
2370 // before returning.
2371 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002372 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002373 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002374 if (flags & eAnimation) {
2375 mAnimTransactionPending = true;
2376 }
2377 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002378 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2379 if (CC_UNLIKELY(err != NO_ERROR)) {
2380 // just in case something goes wrong in SF, return to the
2381 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002382 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2383 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002384 break;
2385 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 }
2388}
2389
Mathias Agopiane57f2922012-08-09 16:29:12 -07002390uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2391{
Jesse Hall9a143922012-10-04 16:29:19 -07002392 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2393 if (dpyIdx < 0)
2394 return 0;
2395
Mathias Agopiane57f2922012-08-09 16:29:12 -07002396 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002397 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002398 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002399 const uint32_t what = s.what;
2400 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002401 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002402 disp.surface = s.surface;
2403 flags |= eDisplayTransactionNeeded;
2404 }
2405 }
2406 if (what & DisplayState::eLayerStackChanged) {
2407 if (disp.layerStack != s.layerStack) {
2408 disp.layerStack = s.layerStack;
2409 flags |= eDisplayTransactionNeeded;
2410 }
2411 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002412 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002413 if (disp.orientation != s.orientation) {
2414 disp.orientation = s.orientation;
2415 flags |= eDisplayTransactionNeeded;
2416 }
2417 if (disp.frame != s.frame) {
2418 disp.frame = s.frame;
2419 flags |= eDisplayTransactionNeeded;
2420 }
2421 if (disp.viewport != s.viewport) {
2422 disp.viewport = s.viewport;
2423 flags |= eDisplayTransactionNeeded;
2424 }
2425 }
Michael Lentine47e45402014-07-18 15:34:25 -07002426 if (what & DisplayState::eDisplaySizeChanged) {
2427 if (disp.width != s.width) {
2428 disp.width = s.width;
2429 flags |= eDisplayTransactionNeeded;
2430 }
2431 if (disp.height != s.height) {
2432 disp.height = s.height;
2433 flags |= eDisplayTransactionNeeded;
2434 }
2435 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002436 }
2437 return flags;
2438}
2439
2440uint32_t SurfaceFlinger::setClientStateLocked(
2441 const sp<Client>& client,
2442 const layer_state_t& s)
2443{
2444 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002445 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002446 if (layer != 0) {
2447 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002448 bool geometryAppliesWithResize =
2449 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002450 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002451 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002452 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002453 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 }
2455 if (what & layer_state_t::eLayerChanged) {
2456 // NOTE: index needs to be calculated before we update the state
2457 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002458 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002459 mCurrentState.layersSortedByZ.removeAt(idx);
2460 mCurrentState.layersSortedByZ.add(layer);
2461 // we need traversal (state changed)
2462 // AND transaction (list changed)
2463 flags |= eTransactionNeeded|eTraversalNeeded;
2464 }
2465 }
2466 if (what & layer_state_t::eSizeChanged) {
2467 if (layer->setSize(s.w, s.h)) {
2468 flags |= eTraversalNeeded;
2469 }
2470 }
2471 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002473 flags |= eTraversalNeeded;
2474 }
2475 if (what & layer_state_t::eMatrixChanged) {
2476 if (layer->setMatrix(s.matrix))
2477 flags |= eTraversalNeeded;
2478 }
2479 if (what & layer_state_t::eTransparentRegionChanged) {
2480 if (layer->setTransparentRegionHint(s.transparentRegion))
2481 flags |= eTraversalNeeded;
2482 }
Dan Stoza23116082015-06-18 14:58:39 -07002483 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002484 if (layer->setFlags(s.flags, s.mask))
2485 flags |= eTraversalNeeded;
2486 }
2487 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002488 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002489 flags |= eTraversalNeeded;
2490 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002491 if (what & layer_state_t::eFinalCropChanged) {
2492 if (layer->setFinalCrop(s.finalCrop))
2493 flags |= eTraversalNeeded;
2494 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002495 if (what & layer_state_t::eLayerStackChanged) {
2496 // NOTE: index needs to be calculated before we update the state
2497 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002498 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 mCurrentState.layersSortedByZ.removeAt(idx);
2500 mCurrentState.layersSortedByZ.add(layer);
2501 // we need traversal (state changed)
2502 // AND transaction (list changed)
2503 flags |= eTransactionNeeded|eTraversalNeeded;
2504 }
2505 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002506 if (what & layer_state_t::eDeferTransaction) {
2507 layer->deferTransactionUntil(s.handle, s.frameNumber);
2508 // We don't trigger a traversal here because if no other state is
2509 // changed, we don't want this to cause any more work
2510 }
Robert Carrc3574f72016-03-24 12:19:32 -07002511 if (what & layer_state_t::eOverrideScalingModeChanged) {
2512 layer->setOverrideScalingMode(s.overrideScalingMode);
2513 // We don't trigger a traversal here because if no other state is
2514 // changed, we don't want this to cause any more work
2515 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002516 }
2517 return flags;
2518}
2519
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002520status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002521 const String8& name,
2522 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002523 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2524 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002526 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002527 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002528 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002529 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002530 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002531
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002532 status_t result = NO_ERROR;
2533
2534 sp<Layer> layer;
2535
Mathias Agopian3165cc22012-08-08 19:42:09 -07002536 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2537 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002538 result = createNormalLayer(client,
2539 name, w, h, flags, format,
2540 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002542 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002543 result = createDimLayer(client,
2544 name, w, h, flags,
2545 handle, gbp, &layer);
2546 break;
2547 default:
2548 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 break;
2550 }
2551
Dan Stoza7d89d062015-04-30 13:29:25 -07002552 if (result != NO_ERROR) {
2553 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002555
2556 result = addClientLayer(client, *handle, *gbp, layer);
2557 if (result != NO_ERROR) {
2558 return result;
2559 }
Irvelffc9efc2016-07-27 15:16:37 -07002560 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002561
2562 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002563 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002566status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2567 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2568 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569{
2570 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002571 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 case PIXEL_FORMAT_TRANSPARENT:
2573 case PIXEL_FORMAT_TRANSLUCENT:
2574 format = PIXEL_FORMAT_RGBA_8888;
2575 break;
2576 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002577 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 break;
2579 }
2580
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002581 *outLayer = new Layer(this, client, name, w, h, flags);
2582 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2583 if (err == NO_ERROR) {
2584 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002585 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002587
2588 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2589 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002592status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2593 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002596 *outLayer = new LayerDim(this, client, name, w, h, flags);
2597 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002598 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002599 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002600}
2601
Mathias Agopianac9fa422013-02-11 16:40:36 -08002602status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603{
Mathias Agopian67106042013-03-14 19:18:13 -07002604 // called by the window manager when it wants to remove a Layer
2605 status_t err = NO_ERROR;
2606 sp<Layer> l(client->getLayerUser(handle));
2607 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002608 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002609 err = removeLayer(l);
2610 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2611 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002612 }
2613 return err;
2614}
2615
Mathias Agopian13127d82013-03-05 17:47:11 -08002616status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002617{
Mathias Agopian67106042013-03-14 19:18:13 -07002618 // called by ~LayerCleaner() when all references to the IBinder (handle)
2619 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002620 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621}
2622
Mathias Agopianb60314a2012-04-10 22:09:54 -07002623// ---------------------------------------------------------------------------
2624
Andy McFadden13a082e2012-08-24 10:16:42 -07002625void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002626 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002627 Vector<ComposerState> state;
2628 Vector<DisplayState> displays;
2629 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002630 d.what = DisplayState::eDisplayProjectionChanged |
2631 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002632 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002633 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002634 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002635 d.frame.makeInvalid();
2636 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002637 d.width = 0;
2638 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002639 displays.add(d);
2640 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002641 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002642
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2644 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002645 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002646}
2647
2648void SurfaceFlinger::initializeDisplays() {
2649 class MessageScreenInitialized : public MessageBase {
2650 SurfaceFlinger* flinger;
2651 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002652 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002653 virtual bool handler() {
2654 flinger->onInitializeDisplays();
2655 return true;
2656 }
2657 };
2658 sp<MessageBase> msg = new MessageScreenInitialized(this);
2659 postMessageAsync(msg); // we may be called from main thread, use async message
2660}
2661
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002662void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2663 int mode) {
2664 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2665 this);
2666 int32_t type = hw->getDisplayType();
2667 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002668
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002669 if (mode == currentMode) {
2670 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002671 return;
2672 }
2673
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002674 hw->setPowerMode(mode);
2675 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2676 ALOGW("Trying to set power mode for virtual display");
2677 return;
2678 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002679
Irvelffc9efc2016-07-27 15:16:37 -07002680 if (mInterceptor.isEnabled()) {
2681 Mutex::Autolock _l(mStateLock);
2682 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2683 if (idx < 0) {
2684 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2685 return;
2686 }
2687 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2688 }
2689
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002690 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002691 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002692 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002693 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2694 // FIXME: eventthread only knows about the main display right now
2695 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002696 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002697 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002699 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002700 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002701 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002702
2703 struct sched_param param = {0};
2704 param.sched_priority = 1;
2705 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2706 ALOGW("Couldn't set SCHED_FIFO on display on");
2707 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002708 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002709 // Turn off the display
2710 struct sched_param param = {0};
2711 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2712 ALOGW("Couldn't set SCHED_OTHER on display off");
2713 }
2714
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002715 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002716 disableHardwareVsync(true); // also cancels any in-progress resync
2717
Mathias Agopiancde87a32012-09-13 14:09:01 -07002718 // FIXME: eventthread only knows about the main display right now
2719 mEventThread->onScreenReleased();
2720 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002721
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002722 getHwComposer().setPowerMode(type, mode);
2723 mVisibleRegionsDirty = true;
2724 // from this point on, SF will stop drawing on this display
2725 } else {
2726 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002727 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002728}
2729
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002730void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2731 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002732 SurfaceFlinger& mFlinger;
2733 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002734 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002735 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002736 MessageSetPowerMode(SurfaceFlinger& flinger,
2737 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2738 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002739 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002740 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002741 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002742 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002743 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002744 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002745 ALOGW("Attempt to set power mode = %d for virtual display",
2746 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002747 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002748 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002749 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002750 return true;
2751 }
2752 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002753 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002754 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002755}
2756
2757// ---------------------------------------------------------------------------
2758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2760{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002762
Mathias Agopianbd115332013-04-18 16:41:04 -07002763 IPCThreadState* ipc = IPCThreadState::self();
2764 const int pid = ipc->getCallingPid();
2765 const int uid = ipc->getCallingUid();
2766 if ((uid != AID_SHELL) &&
2767 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002768 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002769 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002771 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002772 // (this would indicate SF is stuck, but we want to be able to
2773 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002774 status_t err = mStateLock.timedLock(s2ns(1));
2775 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002776 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002777 result.appendFormat(
2778 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2779 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002780 }
2781
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002782 bool dumpAll = true;
2783 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002784 size_t numArgs = args.size();
2785 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002786 if ((index < numArgs) &&
2787 (args[index] == String16("--list"))) {
2788 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002789 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002790 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002791 }
2792
2793 if ((index < numArgs) &&
2794 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002795 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002796 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002797 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002798 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002799
2800 if ((index < numArgs) &&
2801 (args[index] == String16("--latency-clear"))) {
2802 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002803 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002804 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002805 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002806
2807 if ((index < numArgs) &&
2808 (args[index] == String16("--dispsync"))) {
2809 index++;
2810 mPrimaryDispSync.dump(result);
2811 dumpAll = false;
2812 }
Dan Stozab90cf072015-03-05 11:05:59 -08002813
2814 if ((index < numArgs) &&
2815 (args[index] == String16("--static-screen"))) {
2816 index++;
2817 dumpStaticScreenStats(result);
2818 dumpAll = false;
2819 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002820
2821 if ((index < numArgs) &&
2822 (args[index] == String16("--fences"))) {
2823 index++;
2824 mFenceTracker.dump(&result);
2825 dumpAll = false;
2826 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002828
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002829 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002830 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002831 }
2832
Mathias Agopian9795c422009-08-26 16:36:26 -07002833 if (locked) {
2834 mStateLock.unlock();
2835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 }
2837 write(fd, result.string(), result.size());
2838 return NO_ERROR;
2839}
2840
Dan Stozac7014012014-02-14 15:03:43 -08002841void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2842 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002843{
2844 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2845 const size_t count = currentLayers.size();
2846 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002847 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002848 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002849 }
2850}
2851
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002852void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002853 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002854{
2855 String8 name;
2856 if (index < args.size()) {
2857 name = String8(args[index]);
2858 index++;
2859 }
2860
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2862 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002863 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002864
2865 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002866 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002867 } else {
2868 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2869 const size_t count = currentLayers.size();
2870 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002871 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002872 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002873 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002874 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002875 }
2876 }
2877}
2878
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002879void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002880 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002881{
2882 String8 name;
2883 if (index < args.size()) {
2884 name = String8(args[index]);
2885 index++;
2886 }
2887
2888 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2889 const size_t count = currentLayers.size();
2890 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002891 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002892 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002893 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002894 }
2895 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002896
Svetoslavd85084b2014-03-20 10:28:31 -07002897 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002898}
2899
Jamie Gennis6547ff42013-07-16 20:12:42 -07002900// This should only be called from the main thread. Otherwise it would need
2901// the lock and should use mCurrentState rather than mDrawingState.
2902void SurfaceFlinger::logFrameStats() {
2903 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2904 const size_t count = drawingLayers.size();
2905 for (size_t i=0 ; i<count ; i++) {
2906 const sp<Layer>& layer(drawingLayers[i]);
2907 layer->logFrameStats();
2908 }
2909
2910 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2911}
2912
Andy McFadden4803b742012-09-24 19:07:20 -07002913/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2914{
2915 static const char* config =
2916 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002917#ifdef HAS_CONTEXT_PRIORITY
2918 " HAS_CONTEXT_PRIORITY"
2919#endif
2920#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2921 " NEVER_DEFAULT_TO_ASYNC_MODE"
2922#endif
2923#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2924 " TARGET_DISABLE_TRIPLE_BUFFERING"
2925#endif
2926 "]";
2927 result.append(config);
2928}
2929
Dan Stozab90cf072015-03-05 11:05:59 -08002930void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2931{
2932 result.appendFormat("Static screen stats:\n");
2933 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2934 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2935 float percent = 100.0f *
2936 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2937 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2938 b + 1, bucketTimeSec, percent);
2939 }
2940 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2941 float percent = 100.0f *
2942 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2943 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2944 NUM_BUCKETS - 1, bucketTimeSec, percent);
2945}
2946
Dan Stozae77c7662016-05-13 11:37:28 -07002947void SurfaceFlinger::recordBufferingStats(const char* layerName,
2948 std::vector<OccupancyTracker::Segment>&& history) {
2949 Mutex::Autolock lock(mBufferingStatsMutex);
2950 auto& stats = mBufferingStats[layerName];
2951 for (const auto& segment : history) {
2952 if (!segment.usedThirdBuffer) {
2953 stats.twoBufferTime += segment.totalTime;
2954 }
2955 if (segment.occupancyAverage < 1.0f) {
2956 stats.doubleBufferedTime += segment.totalTime;
2957 } else if (segment.occupancyAverage < 2.0f) {
2958 stats.tripleBufferedTime += segment.totalTime;
2959 }
2960 ++stats.numSegments;
2961 stats.totalTime += segment.totalTime;
2962 }
2963}
2964
2965void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2966 result.append("Buffering stats:\n");
2967 result.append(" [Layer name] <Active time> <Two buffer> "
2968 "<Double buffered> <Triple buffered>\n");
2969 Mutex::Autolock lock(mBufferingStatsMutex);
2970 typedef std::tuple<std::string, float, float, float> BufferTuple;
2971 std::map<float, BufferTuple, std::greater<float>> sorted;
2972 for (const auto& statsPair : mBufferingStats) {
2973 const char* name = statsPair.first.c_str();
2974 const BufferingStats& stats = statsPair.second;
2975 if (stats.numSegments == 0) {
2976 continue;
2977 }
2978 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2979 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2980 stats.totalTime;
2981 float doubleBufferRatio = static_cast<float>(
2982 stats.doubleBufferedTime) / stats.totalTime;
2983 float tripleBufferRatio = static_cast<float>(
2984 stats.tripleBufferedTime) / stats.totalTime;
2985 sorted.insert({activeTime, {name, twoBufferRatio,
2986 doubleBufferRatio, tripleBufferRatio}});
2987 }
2988 for (const auto& sortedPair : sorted) {
2989 float activeTime = sortedPair.first;
2990 const BufferTuple& values = sortedPair.second;
2991 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2992 std::get<0>(values).c_str(), activeTime,
2993 std::get<1>(values), std::get<2>(values),
2994 std::get<3>(values));
2995 }
2996 result.append("\n");
2997}
2998
2999
Mathias Agopian74d211a2013-04-22 16:55:35 +02003000void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3001 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003002{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003003 bool colorize = false;
3004 if (index < args.size()
3005 && (args[index] == String16("--color"))) {
3006 colorize = true;
3007 index++;
3008 }
3009
3010 Colorizer colorizer(colorize);
3011
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003012 // figure out if we're stuck somewhere
3013 const nsecs_t now = systemTime();
3014 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3015 const nsecs_t inTransaction(mDebugInTransaction);
3016 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3017 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3018
3019 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003020 * Dump library configuration.
3021 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003022
3023 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003024 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003025 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003026 appendSfConfigString(result);
3027 appendUiConfigString(result);
3028 appendGuiConfigString(result);
3029 result.append("\n");
3030
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003031 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003032 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003033 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003034 result.append(SyncFeatures::getInstance().toString());
3035 result.append("\n");
3036
Dan Stoza9e56aa02015-11-02 13:00:03 -08003037 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3038
Andy McFadden41d67d72014-04-25 16:58:34 -07003039 colorizer.bold(result);
3040 result.append("DispSync configuration: ");
3041 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003042 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3043 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3045 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003046 result.append("\n");
3047
Dan Stozab90cf072015-03-05 11:05:59 -08003048 // Dump static screen stats
3049 result.append("\n");
3050 dumpStaticScreenStats(result);
3051 result.append("\n");
3052
Dan Stozae77c7662016-05-13 11:37:28 -07003053 dumpBufferingStats(result);
3054
Andy McFadden4803b742012-09-24 19:07:20 -07003055 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003056 * Dump the visible layer list
3057 */
3058 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3059 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003060 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003061 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003062 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003063 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003064 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003065 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003066 }
3067
3068 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003069 * Dump Display state
3070 */
3071
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003072 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003073 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003074 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003075 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3076 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003077 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003078 }
3079
3080 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003081 * Dump SurfaceFlinger global state
3082 */
3083
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003084 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003085 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003086 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003087
Mathias Agopian888c8222012-08-04 21:10:38 -07003088 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003089 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003090
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 colorizer.bold(result);
3092 result.appendFormat("EGL implementation : %s\n",
3093 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3094 colorizer.reset(result);
3095 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003096 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003097
Mathias Agopian875d8e12013-06-07 15:35:48 -07003098 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003099
Mathias Agopian42977342012-08-05 00:40:46 -07003100 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003101 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3102 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003104 " last eglSwapBuffers() time: %f us\n"
3105 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003106 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003107 " refresh-rate : %f fps\n"
3108 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003109 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003110 " gpu_to_cpu_unsupported : %d\n"
3111 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003112 mLastSwapBufferTime/1000.0,
3113 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003114 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003115 1e9 / activeConfig->getVsyncPeriod(),
3116 activeConfig->getDpiX(),
3117 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003118 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003119
Mathias Agopian74d211a2013-04-22 16:55:35 +02003120 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003121 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003122
Mathias Agopian74d211a2013-04-22 16:55:35 +02003123 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003124 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125
3126 /*
3127 * VSYNC state
3128 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003129 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003130 result.append("\n");
3131
3132 /*
3133 * HWC layer minidump
3134 */
3135 for (size_t d = 0; d < mDisplays.size(); d++) {
3136 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3137 int32_t hwcId = displayDevice->getHwcDisplayId();
3138 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3139 continue;
3140 }
3141
3142 result.appendFormat("Display %d HWC layers:\n", hwcId);
3143 Layer::miniDumpHeader(result);
3144 for (size_t l = 0; l < count; l++) {
3145 const sp<Layer>& layer(currentLayers[l]);
3146 layer->miniDump(result, hwcId);
3147 }
3148 result.append("\n");
3149 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150
3151 /*
3152 * Dump HWComposer state
3153 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003154 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003155 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003156 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003157 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003158 result.appendFormat(" h/w composer %s\n",
3159 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003160 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003161
3162 /*
3163 * Dump gralloc state
3164 */
3165 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3166 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003167}
3168
Mathias Agopian13127d82013-03-05 17:47:11 -08003169const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003170SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003171 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003172 wp<IBinder> dpy;
3173 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3174 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3175 dpy = mDisplays.keyAt(i);
3176 break;
3177 }
3178 }
3179 if (dpy == NULL) {
3180 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3181 // Just use the primary display so we have something to return
3182 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3183 }
3184 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003185}
3186
Keun young Park63f165f2012-08-31 10:53:36 -07003187bool SurfaceFlinger::startDdmConnection()
3188{
3189 void* libddmconnection_dso =
3190 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3191 if (!libddmconnection_dso) {
3192 return false;
3193 }
3194 void (*DdmConnection_start)(const char* name);
3195 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003196 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003197 if (!DdmConnection_start) {
3198 dlclose(libddmconnection_dso);
3199 return false;
3200 }
3201 (*DdmConnection_start)(getServiceName());
3202 return true;
3203}
3204
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003205status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 switch (code) {
3207 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003208 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003209 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003211 case CLEAR_ANIMATION_FRAME_STATS:
3212 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003214 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215 {
3216 // codes that require permission check
3217 IPCThreadState* ipc = IPCThreadState::self();
3218 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003219 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003220 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003221 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003222 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003223 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003225 break;
3226 }
3227 case CAPTURE_SCREEN:
3228 {
3229 // codes that require permission check
3230 IPCThreadState* ipc = IPCThreadState::self();
3231 const int pid = ipc->getCallingPid();
3232 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003233 if ((uid != AID_GRAPHICS) &&
3234 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003235 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003236 return PERMISSION_DENIED;
3237 }
3238 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
3240 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003241 return OK;
3242}
3243
3244status_t SurfaceFlinger::onTransact(
3245 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3246{
3247 status_t credentialCheck = CheckTransactCodeCredentials(code);
3248 if (credentialCheck != OK) {
3249 return credentialCheck;
3250 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003251
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3253 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003254 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003255 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003256 IPCThreadState* ipc = IPCThreadState::self();
3257 const int pid = ipc->getCallingPid();
3258 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003259 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003260 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261 return PERMISSION_DENIED;
3262 }
3263 int n;
3264 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003265 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003266 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 return NO_ERROR;
3268 case 1002: // SHOW_UPDATES
3269 n = data.readInt32();
3270 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003271 invalidateHwcGeometry();
3272 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003275 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003276 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003278 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 setTransactionFlags(
3280 eTransactionNeeded|
3281 eDisplayTransactionNeeded|
3282 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003283 return NO_ERROR;
3284 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003285 case 1006:{ // send empty update
3286 signalRefresh();
3287 return NO_ERROR;
3288 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003289 case 1008: // toggle use of hw composer
3290 n = data.readInt32();
3291 mDebugDisableHWC = n ? 1 : 0;
3292 invalidateHwcGeometry();
3293 repaintEverything();
3294 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003295 case 1009: // toggle use of transform hint
3296 n = data.readInt32();
3297 mDebugDisableTransformHint = n ? 1 : 0;
3298 invalidateHwcGeometry();
3299 repaintEverything();
3300 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003302 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303 reply->writeInt32(0);
3304 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003305 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003306 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003307 return NO_ERROR;
3308 case 1013: {
3309 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003310 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3311 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003312 return NO_ERROR;
3313 }
3314 case 1014: {
3315 // daltonize
3316 n = data.readInt32();
3317 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003318 case 1:
3319 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3320 break;
3321 case 2:
3322 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3323 break;
3324 case 3:
3325 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3326 break;
3327 default:
3328 mDaltonizer.setType(ColorBlindnessType::None);
3329 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003330 }
3331 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003332 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003333 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003334 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003335 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003336 invalidateHwcGeometry();
3337 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003338 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003340 case 1015: {
3341 // apply a color matrix
3342 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003343 if (n) {
3344 // color matrix is sent as mat3 matrix followed by vec3
3345 // offset, then packed into a mat4 where the last row is
3346 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003347 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003348 for (size_t j = 0; j < 4; j++) {
3349 mColorMatrix[i][j] = data.readFloat();
3350 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003351 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003352 } else {
3353 mColorMatrix = mat4();
3354 }
3355 invalidateHwcGeometry();
3356 repaintEverything();
3357 return NO_ERROR;
3358 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003359 // This is an experimental interface
3360 // Needs to be shifted to proper binder interface when we productize
3361 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003362 n = data.readInt32();
3363 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003364 return NO_ERROR;
3365 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003366 case 1017: {
3367 n = data.readInt32();
3368 mForceFullDamage = static_cast<bool>(n);
3369 return NO_ERROR;
3370 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003371 case 1018: { // Modify Choreographer's phase offset
3372 n = data.readInt32();
3373 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3374 return NO_ERROR;
3375 }
3376 case 1019: { // Modify SurfaceFlinger's phase offset
3377 n = data.readInt32();
3378 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3379 return NO_ERROR;
3380 }
Irvel468051e2016-06-13 16:44:44 -07003381 case 1020: { // Layer updates interceptor
3382 n = data.readInt32();
3383 if (n) {
3384 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003385 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003386 }
3387 else{
3388 ALOGV("Interceptor disabled");
3389 mInterceptor.disable();
3390 }
3391 return NO_ERROR;
3392 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003393 case 1021: { // Disable HWC virtual displays
3394 n = data.readInt32();
3395 mUseHwcVirtualDisplays = !n;
3396 return NO_ERROR;
3397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003398 }
3399 }
3400 return err;
3401}
3402
Mathias Agopian53331da2011-08-22 21:44:41 -07003403void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003404 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003405 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003406}
3407
Mathias Agopian59119e62010-10-11 12:37:43 -07003408// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003409// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003410// ---------------------------------------------------------------------------
3411
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003412/* The code below is here to handle b/8734824
3413 *
3414 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003415 * from the surfaceflinger thread to the calling binder thread, where they
3416 * are executed. This allows the calling thread in the calling process to be
3417 * reused and not depend on having "enough" binder threads to handle the
3418 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003419 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003420class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003421 /* Parts of GraphicProducerWrapper are run on two different threads,
3422 * communicating by sending messages via Looper but also by shared member
3423 * data. Coherence maintenance is subtle and in places implicit (ugh).
3424 *
3425 * Don't rely on Looper's sendMessage/handleMessage providing
3426 * release/acquire semantics for any data not actually in the Message.
3427 * Data going from surfaceflinger to binder threads needs to be
3428 * synchronized explicitly.
3429 *
3430 * Barrier open/wait do provide release/acquire semantics. This provides
3431 * implicit synchronization for data coming back from binder to
3432 * surfaceflinger threads.
3433 */
3434
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003435 sp<IGraphicBufferProducer> impl;
3436 sp<Looper> looper;
3437 status_t result;
3438 bool exitPending;
3439 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003440 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003441 uint32_t code;
3442 Parcel const* data;
3443 Parcel* reply;
3444
3445 enum {
3446 MSG_API_CALL,
3447 MSG_EXIT
3448 };
3449
3450 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003451 * Called on surfaceflinger thread. This is called by our "fake"
3452 * BpGraphicBufferProducer. We package the data and reply Parcel and
3453 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003454 */
3455 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003456 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003457 this->code = code;
3458 this->data = &data;
3459 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003460 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003461 // if we've exited, we run the message synchronously right here.
3462 // note (JH): as far as I can tell from looking at the code, this
3463 // never actually happens. if it does, i'm not sure if it happens
3464 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003465 handleMessage(Message(MSG_API_CALL));
3466 } else {
3467 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003468 // Prevent stores to this->{code, data, reply} from being
3469 // reordered later than the construction of Message.
3470 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003471 looper->sendMessage(this, Message(MSG_API_CALL));
3472 barrier.wait();
3473 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003474 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003475 }
3476
3477 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003478 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003479 * call the real BpGraphicBufferProducer.
3480 */
3481 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003482 int what = message.what;
3483 // Prevent reads below from happening before the read from Message
3484 atomic_thread_fence(memory_order_acquire);
3485 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003486 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003487 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003488 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003489 exitRequested = true;
3490 }
3491 }
3492
3493public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003494 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003495 : impl(impl),
3496 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003497 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003498 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003499 exitRequested(false),
3500 code(0),
3501 data(NULL),
3502 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003503 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003504
Jesse Hallb154c422014-07-13 12:47:02 -07003505 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003506 status_t waitForResponse() {
3507 do {
3508 looper->pollOnce(-1);
3509 } while (!exitRequested);
3510 return result;
3511 }
3512
Jesse Hallb154c422014-07-13 12:47:02 -07003513 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003514 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003515 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003516 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003517 // Ensure this->result is visible to the binder thread before it
3518 // handles the message.
3519 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003520 looper->sendMessage(this, Message(MSG_EXIT));
3521 }
3522};
3523
3524
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003525status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3526 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003527 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003528 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003529 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003530
3531 if (CC_UNLIKELY(display == 0))
3532 return BAD_VALUE;
3533
3534 if (CC_UNLIKELY(producer == 0))
3535 return BAD_VALUE;
3536
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003537 // if we have secure windows on this display, never allow the screen capture
3538 // unless the producer interface is local (i.e.: we can take a screenshot for
3539 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003540 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003541
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003542 // Convert to surfaceflinger's internal rotation type.
3543 Transform::orientation_flags rotationFlags;
3544 switch (rotation) {
3545 case ISurfaceComposer::eRotateNone:
3546 rotationFlags = Transform::ROT_0;
3547 break;
3548 case ISurfaceComposer::eRotate90:
3549 rotationFlags = Transform::ROT_90;
3550 break;
3551 case ISurfaceComposer::eRotate180:
3552 rotationFlags = Transform::ROT_180;
3553 break;
3554 case ISurfaceComposer::eRotate270:
3555 rotationFlags = Transform::ROT_270;
3556 break;
3557 default:
3558 rotationFlags = Transform::ROT_0;
3559 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3560 break;
3561 }
3562
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003563 class MessageCaptureScreen : public MessageBase {
3564 SurfaceFlinger* flinger;
3565 sp<IBinder> display;
3566 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003567 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003568 uint32_t reqWidth, reqHeight;
3569 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003570 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003571 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003572 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003573 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003574 public:
3575 MessageCaptureScreen(SurfaceFlinger* flinger,
3576 const sp<IBinder>& display,
3577 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003578 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003579 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003580 bool useIdentityTransform,
3581 Transform::orientation_flags rotation,
3582 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003583 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003584 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003585 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003586 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003587 rotation(rotation), result(PERMISSION_DENIED),
3588 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003589 {
3590 }
3591 status_t getResult() const {
3592 return result;
3593 }
3594 virtual bool handler() {
3595 Mutex::Autolock _l(flinger->mStateLock);
3596 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003597 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003598 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003599 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003600 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003601 return true;
3602 }
3603 };
3604
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003605 // this creates a "fake" BBinder which will serve as a "fake" remote
3606 // binder to receive the marshaled calls and forward them to the
3607 // real remote (a BpGraphicBufferProducer)
3608 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3609
3610 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3611 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003612 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003613 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003614 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003615 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003616
3617 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003618 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003619 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003620 }
3621 return res;
3622}
3623
Mathias Agopian180f10d2013-04-10 22:55:41 -07003624
3625void SurfaceFlinger::renderScreenImplLocked(
3626 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003627 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003628 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003629 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003630{
3631 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003632 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003633
3634 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003635 const int32_t hw_w = hw->getWidth();
3636 const int32_t hw_h = hw->getHeight();
3637 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003638 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003639
Dan Stozac1879002014-05-22 15:59:05 -07003640 // if a default or invalid sourceCrop is passed in, set reasonable values
3641 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3642 !sourceCrop.isValid()) {
3643 sourceCrop.setLeftTop(Point(0, 0));
3644 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3645 }
3646
3647 // ensure that sourceCrop is inside screen
3648 if (sourceCrop.left < 0) {
3649 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3650 }
Dan Stozabe31f442014-06-11 11:20:54 -07003651 if (sourceCrop.right > hw_w) {
3652 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003653 }
3654 if (sourceCrop.top < 0) {
3655 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3656 }
Dan Stozabe31f442014-06-11 11:20:54 -07003657 if (sourceCrop.bottom > hw_h) {
3658 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003659 }
3660
Mathias Agopian180f10d2013-04-10 22:55:41 -07003661 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003662 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003663
3664 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003665 engine.setViewportAndProjection(
3666 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003667 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003668
3669 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003670 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003671
3672 const LayerVector& layers( mDrawingState.layersSortedByZ );
3673 const size_t count = layers.size();
3674 for (size_t i=0 ; i<count ; ++i) {
3675 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003676 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003677 if (state.layerStack == hw->getLayerStack()) {
3678 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3679 if (layer->isVisible()) {
3680 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003681 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003682 if (filtering) layer->setFiltering(false);
3683 }
3684 }
3685 }
3686 }
3687
Mathias Agopian931bda12013-08-28 18:11:46 -07003688 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003689}
3690
3691
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003692status_t SurfaceFlinger::captureScreenImplLocked(
3693 const sp<const DisplayDevice>& hw,
3694 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003695 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003696 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003697 bool useIdentityTransform, Transform::orientation_flags rotation,
3698 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003699{
3700 ATRACE_CALL();
3701
Mathias Agopian180f10d2013-04-10 22:55:41 -07003702 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003703 uint32_t hw_w = hw->getWidth();
3704 uint32_t hw_h = hw->getHeight();
3705
3706 if (rotation & Transform::ROT_90) {
3707 std::swap(hw_w, hw_h);
3708 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003709
Mathias Agopian180f10d2013-04-10 22:55:41 -07003710 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3711 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3712 reqWidth, reqHeight, hw_w, hw_h);
3713 return BAD_VALUE;
3714 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003715
Mathias Agopian180f10d2013-04-10 22:55:41 -07003716 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3717 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3718
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003719 bool secureLayerIsVisible = false;
3720 const LayerVector& layers(mDrawingState.layersSortedByZ);
3721 const size_t count = layers.size();
3722 for (size_t i = 0 ; i < count ; ++i) {
3723 const sp<Layer>& layer(layers[i]);
3724 const Layer::State& state(layer->getDrawingState());
3725 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3726 state.z <= maxLayerZ && layer->isVisible() &&
3727 layer->isSecure()) {
3728 secureLayerIsVisible = true;
3729 }
3730 }
3731
3732 if (!isLocalScreenshot && secureLayerIsVisible) {
3733 ALOGW("FB is protected: PERMISSION_DENIED");
3734 return PERMISSION_DENIED;
3735 }
3736
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003737 // create a surface (because we're a producer, and we need to
3738 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003739 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003740
3741 // Put the screenshot Surface into async mode so that
3742 // Layer::headFenceHasSignaled will always return true and we'll latch the
3743 // first buffer regardless of whether or not its acquire fence has
3744 // signaled. This is needed to avoid a race condition in the rotation
3745 // animation. See b/30209608
3746 sur->setAsyncMode(true);
3747
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003748 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003749
Michael Lentine5a16a622015-05-21 13:48:24 -07003750 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3751 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003752 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3753 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003754
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003755 int err = 0;
3756 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003757 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003758 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3759 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003760
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003761 if (err == NO_ERROR) {
3762 ANativeWindowBuffer* buffer;
3763 /* TODO: Once we have the sync framework everywhere this can use
3764 * server-side waits on the fence that dequeueBuffer returns.
3765 */
3766 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3767 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003768 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003769 // create an EGLImage from the buffer so we can later
3770 // turn it into a texture
3771 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3772 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3773 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003774 // this binds the given EGLImage as a framebuffer for the
3775 // duration of this scope.
3776 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3777 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003778 // this will in fact render into our dequeued buffer
3779 // via an FBO, which means we didn't have to create
3780 // an EGLSurface and therefore we're not
3781 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003782 renderScreenImplLocked(
3783 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3784 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003785
Riley Andrews86639902014-08-15 12:27:24 -07003786 // Attempt to create a sync khr object that can produce a sync point. If that
3787 // isn't available, create a non-dupable sync object in the fallback path and
3788 // wait on it directly.
3789 EGLSyncKHR sync;
3790 if (!DEBUG_SCREENSHOTS) {
3791 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003792 // native fence fd will not be populated until flush() is done.
3793 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003794 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003795 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003796 }
Riley Andrews86639902014-08-15 12:27:24 -07003797 if (sync != EGL_NO_SYNC_KHR) {
3798 // get the sync fd
3799 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3800 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3801 ALOGW("captureScreen: failed to dup sync khr object");
3802 syncFd = -1;
3803 }
3804 eglDestroySyncKHR(mEGLDisplay, sync);
3805 } else {
3806 // fallback path
3807 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3808 if (sync != EGL_NO_SYNC_KHR) {
3809 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3810 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3811 EGLint eglErr = eglGetError();
3812 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3813 ALOGW("captureScreen: fence wait timed out");
3814 } else {
3815 ALOGW_IF(eglErr != EGL_SUCCESS,
3816 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3817 }
3818 eglDestroySyncKHR(mEGLDisplay, sync);
3819 } else {
3820 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3821 }
3822 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003823 if (DEBUG_SCREENSHOTS) {
3824 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3825 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3826 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3827 hw, minLayerZ, maxLayerZ);
3828 delete [] pixels;
3829 }
3830
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003831 } else {
3832 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3833 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003834 window->cancelBuffer(window, buffer, syncFd);
3835 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003836 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003837 // destroy our image
3838 eglDestroyImageKHR(mEGLDisplay, image);
3839 } else {
3840 result = BAD_VALUE;
3841 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003842 if (buffer) {
3843 // queueBuffer takes ownership of syncFd
3844 result = window->queueBuffer(window, buffer, syncFd);
3845 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003846 }
3847 } else {
3848 result = BAD_VALUE;
3849 }
3850 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3851 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003852
Mathias Agopian74c40c02010-09-29 13:02:36 -07003853 return result;
3854}
3855
Mathias Agopiand5556842013-09-19 17:08:37 -07003856void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3857 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003858 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003859 for (size_t y=0 ; y<h ; y++) {
3860 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3861 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003862 if (p[x] != 0xFF000000) return;
3863 }
3864 }
3865 ALOGE("*** we just took a black screenshot ***\n"
3866 "requested minz=%d, maxz=%d, layerStack=%d",
3867 minLayerZ, maxLayerZ, hw->getLayerStack());
3868 const LayerVector& layers( mDrawingState.layersSortedByZ );
3869 const size_t count = layers.size();
3870 for (size_t i=0 ; i<count ; ++i) {
3871 const sp<Layer>& layer(layers[i]);
3872 const Layer::State& state(layer->getDrawingState());
3873 const bool visible = (state.layerStack == hw->getLayerStack())
3874 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3875 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003876 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003877 visible ? '+' : '-',
3878 i, layer->getName().string(), state.layerStack, state.z,
3879 layer->isVisible(), state.flags, state.alpha);
3880 }
3881 }
3882}
3883
Pablo Ceballosce796e72016-02-04 19:10:51 -08003884bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3885 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3886 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3887}
3888
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003889// ---------------------------------------------------------------------------
3890
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003891SurfaceFlinger::LayerVector::LayerVector() {
3892}
3893
3894SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003895 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003896}
3897
3898int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3899 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003900{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003901 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003902 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3903 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003904
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003905 uint32_t ls = l->getCurrentState().layerStack;
3906 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003907 if (ls != rs)
3908 return ls - rs;
3909
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003910 uint32_t lz = l->getCurrentState().z;
3911 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003912 if (lz != rz)
3913 return lz - rz;
3914
3915 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003916}
3917
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003919
3920
3921#if defined(__gl_h_)
3922#error "don't include gl/gl.h in this file"
3923#endif
3924
3925#if defined(__gl2_h_)
3926#error "don't include gl2/gl2.h in this file"
3927#endif