blob: fa61a9b528462594739aaa2e7207543db3133c4c [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>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700155 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
160 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Steve Blocka19954a2012-01-04 20:05:49 +0000162 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163
164 // debugging stuff...
165 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700166
Mathias Agopianb4b17302013-03-20 18:36:41 -0700167 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700168 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700169
Dan Stoza14cd37c2015-07-09 12:43:33 -0700170 property_get("debug.sf.drop_missed_frames", value, "0");
171 mDropMissedFrames = atoi(value);
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 property_get("debug.sf.showupdates", value, "0");
174 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700175
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700176 property_get("debug.sf.ddms", value, "0");
177 mDebugDDMS = atoi(value);
178 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700179 if (!startDdmConnection()) {
180 // start failed, and DDMS debugging not enabled
181 mDebugDDMS = 0;
182 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700183 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700184 ALOGI_IF(mDebugRegion, "showupdates enabled");
185 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186}
187
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800188void SurfaceFlinger::onFirstRef()
189{
190 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800191}
192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193SurfaceFlinger::~SurfaceFlinger()
194{
Mathias Agopiana4912602012-07-12 14:25:33 -0700195 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
196 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
197 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198}
199
Dan Stozac7014012014-02-14 15:03:43 -0800200void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800201{
202 // the window manager died on us. prepare its eulogy.
203
Andy McFadden13a082e2012-08-24 10:16:42 -0700204 // restore initial conditions (default device unblank, etc)
205 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800206
207 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700208 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800209}
210
Mathias Agopian7e27f052010-05-28 14:22:23 -0700211sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212{
Mathias Agopian96f08192010-06-02 23:28:45 -0700213 sp<ISurfaceComposerClient> bclient;
214 sp<Client> client(new Client(this));
215 status_t err = client->initCheck();
216 if (err == NO_ERROR) {
217 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 return bclient;
220}
221
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700222sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
223 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700224{
225 class DisplayToken : public BBinder {
226 sp<SurfaceFlinger> flinger;
227 virtual ~DisplayToken() {
228 // no more references, this display must be terminated
229 Mutex::Autolock _l(flinger->mStateLock);
230 flinger->mCurrentState.displays.removeItem(this);
231 flinger->setTransactionFlags(eDisplayTransactionNeeded);
232 }
233 public:
234 DisplayToken(const sp<SurfaceFlinger>& flinger)
235 : flinger(flinger) {
236 }
237 };
238
239 sp<BBinder> token = new DisplayToken(this);
240
241 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700242 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700243 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700244 mCurrentState.displays.add(token, info);
245
246 return token;
247}
248
Jesse Hall6c913be2013-08-08 12:15:49 -0700249void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
250 Mutex::Autolock _l(mStateLock);
251
252 ssize_t idx = mCurrentState.displays.indexOfKey(display);
253 if (idx < 0) {
254 ALOGW("destroyDisplay: invalid display token");
255 return;
256 }
257
258 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
259 if (!info.isVirtualDisplay()) {
260 ALOGE("destroyDisplay called for non-virtual display");
261 return;
262 }
263
264 mCurrentState.displays.removeItemsAt(idx);
265 setTransactionFlags(eDisplayTransactionNeeded);
266}
267
Jesse Hall692c7232012-11-08 15:41:56 -0800268void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800269 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800270 ALOGW_IF(mBuiltinDisplays[type],
271 "Overwriting display token for display type %d", type);
272 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800273 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700274 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800275 mCurrentState.displays.add(mBuiltinDisplays[type], info);
276}
277
Mathias Agopiane57f2922012-08-09 16:29:12 -0700278sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700279 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
281 return NULL;
282 }
Jesse Hall692c7232012-11-08 15:41:56 -0800283 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284}
285
Jamie Gennis9a78c902011-01-12 18:30:40 -0800286sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
287{
288 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
289 return gba;
290}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700291
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292void SurfaceFlinger::bootFinished()
293{
294 const nsecs_t now = systemTime();
295 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000296 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700297 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700298
299 // wait patiently for the window manager death
300 const String16 name("window");
301 sp<IBinder> window(defaultServiceManager()->getService(name));
302 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700303 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700304 }
305
306 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700307 // formerly we would just kill the process, but we now ask it to exit so it
308 // can choose where to stop the animation.
309 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700310
311 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
312 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
313 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314}
315
Mathias Agopian3f844832013-08-07 21:24:32 -0700316void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700317 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700318 RenderEngine& engine;
319 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700320 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700321 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
322 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700323 }
324 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700326 return true;
327 }
328 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700329 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330}
331
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700332class DispSyncSource : public VSyncSource, private DispSync::Callback {
333public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700334 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000335 const char* name) :
336 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700337 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700338 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000339 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
340 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700341 mDispSync(dispSync),
342 mCallbackMutex(),
343 mCallback(),
344 mVsyncMutex(),
345 mPhaseOffset(phaseOffset),
346 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700347
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700348 virtual ~DispSyncSource() {}
349
350 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700351 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000353 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error registering vsync callback: %s (%d)",
357 strerror(-err), err);
358 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700359 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700360 } else {
361 status_t err = mDispSync->removeEventListener(
362 static_cast<DispSync::Callback*>(this));
363 if (err != NO_ERROR) {
364 ALOGE("error unregistering vsync callback: %s (%d)",
365 strerror(-err), err);
366 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700367 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700369 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700370 }
371
372 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700373 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 mCallback = callback;
375 }
376
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700377 virtual void setPhaseOffset(nsecs_t phaseOffset) {
378 Mutex::Autolock lock(mVsyncMutex);
379
380 // Normalize phaseOffset to [0, period)
381 auto period = mDispSync->getPeriod();
382 phaseOffset %= period;
383 if (phaseOffset < 0) {
384 // If we're here, then phaseOffset is in (-period, 0). After this
385 // operation, it will be in (0, period)
386 phaseOffset += period;
387 }
388 mPhaseOffset = phaseOffset;
389
390 // If we're not enabled, we don't need to mess with the listeners
391 if (!mEnabled) {
392 return;
393 }
394
395 // Remove the listener with the old offset
396 status_t err = mDispSync->removeEventListener(
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error unregistering vsync callback: %s (%d)",
400 strerror(-err), err);
401 }
402
403 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 static_cast<DispSync::Callback*>(this));
406 if (err != NO_ERROR) {
407 ALOGE("error registering vsync callback: %s (%d)",
408 strerror(-err), err);
409 }
410 }
411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412private:
413 virtual void onDispSyncEvent(nsecs_t when) {
414 sp<VSyncSource::Callback> callback;
415 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700416 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 callback = mCallback;
418
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700419 if (mTraceVsync) {
420 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700421 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700422 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 }
424
425 if (callback != NULL) {
426 callback->onVSyncEvent(when);
427 }
428 }
429
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* const mName;
431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 int mValue;
433
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700434 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 const String8 mVsyncOnLabel;
436 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439
440 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442
443 Mutex mVsyncMutex; // Protects the following
444 nsecs_t mPhaseOffset;
445 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446};
447
448void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700449 ALOGI( "SurfaceFlinger's main thread ready to run. "
450 "Initializing graphics H/W...");
451
Dan Stoza9e56aa02015-11-02 13:00:03 -0800452 { // Autolock scope
453 Mutex::Autolock _l(mStateLock);
454
455 // initialize EGL for the default display
456 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
457 eglInitialize(mEGLDisplay, NULL, NULL);
458
459 // start the EventThread
460 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
461 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000462 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800463 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
464 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800466 mEventQueue.setEventThread(mSFEventThread);
467
468 // Get a RenderEngine for the given display / config (can't fail)
469 mRenderEngine = RenderEngine::create(mEGLDisplay,
470 HAL_PIXEL_FORMAT_RGBA_8888);
471 }
472
473 // Drop the state lock while we initialize the hardware composer. We drop
474 // the lock because on creation, it will call back into SurfaceFlinger to
475 // initialize the primary display.
476 mHwc = new HWComposer(this);
477 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
478
Jesse Hall692c7232012-11-08 15:41:56 -0800479 Mutex::Autolock _l(mStateLock);
480
Mathias Agopian875d8e12013-06-07 15:35:48 -0700481 // retrieve the EGL context that was selected/created
482 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700483
Mathias Agopianda27af92012-09-13 18:17:13 -0700484 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
485 "couldn't create EGLContext");
486
Dan Stoza9e56aa02015-11-02 13:00:03 -0800487 // make the GLContext current so that we can create textures when creating
488 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700489 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
490
Jamie Gennisd1700752013-10-14 12:22:52 -0700491 mEventControlThread = new EventControlThread(this);
492 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
493
Mathias Agopian92a979a2012-08-02 18:32:23 -0700494 // initialize our drawing state
495 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700496
Andy McFadden13a082e2012-08-24 10:16:42 -0700497 // set initial conditions (e.g. unblank default device)
498 initializeDisplays();
499
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700500 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700501 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502
Dan Stoza9e56aa02015-11-02 13:00:03 -0800503 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700504}
505
Mathias Agopiana67e4182012-06-19 17:26:12 -0700506void SurfaceFlinger::startBootAnim() {
507 // start boot animation
508 property_set("service.bootanim.exit", "0");
509 property_set("ctl.start", "bootanim");
510}
511
Mathias Agopian875d8e12013-06-07 15:35:48 -0700512size_t SurfaceFlinger::getMaxTextureSize() const {
513 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700514}
515
Mathias Agopian875d8e12013-06-07 15:35:48 -0700516size_t SurfaceFlinger::getMaxViewportDims() const {
517 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700518}
519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800521
Jamie Gennis582270d2011-08-17 18:19:00 -0700522bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800523 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800524 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800525 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700526 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800527}
528
Dan Stoza7f7da322014-05-02 15:26:25 -0700529status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
530 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700531 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700532 return BAD_VALUE;
533 }
534
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500535 if (!display.get())
536 return NAME_NOT_FOUND;
537
Jesse Hall692c7232012-11-08 15:41:56 -0800538 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700539 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800540 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700541 type = i;
542 break;
543 }
544 }
545
546 if (type < 0) {
547 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700548 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700549
Mathias Agopian8b736f12012-08-13 17:54:26 -0700550 // TODO: Not sure if display density should handled by SF any longer
551 class Density {
552 static int getDensityFromProperty(char const* propName) {
553 char property[PROPERTY_VALUE_MAX];
554 int density = 0;
555 if (property_get(propName, property, NULL) > 0) {
556 density = atoi(property);
557 }
558 return density;
559 }
560 public:
561 static int getEmuDensity() {
562 return getDensityFromProperty("qemu.sf.lcd_density"); }
563 static int getBuildDensity() {
564 return getDensityFromProperty("ro.sf.lcd_density"); }
565 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700566
Dan Stoza7f7da322014-05-02 15:26:25 -0700567 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700568
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700570 DisplayInfo info = DisplayInfo();
571
Dan Stoza9e56aa02015-11-02 13:00:03 -0800572 float xdpi = hwConfig->getDpiX();
573 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700574
575 if (type == DisplayDevice::DISPLAY_PRIMARY) {
576 // The density of the device is provided by a build property
577 float density = Density::getBuildDensity() / 160.0f;
578 if (density == 0) {
579 // the build doesn't provide a density -- this is wrong!
580 // use xdpi instead
581 ALOGE("ro.sf.lcd_density must be defined as a build property");
582 density = xdpi / 160.0f;
583 }
584 if (Density::getEmuDensity()) {
585 // if "qemu.sf.lcd_density" is specified, it overrides everything
586 xdpi = ydpi = density = Density::getEmuDensity();
587 density /= 160.0f;
588 }
589 info.density = density;
590
591 // TODO: this needs to go away (currently needed only by webkit)
592 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
593 info.orientation = hw->getOrientation();
594 } else {
595 // TODO: where should this value come from?
596 static const int TV_DENSITY = 213;
597 info.density = TV_DENSITY / 160.0f;
598 info.orientation = 0;
599 }
600
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601 info.w = hwConfig->getWidth();
602 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700603 info.xdpi = xdpi;
604 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700606 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607
608 // TODO: Hook this back up
609 info.colorTransform = 0;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700610
611 // This is how far in advance a buffer must be queued for
612 // presentation at a given time. If you want a buffer to appear
613 // on the screen at time N, you must submit the buffer before
614 // (N - presentationDeadline).
615 //
616 // Normally it's one full refresh period (to give SF a chance to
617 // latch the buffer), but this can be reduced by configuring a
618 // DispSync offset. Any additional delays introduced by the hardware
619 // composer or panel must be accounted for here.
620 //
621 // We add an additional 1ms to allow for processing time and
622 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 info.presentationDeadline = hwConfig->getVsyncPeriod() -
624 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700625
626 // All non-virtual displays are currently considered secure.
627 info.secure = true;
628
629 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700630 }
631
Dan Stoza7f7da322014-05-02 15:26:25 -0700632 return NO_ERROR;
633}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700634
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800635status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700636 DisplayStatInfo* stats) {
637 if (stats == NULL) {
638 return BAD_VALUE;
639 }
640
641 // FIXME for now we always return stats for the primary display
642 memset(stats, 0, sizeof(*stats));
643 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
644 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
645 return NO_ERROR;
646}
647
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700648int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700649 sp<DisplayDevice> device(getDisplayDevice(display));
650 if (device != NULL) {
651 return device->getActiveConfig();
652 }
653 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700654}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700655
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700656void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
657 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
658 this);
659 int32_t type = hw->getDisplayType();
660 int currentMode = hw->getActiveConfig();
661
662 if (mode == currentMode) {
663 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
664 return;
665 }
666
667 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
668 ALOGW("Trying to set config for virtual display");
669 return;
670 }
671
672 hw->setActiveConfig(mode);
673 getHwComposer().setActiveConfig(type, mode);
674}
675
676status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
677 class MessageSetActiveConfig: public MessageBase {
678 SurfaceFlinger& mFlinger;
679 sp<IBinder> mDisplay;
680 int mMode;
681 public:
682 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
683 int mode) :
684 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
685 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700686 Vector<DisplayInfo> configs;
687 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700688 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700689 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700690 mMode, configs.size());
691 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700692 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
693 if (hw == NULL) {
694 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700695 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700696 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
697 ALOGW("Attempt to set active config = %d for virtual display",
698 mMode);
699 } else {
700 mFlinger.setActiveConfigInternal(hw, mMode);
701 }
702 return true;
703 }
704 };
705 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
706 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700707 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700708}
709
Svetoslavd85084b2014-03-20 10:28:31 -0700710status_t SurfaceFlinger::clearAnimationFrameStats() {
711 Mutex::Autolock _l(mStateLock);
712 mAnimFrameTracker.clearStats();
713 return NO_ERROR;
714}
715
716status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
717 Mutex::Autolock _l(mStateLock);
718 mAnimFrameTracker.getStats(outStats);
719 return NO_ERROR;
720}
721
Dan Stozac4f471e2016-03-24 09:31:08 -0700722status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
723 HdrCapabilities* outCapabilities) const {
724 Mutex::Autolock _l(mStateLock);
725
726 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
727 if (displayDevice == nullptr) {
728 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
729 return BAD_VALUE;
730 }
731
732 std::unique_ptr<HdrCapabilities> capabilities =
733 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
734 if (capabilities) {
735 std::swap(*outCapabilities, *capabilities);
736 } else {
737 return BAD_VALUE;
738 }
739
740 return NO_ERROR;
741}
742
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800743// ----------------------------------------------------------------------------
744
745sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800746 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700747}
748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800750
751void SurfaceFlinger::waitForEvent() {
752 mEventQueue.waitMessage();
753}
754
755void SurfaceFlinger::signalTransaction() {
756 mEventQueue.invalidate();
757}
758
759void SurfaceFlinger::signalLayerUpdate() {
760 mEventQueue.invalidate();
761}
762
763void SurfaceFlinger::signalRefresh() {
764 mEventQueue.refresh();
765}
766
767status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800768 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800769 return mEventQueue.postMessage(msg, reltime);
770}
771
772status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800773 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800774 status_t res = mEventQueue.postMessage(msg, reltime);
775 if (res == NO_ERROR) {
776 msg->wait();
777 }
778 return res;
779}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700781void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700782 do {
783 waitForEvent();
784 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785}
786
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700787void SurfaceFlinger::enableHardwareVsync() {
788 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700789 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700790 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700791 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
792 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700793 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700794 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700795}
796
Jesse Hall948fe0c2013-10-14 12:56:09 -0700797void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700798 Mutex::Autolock _l(mHWVsyncLock);
799
Jesse Hall948fe0c2013-10-14 12:56:09 -0700800 if (makeAvailable) {
801 mHWVsyncAvailable = true;
802 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700803 // Hardware vsync is not currently available, so abort the resync
804 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700805 return;
806 }
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
809 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700810
811 mPrimaryDispSync.reset();
812 mPrimaryDispSync.setPeriod(period);
813
814 if (!mPrimaryHWVsyncEnabled) {
815 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700816 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
817 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700818 mPrimaryHWVsyncEnabled = true;
819 }
820}
821
Jesse Hall948fe0c2013-10-14 12:56:09 -0700822void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700823 Mutex::Autolock _l(mHWVsyncLock);
824 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700825 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
826 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700827 mPrimaryDispSync.endResync();
828 mPrimaryHWVsyncEnabled = false;
829 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700830 if (makeUnavailable) {
831 mHWVsyncAvailable = false;
832 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700833}
834
Tim Murray4a4e4a22016-04-19 16:29:23 +0000835void SurfaceFlinger::resyncWithRateLimit() {
836 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
837 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700838 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000839 }
840}
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700843 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700844
Jamie Gennisd1700752013-10-14 12:22:52 -0700845 { // Scope for the lock
846 Mutex::Autolock _l(mHWVsyncLock);
847 if (type == 0 && mPrimaryHWVsyncEnabled) {
848 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700849 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700850 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700851
852 if (needsHwVsync) {
853 enableHardwareVsync();
854 } else {
855 disableHardwareVsync(false);
856 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700857}
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
860 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
861 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
862 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700863
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 // All non-virtual displays are currently considered secure.
865 bool isSecure = true;
866
867 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
868 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
869 wp<IBinder> token = mBuiltinDisplays[type];
870
871 sp<IGraphicBufferProducer> producer;
872 sp<IGraphicBufferConsumer> consumer;
873 BufferQueue::createBufferQueue(&producer, &consumer,
874 new GraphicBufferAlloc());
875
876 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
877 DisplayDevice::DISPLAY_PRIMARY, consumer);
878 sp<DisplayDevice> hw = new DisplayDevice(this,
879 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
880 producer, mRenderEngine->getEGLConfig());
881 mDisplays.add(token, hw);
882 } else {
883 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700884 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800885 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700887 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800888 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
889 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700890 }
891 setTransactionFlags(eDisplayTransactionNeeded);
892
Andy McFadden9e9689c2012-10-10 18:17:51 -0700893 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700894 }
Mathias Agopian86303202012-07-24 22:46:10 -0700895}
896
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700898 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800899 getHwComposer().setVsyncEnabled(disp,
900 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700901}
902
Mathias Agopian4fec8732012-06-29 14:12:52 -0700903void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800904 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800905 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800906 case MessageQueue::INVALIDATE: {
907 bool refreshNeeded = handleMessageTransaction();
908 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800909 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800910 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800911 // Signal a refresh if a transaction modified the window state,
912 // a new buffer was latched, or if HWC has requested a full
913 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800914 signalRefresh();
915 }
916 break;
917 }
918 case MessageQueue::REFRESH: {
919 handleMessageRefresh();
920 break;
921 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800922 }
923}
924
Dan Stoza6b9454d2014-11-07 16:00:59 -0800925bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700926 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700927 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700928 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800929 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700930 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800931 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700932}
933
Dan Stoza6b9454d2014-11-07 16:00:59 -0800934bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700935 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800936 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700937}
938
939void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700940 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700941
Pablo Ceballos40845df2016-01-25 17:41:15 -0800942 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700943 static nsecs_t previousExpectedPresent = 0;
944 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
945 static bool previousFrameMissed = false;
946 bool frameMissed = (expectedPresent == previousExpectedPresent);
947 if (frameMissed != previousFrameMissed) {
948 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
949 }
950 previousFrameMissed = frameMissed;
951
952 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
953 // Latch buffers, but don't send anything to HWC, then signal another
954 // wakeup for the next vsync
955 preComposition();
956 repaintEverything();
957 } else {
958 preComposition();
959 rebuildLayerStacks();
960 setUpHWComposer();
961 doDebugFlashRegions();
962 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800963 postComposition(refreshStartTime);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700964 }
965
Dan Stoza9e56aa02015-11-02 13:00:03 -0800966 // Release any buffers which were replaced this frame
967 for (auto& layer : mLayersWithQueuedFrames) {
968 layer->releasePendingBuffer();
969 }
970 mLayersWithQueuedFrames.clear();
971
Dan Stoza14cd37c2015-07-09 12:43:33 -0700972 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700973}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700974
Mathias Agopiancd60f992012-08-16 16:28:27 -0700975void SurfaceFlinger::doDebugFlashRegions()
976{
977 // is debugging enabled
978 if (CC_LIKELY(!mDebugRegion))
979 return;
980
981 const bool repaintEverything = mRepaintEverything;
982 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
983 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700984 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700985 // transform the dirty region into this screen's coordinate space
986 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
987 if (!dirtyRegion.isEmpty()) {
988 // redraw the whole screen
989 doComposeSurfaces(hw, Region(hw->bounds()));
990
991 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700992 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -0700993 RenderEngine& engine(getRenderEngine());
994 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
995
Mathias Agopianda27af92012-09-13 18:17:13 -0700996 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -0700997 }
998 }
999 }
1000
1001 postFramebuffer();
1002
1003 if (mDebugRegion > 1) {
1004 usleep(mDebugRegion * 1000);
1005 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001006
Dan Stoza9e56aa02015-11-02 13:00:03 -08001007 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001008 auto& displayDevice = mDisplays[displayId];
1009 if (!displayDevice->isDisplayOn()) {
1010 continue;
1011 }
1012
1013 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001014 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1015 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001016 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001017}
1018
1019void SurfaceFlinger::preComposition()
1020{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001021 ATRACE_CALL();
1022 ALOGV("preComposition");
1023
Mathias Agopiancd60f992012-08-16 16:28:27 -07001024 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001025 const LayerVector& layers(mDrawingState.layersSortedByZ);
1026 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001027 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001028 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001029 needExtraInvalidate = true;
1030 }
1031 }
1032 if (needExtraInvalidate) {
1033 signalLayerUpdate();
1034 }
1035}
1036
Pablo Ceballos40845df2016-01-25 17:41:15 -08001037void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001038{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001039 ATRACE_CALL();
1040 ALOGV("postComposition");
1041
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001042 const LayerVector& layers(mDrawingState.layersSortedByZ);
1043 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001044 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001045 bool frameLatched = layers[i]->onPostComposition();
1046 if (frameLatched) {
1047 recordBufferingStats(layers[i]->getName().string(),
1048 layers[i]->getOccupancyHistory(false));
1049 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001050 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001051
Dan Stoza9e56aa02015-11-02 13:00:03 -08001052 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053
1054 if (presentFence->isValid()) {
1055 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1056 enableHardwareVsync();
1057 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001058 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059 }
1060 }
1061
Dan Stozab90cf072015-03-05 11:05:59 -08001062 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001063 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001064 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065 enableHardwareVsync();
1066 }
1067 }
1068
Pablo Ceballos40845df2016-01-25 17:41:15 -08001069 mFenceTracker.addFrame(refreshStartTime, presentFence,
1070 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1071
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001072 if (mAnimCompositionPending) {
1073 mAnimCompositionPending = false;
1074
Jesse Halla9a1b002013-02-27 16:39:25 -08001075 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001076 mAnimFrameTracker.setActualPresentFence(presentFence);
1077 } else {
1078 // The HWC doesn't support present fences, so use the refresh
1079 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001080 nsecs_t presentTime =
1081 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001082 mAnimFrameTracker.setActualPresentTime(presentTime);
1083 }
1084 mAnimFrameTracker.advanceFrame();
1085 }
Dan Stozab90cf072015-03-05 11:05:59 -08001086
1087 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1088 return;
1089 }
1090
1091 nsecs_t currentTime = systemTime();
1092 if (mHasPoweredOff) {
1093 mHasPoweredOff = false;
1094 } else {
1095 nsecs_t period = mPrimaryDispSync.getPeriod();
1096 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1097 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1098 if (numPeriods < NUM_BUCKETS - 1) {
1099 mFrameBuckets[numPeriods] += elapsedTime;
1100 } else {
1101 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1102 }
1103 mTotalTime += elapsedTime;
1104 }
1105 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001106}
1107
1108void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001109 ATRACE_CALL();
1110 ALOGV("rebuildLayerStacks");
1111
Mathias Agopiancd60f992012-08-16 16:28:27 -07001112 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001113 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001114 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001115 mVisibleRegionsDirty = false;
1116 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001117
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001118 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001119 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001120 Region opaqueRegion;
1121 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001122 Vector<sp<Layer>> layersSortedByZ;
1123 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1124 const Transform& tr(displayDevice->getTransform());
1125 const Rect bounds(displayDevice->getBounds());
1126 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001127 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128 displayDevice->getLayerStack(), dirtyRegion,
1129 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001130
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001131 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001132 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001133 const sp<Layer>& layer(layers[i]);
1134 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001135 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001136 Region drawRegion(tr.transform(
1137 layer->visibleNonTransparentRegion));
1138 drawRegion.andSelf(bounds);
1139 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001140 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 } else {
1142 // Clear out the HWC layer if this layer was
1143 // previously visible, but no longer is
1144 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1145 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001146 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001147 }
1148 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001149 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1151 displayDevice->undefinedRegion.set(bounds);
1152 displayDevice->undefinedRegion.subtractSelf(
1153 tr.transform(opaqueRegion));
1154 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001155 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001156 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001157}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001158
Mathias Agopiancd60f992012-08-16 16:28:27 -07001159void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001160 ATRACE_CALL();
1161 ALOGV("setUpHWComposer");
1162
Jesse Hall028dc8f2013-08-20 16:35:32 -07001163 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001164 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1165 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1166 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1167
1168 // If nothing has changed (!dirty), don't recompose.
1169 // If something changed, but we don't currently have any visible layers,
1170 // and didn't when we last did a composition, then skip it this time.
1171 // The second rule does two things:
1172 // - When all layers are removed from a display, we'll emit one black
1173 // frame, then nothing more until we get new layers.
1174 // - When a display is created with a private layer stack, we won't
1175 // emit any black frames until a layer is added to the layer stack.
1176 bool mustRecompose = dirty && !(empty && wasEmpty);
1177
1178 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1179 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1180 mustRecompose ? "doing" : "skipping",
1181 dirty ? "+" : "-",
1182 empty ? "+" : "-",
1183 wasEmpty ? "+" : "-");
1184
Dan Stoza71433162014-02-04 16:22:36 -08001185 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001186
1187 if (mustRecompose) {
1188 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1189 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001190 }
1191
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192 // build the h/w work list
1193 if (CC_UNLIKELY(mGeometryInvalid)) {
1194 mGeometryInvalid = false;
1195 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1196 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1197 const auto hwcId = displayDevice->getHwcDisplayId();
1198 if (hwcId >= 0) {
1199 const Vector<sp<Layer>>& currentLayers(
1200 displayDevice->getVisibleLayersSortedByZ());
1201 bool foundLayerWithoutHwc = false;
1202 for (auto& layer : currentLayers) {
1203 if (!layer->hasHwcLayer(hwcId)) {
1204 auto hwcLayer = mHwc->createLayer(hwcId);
1205 if (hwcLayer) {
1206 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1207 } else {
1208 layer->forceClientComposition(hwcId);
1209 foundLayerWithoutHwc = true;
1210 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001211 }
1212 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001213
Dan Stoza9e56aa02015-11-02 13:00:03 -08001214 layer->setGeometry(displayDevice);
1215 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1216 mHasColorMatrix) {
1217 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001218 }
1219 }
1220 }
1221 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001222 }
Riley Andrews03414a12014-07-01 14:22:59 -07001223
Dan Stoza9e56aa02015-11-02 13:00:03 -08001224 // Set the per-frame data
1225 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1226 auto& displayDevice = mDisplays[displayId];
1227 const auto hwcId = displayDevice->getHwcDisplayId();
1228 if (hwcId < 0) {
1229 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001230 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001231 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1232 layer->setPerFrameData(displayDevice);
1233 }
1234 }
1235
1236 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001237 auto& displayDevice = mDisplays[displayId];
1238 if (!displayDevice->isDisplayOn()) {
1239 continue;
1240 }
1241
1242 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1244 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001245 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001246}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001247
Mathias Agopiancd60f992012-08-16 16:28:27 -07001248void SurfaceFlinger::doComposition() {
1249 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 ALOGV("doComposition");
1251
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001252 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001253 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001254 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001255 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001256 // transform the dirty region into this screen's coordinate space
1257 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001258
1259 // repaint the framebuffer (if needed)
1260 doDisplayComposition(hw, dirtyRegion);
1261
Mathias Agopiancd60f992012-08-16 16:28:27 -07001262 hw->dirtyRegion.clear();
1263 hw->flip(hw->swapRegion);
1264 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001265 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001266 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001267 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001268}
1269
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270void SurfaceFlinger::postFramebuffer()
1271{
Mathias Agopian841cde52012-03-01 15:44:37 -08001272 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001274
Mathias Agopiana44b0412011-10-16 18:46:35 -07001275 const nsecs_t now = systemTime();
1276 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001277
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1279 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001280 if (!displayDevice->isDisplayOn()) {
1281 continue;
1282 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001283 const auto hwcId = displayDevice->getHwcDisplayId();
1284 if (hwcId >= 0) {
1285 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001286 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001287 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001288 if (displayId == 0) {
1289 // Make the default display current because the VirtualDisplayDevice
1290 // code cannot deal with dequeueBuffer() being called outside of the
1291 // composition loop; however the code below can call glFlush() which
1292 // is allowed to (and does in some case) call dequeueBuffer().
1293 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1294 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001295 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1296 sp<Fence> releaseFence = Fence::NO_FENCE;
1297 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1298 releaseFence = displayDevice->getClientTargetAcquireFence();
1299 } else {
1300 auto hwcLayer = layer->getHwcLayer(hwcId);
1301 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001302 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 layer->onLayerDisplayed(releaseFence);
1304 }
1305 if (hwcId >= 0) {
1306 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001307 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001308 }
1309
Mathias Agopiana44b0412011-10-16 18:46:35 -07001310 mLastSwapBufferTime = systemTime() - now;
1311 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001312
1313 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1314 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1315 logFrameStats();
1316 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001317}
1318
Mathias Agopian87baae12012-07-31 12:38:26 -07001319void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320{
Mathias Agopian841cde52012-03-01 15:44:37 -08001321 ATRACE_CALL();
1322
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001323 // here we keep a copy of the drawing state (that is the state that's
1324 // going to be overwritten by handleTransactionLocked()) outside of
1325 // mStateLock so that the side-effects of the State assignment
1326 // don't happen with mStateLock held (which can cause deadlocks).
1327 State drawingState(mDrawingState);
1328
Mathias Agopianca4d3602011-05-19 15:38:14 -07001329 Mutex::Autolock _l(mStateLock);
1330 const nsecs_t now = systemTime();
1331 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332
Mathias Agopianca4d3602011-05-19 15:38:14 -07001333 // Here we're guaranteed that some transaction flags are set
1334 // so we can call handleTransactionLocked() unconditionally.
1335 // We call getTransactionFlags(), which will also clear the flags,
1336 // with mStateLock held to guarantee that mCurrentState won't change
1337 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001338
Mathias Agopiane57f2922012-08-09 16:29:12 -07001339 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001340 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001341
Mathias Agopianca4d3602011-05-19 15:38:14 -07001342 mLastTransactionTime = systemTime() - now;
1343 mDebugInTransaction = 0;
1344 invalidateHwcGeometry();
1345 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001346}
1347
Mathias Agopian87baae12012-07-31 12:38:26 -07001348void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001349{
1350 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351 const size_t count = currentLayers.size();
1352
Dan Stoza7dde5992015-05-22 09:51:44 -07001353 // Notify all layers of available frames
1354 for (size_t i = 0; i < count; ++i) {
1355 currentLayers[i]->notifyAvailableFrames();
1356 }
1357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001358 /*
1359 * Traversal of the children
1360 * (perform the transaction for each of them if needed)
1361 */
1362
Mathias Agopian3559b072012-08-15 13:46:03 -07001363 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001364 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001365 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001366 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1367 if (!trFlags) continue;
1368
1369 const uint32_t flags = layer->doTransaction(0);
1370 if (flags & Layer::eVisibleRegion)
1371 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001372 }
1373 }
1374
1375 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001376 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001377 */
1378
Mathias Agopiane57f2922012-08-09 16:29:12 -07001379 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001380 // here we take advantage of Vector's copy-on-write semantics to
1381 // improve performance by skipping the transaction entirely when
1382 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001383 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1384 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001385 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001386 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001387 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001388 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001389
1390 // find the displays that were removed
1391 // (ie: in drawing state but not in current state)
1392 // also handle displays that changed
1393 // (ie: displays that are in both lists)
1394 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001395 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1396 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001397 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001398 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001399 // Call makeCurrent() on the primary display so we can
1400 // be sure that nothing associated with this display
1401 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001402 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001403 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001404 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1405 if (hw != NULL)
1406 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001407 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001408 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001409 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001410 } else {
1411 ALOGW("trying to remove the main display");
1412 }
1413 } else {
1414 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001415 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001416 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001417 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1418 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001419 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001420 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001421 // recreating the DisplayDevice, so we just remove it
1422 // from the drawing state, so that it get re-added
1423 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001424 sp<DisplayDevice> hw(getDisplayDevice(display));
1425 if (hw != NULL)
1426 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001427 mDisplays.removeItem(display);
1428 mDrawingState.displays.removeItemsAt(i);
1429 dc--; i--;
1430 // at this point we must loop to the next item
1431 continue;
1432 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001433
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001434 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001435 if (disp != NULL) {
1436 if (state.layerStack != draw[i].layerStack) {
1437 disp->setLayerStack(state.layerStack);
1438 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001439 if ((state.orientation != draw[i].orientation)
1440 || (state.viewport != draw[i].viewport)
1441 || (state.frame != draw[i].frame))
1442 {
1443 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001444 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001445 }
Michael Lentine47e45402014-07-18 15:34:25 -07001446 if (state.width != draw[i].width || state.height != draw[i].height) {
1447 disp->setDisplaySize(state.width, state.height);
1448 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001449 }
1450 }
1451 }
1452
1453 // find displays that were added
1454 // (ie: in current state but not in drawing state)
1455 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001456 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001457 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001458
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001459 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001460 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001461 sp<IGraphicBufferProducer> bqProducer;
1462 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001463 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1464 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001465
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001467 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001468 // Virtual displays without a surface are dormant:
1469 // they have external state (layer stack, projection,
1470 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001471 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001472
Dan Stoza1f3efb12014-10-15 16:34:55 -07001473 int width = 0;
1474 int status = state.surface->query(
1475 NATIVE_WINDOW_WIDTH, &width);
1476 ALOGE_IF(status != NO_ERROR,
1477 "Unable to query width (%d)", status);
1478 int height = 0;
1479 status = state.surface->query(
1480 NATIVE_WINDOW_HEIGHT, &height);
1481 ALOGE_IF(status != NO_ERROR,
1482 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001483 int intFormat = 0;
1484 status = state.surface->query(
1485 NATIVE_WINDOW_FORMAT, &intFormat);
1486 ALOGE_IF(status != NO_ERROR,
1487 "Unable to query format (%d)", status);
1488 auto format = static_cast<android_pixel_format_t>(
1489 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001490
Dan Stoza5cf424b2016-05-20 14:02:39 -07001491 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 &hwcId);
1493
Dan Stoza5cf424b2016-05-20 14:02:39 -07001494 // TODO: Plumb requested format back up to consumer
1495
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 sp<VirtualDisplaySurface> vds =
1497 new VirtualDisplaySurface(*mHwc,
1498 hwcId, state.surface, bqProducer,
1499 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001500
1501 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001502 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001503 }
1504 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001505 ALOGE_IF(state.surface!=NULL,
1506 "adding a supported display, but rendering "
1507 "surface is provided (%p), ignoring it",
1508 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1510 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1511 dispSurface = new FramebufferSurface(*mHwc,
1512 DisplayDevice::DISPLAY_EXTERNAL,
1513 bqConsumer);
1514 producer = bqProducer;
1515 } else {
1516 ALOGE("Attempted to add non-external non-virtual"
1517 " display");
1518 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001519 }
1520
1521 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001522 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001523 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001524 state.type, hwcId, state.isSecure, display,
1525 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001526 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001527 hw->setLayerStack(state.layerStack);
1528 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001529 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001530 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001531 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001532 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001533 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001534 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001535 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001536 }
1537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001538 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001539 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001540
Mathias Agopian84300952012-11-21 16:02:13 -08001541 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1542 // The transform hint might have changed for some layers
1543 // (either because a display has changed, or because a layer
1544 // as changed).
1545 //
1546 // Walk through all the layers in currentLayers,
1547 // and update their transform hint.
1548 //
1549 // If a layer is visible only on a single display, then that
1550 // display is used to calculate the hint, otherwise we use the
1551 // default display.
1552 //
1553 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1554 // the hint is set before we acquire a buffer from the surface texture.
1555 //
1556 // NOTE: layer transactions have taken place already, so we use their
1557 // drawing state. However, SurfaceFlinger's own transaction has not
1558 // happened yet, so we must use the current state layer list
1559 // (soon to become the drawing state list).
1560 //
1561 sp<const DisplayDevice> disp;
1562 uint32_t currentlayerStack = 0;
1563 for (size_t i=0; i<count; i++) {
1564 // NOTE: we rely on the fact that layers are sorted by
1565 // layerStack first (so we don't have to traverse the list
1566 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001567 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001568 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001569 if (i==0 || currentlayerStack != layerStack) {
1570 currentlayerStack = layerStack;
1571 // figure out if this layerstack is mirrored
1572 // (more than one display) if so, pick the default display,
1573 // if not, pick the only display it's on.
1574 disp.clear();
1575 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1576 sp<const DisplayDevice> hw(mDisplays[dpy]);
1577 if (hw->getLayerStack() == currentlayerStack) {
1578 if (disp == NULL) {
1579 disp = hw;
1580 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001581 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001582 break;
1583 }
1584 }
1585 }
1586 }
Chet Haase91d25932013-04-11 15:24:55 -07001587 if (disp == NULL) {
1588 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1589 // redraw after transform hint changes. See bug 8508397.
1590
1591 // could be null when this layer is using a layerStack
1592 // that is not visible on any display. Also can occur at
1593 // screen off/on times.
1594 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001595 }
Chet Haase91d25932013-04-11 15:24:55 -07001596 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001597 }
1598 }
1599
1600
Mathias Agopian3559b072012-08-15 13:46:03 -07001601 /*
1602 * Perform our own transaction if needed
1603 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001604
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001605 const LayerVector& layers(mDrawingState.layersSortedByZ);
1606 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001607 // layers have been added
1608 mVisibleRegionsDirty = true;
1609 }
1610
1611 // some layers might have been removed, so
1612 // we need to update the regions they're exposing.
1613 if (mLayersRemoved) {
1614 mLayersRemoved = false;
1615 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001616 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001617 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001618 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001619 if (currentLayers.indexOf(layer) < 0) {
1620 // this layer is not visible anymore
1621 // TODO: we could traverse the tree from front to back and
1622 // compute the actual visible region
1623 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001624 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001625 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001626 Region(Rect(s.active.w, s.active.h)));
1627 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001630 }
1631
1632 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001633
1634 updateCursorAsync();
1635}
1636
1637void SurfaceFlinger::updateCursorAsync()
1638{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001639 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1640 auto& displayDevice = mDisplays[displayId];
1641 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001642 continue;
1643 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644
1645 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1646 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001647 }
1648 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001649}
1650
1651void SurfaceFlinger::commitTransaction()
1652{
1653 if (!mLayersPendingRemoval.isEmpty()) {
1654 // Notify removed layers now that they can't be drawn from
1655 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001656 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1657 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001658 mLayersPendingRemoval[i]->onRemoved();
1659 }
1660 mLayersPendingRemoval.clear();
1661 }
1662
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001663 // If this transaction is part of a window animation then the next frame
1664 // we composite should be considered an animation as well.
1665 mAnimCompositionPending = mAnimTransactionPending;
1666
Mathias Agopian4fec8732012-06-29 14:12:52 -07001667 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001668 mTransactionPending = false;
1669 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001670 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001671}
1672
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001673void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001674 const LayerVector& currentLayers, uint32_t layerStack,
1675 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001676{
Mathias Agopian841cde52012-03-01 15:44:37 -08001677 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001680 Region aboveOpaqueLayers;
1681 Region aboveCoveredLayers;
1682 Region dirty;
1683
Mathias Agopian87baae12012-07-31 12:38:26 -07001684 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001685
1686 size_t i = currentLayers.size();
1687 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001688 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001689
1690 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001691 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001692
Jesse Hall01e29052013-02-19 16:13:35 -08001693 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001694 if (s.layerStack != layerStack)
1695 continue;
1696
Mathias Agopianab028732010-03-16 16:41:46 -07001697 /*
1698 * opaqueRegion: area of a surface that is fully opaque.
1699 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001700 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001701
1702 /*
1703 * visibleRegion: area of a surface that is visible on screen
1704 * and not fully transparent. This is essentially the layer's
1705 * footprint minus the opaque regions above it.
1706 * Areas covered by a translucent surface are considered visible.
1707 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001708 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001709
1710 /*
1711 * coveredRegion: area of a surface that is covered by all
1712 * visible regions above it (which includes the translucent areas).
1713 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001714 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001715
Jesse Halla8026d22012-09-25 13:25:04 -07001716 /*
1717 * transparentRegion: area of a surface that is hinted to be completely
1718 * transparent. This is only used to tell when the layer has no visible
1719 * non-transparent regions and can be removed from the layer list. It
1720 * does not affect the visibleRegion of this layer or any layers
1721 * beneath it. The hint may not be correct if apps don't respect the
1722 * SurfaceView restrictions (which, sadly, some don't).
1723 */
1724 Region transparentRegion;
1725
Mathias Agopianab028732010-03-16 16:41:46 -07001726
1727 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001728 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001729 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001730 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001731 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001732 if (!visibleRegion.isEmpty()) {
1733 // Remove the transparent area from the visible region
1734 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001735 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001736 if (tr.preserveRects()) {
1737 // transform the transparent region
1738 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001739 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001740 // transformation too complex, can't do the
1741 // transparent region optimization.
1742 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001743 }
Mathias Agopianab028732010-03-16 16:41:46 -07001744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001745
Mathias Agopianab028732010-03-16 16:41:46 -07001746 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001747 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001748 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001749 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1750 // the opaque region is the layer's footprint
1751 opaqueRegion = visibleRegion;
1752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001753 }
1754 }
1755
Mathias Agopianab028732010-03-16 16:41:46 -07001756 // Clip the covered region to the visible region
1757 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1758
1759 // Update aboveCoveredLayers for next (lower) layer
1760 aboveCoveredLayers.orSelf(visibleRegion);
1761
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001762 // subtract the opaque region covered by the layers above us
1763 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001764
1765 // compute this layer's dirty region
1766 if (layer->contentDirty) {
1767 // we need to invalidate the whole region
1768 dirty = visibleRegion;
1769 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001770 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001771 layer->contentDirty = false;
1772 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001773 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001774 * the exposed region consists of two components:
1775 * 1) what's VISIBLE now and was COVERED before
1776 * 2) what's EXPOSED now less what was EXPOSED before
1777 *
1778 * note that (1) is conservative, we start with the whole
1779 * visible region but only keep what used to be covered by
1780 * something -- which mean it may have been exposed.
1781 *
1782 * (2) handles areas that were not covered by anything but got
1783 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001784 */
Mathias Agopianab028732010-03-16 16:41:46 -07001785 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001786 const Region oldVisibleRegion = layer->visibleRegion;
1787 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001788 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1789 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001790 }
1791 dirty.subtractSelf(aboveOpaqueLayers);
1792
1793 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001794 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795
Mathias Agopianab028732010-03-16 16:41:46 -07001796 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001798
Jesse Halla8026d22012-09-25 13:25:04 -07001799 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001800 layer->setVisibleRegion(visibleRegion);
1801 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001802 layer->setVisibleNonTransparentRegion(
1803 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 }
1805
Mathias Agopian87baae12012-07-31 12:38:26 -07001806 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807}
1808
Mathias Agopian87baae12012-07-31 12:38:26 -07001809void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1810 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001811 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001812 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1813 if (hw->getLayerStack() == layerStack) {
1814 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001815 }
1816 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001817}
1818
Dan Stoza6b9454d2014-11-07 16:00:59 -08001819bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821 ALOGV("handlePageFlip");
1822
Mathias Agopian4fec8732012-06-29 14:12:52 -07001823 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824
Mathias Agopian4fec8732012-06-29 14:12:52 -07001825 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001826 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001827 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001828
1829 // Store the set of layers that need updates. This set must not change as
1830 // buffers are being latched, as this could result in a deadlock.
1831 // Example: Two producers share the same command stream and:
1832 // 1.) Layer 0 is latched
1833 // 2.) Layer 0 gets a new frame
1834 // 2.) Layer 1 gets a new frame
1835 // 3.) Layer 1 is latched.
1836 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1837 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001838 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001839 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001840 if (layer->hasQueuedFrame()) {
1841 frameQueued = true;
1842 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001844 } else {
1845 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001846 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001847 } else {
1848 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001849 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001850 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001851 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001852 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001853 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001854 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001855 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001856 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001857
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001858 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001859
1860 // If we will need to wake up at some time in the future to deal with a
1861 // queued frame that shouldn't be displayed during this vsync period, wake
1862 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001864 signalLayerUpdate();
1865 }
1866
1867 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001869}
1870
Mathias Agopianad456f92011-01-13 17:53:01 -08001871void SurfaceFlinger::invalidateHwcGeometry()
1872{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001874}
1875
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001876
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001878 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001879{
Dan Stoza71433162014-02-04 16:22:36 -08001880 // We only need to actually compose the display if:
1881 // 1) It is being handled by hardware composer, which may need this to
1882 // keep its virtual display state machine in sync, or
1883 // 2) There is work to be done (the dirty region isn't empty)
1884 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1885 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001887 return;
1888 }
1889
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 ALOGV("doDisplayComposition");
1891
Mathias Agopian87baae12012-07-31 12:38:26 -07001892 Region dirtyRegion(inDirtyRegion);
1893
Mathias Agopianb8a55602009-06-26 19:06:36 -07001894 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001895 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001896
Mathias Agopian42977342012-08-05 00:40:46 -07001897 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001898 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001899 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1900 // takes a rectangle, we must make sure to update that whole
1901 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001902 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001903 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001904 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001905 // We need to redraw the rectangle that will be updated
1906 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001907 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001908 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001909 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001910 } else {
1911 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001912 dirtyRegion.set(hw->bounds());
1913 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001914 }
1915 }
1916
Alan Viverette9c5a3332013-09-12 20:04:35 -07001917 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001918 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001919 } else {
1920 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001921 mat4 colorMatrix = mColorMatrix;
1922 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001923 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001924 }
Dan Stozaf0087992014-10-20 15:46:09 -07001925 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001926 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001927 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001928 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001930 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001931 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001932
1933 // swap buffers (presentation)
1934 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001935}
1936
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937bool SurfaceFlinger::doComposeSurfaces(
1938 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001939{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 const auto hwcId = displayDevice->getHwcDisplayId();
1943 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1944 if (hasClientComposition) {
1945 ALOGV("hasClientComposition");
1946
1947 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001948 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001950 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1951 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1952 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1953 }
1954 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001955 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001956
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001957 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1959 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001960 // when using overlays, we assume a fully transparent framebuffer
1961 // NOTE: we could reduce how much we need to clear, for instance
1962 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001963 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001964 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001966 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001967 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001969
1970 // we remove the scissor part
1971 // we're left with the letterbox region
1972 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001974
1975 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001977
1978 // but limit it to the dirty region
1979 region.andSelf(dirty);
1980
Mathias Agopianb9494d52012-04-18 02:28:45 -07001981 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001982 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001983 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001985 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001986 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001987
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07001989 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001990 // scissor on the main display. It should never be needed
1991 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 const Rect& bounds(displayDevice->getBounds());
1993 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001994 if (scissor != bounds) {
1995 // scissor doesn't match the screen's dimensions, so we
1996 // need to clear everything outside of it and enable
1997 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001998
Mathias Agopianf45c5102012-10-24 16:29:17 -07001999 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 const uint32_t height = displayDevice->getHeight();
2001 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002002 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002003 }
2004 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002005 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002006
Mathias Agopian85d751c2012-08-29 16:59:24 -07002007 /*
2008 * and then, render the layers targeted at the framebuffer
2009 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002010
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ALOGV("Rendering client layers");
2012 const Transform& displayTransform = displayDevice->getTransform();
2013 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002014 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 bool firstLayer = true;
2016 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2017 const Region clip(dirty.intersect(
2018 displayTransform.transform(layer->visibleRegion)));
2019 ALOGV("Layer: %s", layer->getName().string());
2020 ALOGV(" Composition type: %s",
2021 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002022 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 switch (layer->getCompositionType(hwcId)) {
2024 case HWC2::Composition::Cursor:
2025 case HWC2::Composition::Device:
2026 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002027 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2029 layer->isOpaque(state) && (state.alpha == 1.0f)
2030 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031 // never clear the very first layer since we're
2032 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002034 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002035 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002036 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 case HWC2::Composition::Client: {
2038 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002039 break;
2040 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002042 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002043 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 } else {
2045 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002046 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002048 }
2049 } else {
2050 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002052 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002054 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002056 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002057 }
2058 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002059
2060 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002062 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063}
2064
Mathias Agopian3f844832013-08-07 21:24:32 -07002065void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002066 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002067 RenderEngine& engine(getRenderEngine());
2068 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069}
2070
Dan Stoza7d89d062015-04-30 13:29:25 -07002071status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002072 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002073 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002074 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002075{
Dan Stoza7d89d062015-04-30 13:29:25 -07002076 // add this layer to the current state list
2077 {
2078 Mutex::Autolock _l(mStateLock);
2079 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2080 return NO_MEMORY;
2081 }
2082 mCurrentState.layersSortedByZ.add(lbc);
2083 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2084 }
2085
Mathias Agopian96f08192010-06-02 23:28:45 -07002086 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002087 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002088
Dan Stoza7d89d062015-04-30 13:29:25 -07002089 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002090}
2091
Mathias Agopian3f844832013-08-07 21:24:32 -07002092status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002094 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002096 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002097 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002098 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099 return NO_ERROR;
2100 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002101 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102}
2103
Dan Stozac7014012014-02-14 15:03:43 -08002104uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002105 return android_atomic_release_load(&mTransactionFlags);
2106}
2107
Mathias Agopian3f844832013-08-07 21:24:32 -07002108uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2110}
2111
Mathias Agopian3f844832013-08-07 21:24:32 -07002112uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2114 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002115 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116 }
2117 return old;
2118}
2119
Mathias Agopian8b33f032012-07-24 20:43:54 -07002120void SurfaceFlinger::setTransactionState(
2121 const Vector<ComposerState>& state,
2122 const Vector<DisplayState>& displays,
2123 uint32_t flags)
2124{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002125 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002126 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002127 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002128
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002129 if (flags & eAnimation) {
2130 // For window updates that are part of an animation we must wait for
2131 // previous animation "frames" to be handled.
2132 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002133 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002134 if (CC_UNLIKELY(err != NO_ERROR)) {
2135 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002136 // caller after a few seconds.
2137 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2138 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002139 mAnimTransactionPending = false;
2140 break;
2141 }
2142 }
2143 }
2144
Mathias Agopiane57f2922012-08-09 16:29:12 -07002145 size_t count = displays.size();
2146 for (size_t i=0 ; i<count ; i++) {
2147 const DisplayState& s(displays[i]);
2148 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002149 }
2150
Mathias Agopiane57f2922012-08-09 16:29:12 -07002151 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002152 for (size_t i=0 ; i<count ; i++) {
2153 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002154 // Here we need to check that the interface we're given is indeed
2155 // one of our own. A malicious client could give us a NULL
2156 // IInterface, or one of its own or even one of our own but a
2157 // different type. All these situations would cause us to crash.
2158 //
2159 // NOTE: it would be better to use RTTI as we could directly check
2160 // that we have a Client*. however, RTTI is disabled in Android.
2161 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002162 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002163 if (binder != NULL) {
2164 String16 desc(binder->getInterfaceDescriptor());
2165 if (desc == ISurfaceComposerClient::descriptor) {
2166 sp<Client> client( static_cast<Client *>(s.client.get()) );
2167 transactionFlags |= setClientStateLocked(client, s.state);
2168 }
2169 }
2170 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002171 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002172
Robert Carr2a7dbb42016-05-24 11:41:28 -07002173 // If a synchronous transaction is explicitly requested without any changes,
2174 // force a transaction anyway. This can be used as a flush mechanism for
2175 // previous async transactions.
2176 if (transactionFlags == 0 && (flags & eSynchronous)) {
2177 transactionFlags = eTransactionNeeded;
2178 }
2179
Mathias Agopian386aa982011-11-07 21:58:03 -08002180 if (transactionFlags) {
2181 // this triggers the transaction
2182 setTransactionFlags(transactionFlags);
2183
2184 // if this is a synchronous transaction, wait for it to take effect
2185 // before returning.
2186 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002187 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002188 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002189 if (flags & eAnimation) {
2190 mAnimTransactionPending = true;
2191 }
2192 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002193 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2194 if (CC_UNLIKELY(err != NO_ERROR)) {
2195 // just in case something goes wrong in SF, return to the
2196 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002197 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2198 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002199 break;
2200 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202 }
2203}
2204
Mathias Agopiane57f2922012-08-09 16:29:12 -07002205uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2206{
Jesse Hall9a143922012-10-04 16:29:19 -07002207 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2208 if (dpyIdx < 0)
2209 return 0;
2210
Mathias Agopiane57f2922012-08-09 16:29:12 -07002211 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002212 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002213 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002214 const uint32_t what = s.what;
2215 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002216 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002217 disp.surface = s.surface;
2218 flags |= eDisplayTransactionNeeded;
2219 }
2220 }
2221 if (what & DisplayState::eLayerStackChanged) {
2222 if (disp.layerStack != s.layerStack) {
2223 disp.layerStack = s.layerStack;
2224 flags |= eDisplayTransactionNeeded;
2225 }
2226 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002227 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002228 if (disp.orientation != s.orientation) {
2229 disp.orientation = s.orientation;
2230 flags |= eDisplayTransactionNeeded;
2231 }
2232 if (disp.frame != s.frame) {
2233 disp.frame = s.frame;
2234 flags |= eDisplayTransactionNeeded;
2235 }
2236 if (disp.viewport != s.viewport) {
2237 disp.viewport = s.viewport;
2238 flags |= eDisplayTransactionNeeded;
2239 }
2240 }
Michael Lentine47e45402014-07-18 15:34:25 -07002241 if (what & DisplayState::eDisplaySizeChanged) {
2242 if (disp.width != s.width) {
2243 disp.width = s.width;
2244 flags |= eDisplayTransactionNeeded;
2245 }
2246 if (disp.height != s.height) {
2247 disp.height = s.height;
2248 flags |= eDisplayTransactionNeeded;
2249 }
2250 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002251 }
2252 return flags;
2253}
2254
2255uint32_t SurfaceFlinger::setClientStateLocked(
2256 const sp<Client>& client,
2257 const layer_state_t& s)
2258{
2259 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002260 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002261 if (layer != 0) {
2262 const uint32_t what = s.what;
Robert Carr82364e32016-05-15 11:27:47 -07002263 bool positionAppliesWithResize =
2264 what & layer_state_t::ePositionAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002265 if (what & layer_state_t::ePositionChanged) {
Robert Carr82364e32016-05-15 11:27:47 -07002266 if (layer->setPosition(s.x, s.y, !positionAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002267 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002268 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002269 }
2270 if (what & layer_state_t::eLayerChanged) {
2271 // NOTE: index needs to be calculated before we update the state
2272 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002273 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002274 mCurrentState.layersSortedByZ.removeAt(idx);
2275 mCurrentState.layersSortedByZ.add(layer);
2276 // we need traversal (state changed)
2277 // AND transaction (list changed)
2278 flags |= eTransactionNeeded|eTraversalNeeded;
2279 }
2280 }
2281 if (what & layer_state_t::eSizeChanged) {
2282 if (layer->setSize(s.w, s.h)) {
2283 flags |= eTraversalNeeded;
2284 }
2285 }
2286 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002288 flags |= eTraversalNeeded;
2289 }
2290 if (what & layer_state_t::eMatrixChanged) {
2291 if (layer->setMatrix(s.matrix))
2292 flags |= eTraversalNeeded;
2293 }
2294 if (what & layer_state_t::eTransparentRegionChanged) {
2295 if (layer->setTransparentRegionHint(s.transparentRegion))
2296 flags |= eTraversalNeeded;
2297 }
Dan Stoza23116082015-06-18 14:58:39 -07002298 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002299 if (layer->setFlags(s.flags, s.mask))
2300 flags |= eTraversalNeeded;
2301 }
2302 if (what & layer_state_t::eCropChanged) {
2303 if (layer->setCrop(s.crop))
2304 flags |= eTraversalNeeded;
2305 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002306 if (what & layer_state_t::eFinalCropChanged) {
2307 if (layer->setFinalCrop(s.finalCrop))
2308 flags |= eTraversalNeeded;
2309 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002310 if (what & layer_state_t::eLayerStackChanged) {
2311 // NOTE: index needs to be calculated before we update the state
2312 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002313 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002314 mCurrentState.layersSortedByZ.removeAt(idx);
2315 mCurrentState.layersSortedByZ.add(layer);
2316 // we need traversal (state changed)
2317 // AND transaction (list changed)
2318 flags |= eTransactionNeeded|eTraversalNeeded;
2319 }
2320 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002321 if (what & layer_state_t::eDeferTransaction) {
2322 layer->deferTransactionUntil(s.handle, s.frameNumber);
2323 // We don't trigger a traversal here because if no other state is
2324 // changed, we don't want this to cause any more work
2325 }
Robert Carrc3574f72016-03-24 12:19:32 -07002326 if (what & layer_state_t::eOverrideScalingModeChanged) {
2327 layer->setOverrideScalingMode(s.overrideScalingMode);
2328 // We don't trigger a traversal here because if no other state is
2329 // changed, we don't want this to cause any more work
2330 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002331 }
2332 return flags;
2333}
2334
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002335status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002336 const String8& name,
2337 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002338 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2339 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002341 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002342 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002343 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002344 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002345 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002346 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002347
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002348 status_t result = NO_ERROR;
2349
2350 sp<Layer> layer;
2351
Mathias Agopian3165cc22012-08-08 19:42:09 -07002352 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2353 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002354 result = createNormalLayer(client,
2355 name, w, h, flags, format,
2356 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002358 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002359 result = createDimLayer(client,
2360 name, w, h, flags,
2361 handle, gbp, &layer);
2362 break;
2363 default:
2364 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365 break;
2366 }
2367
Dan Stoza7d89d062015-04-30 13:29:25 -07002368 if (result != NO_ERROR) {
2369 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002371
2372 result = addClientLayer(client, *handle, *gbp, layer);
2373 if (result != NO_ERROR) {
2374 return result;
2375 }
2376
2377 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002378 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379}
2380
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002381status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2382 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2383 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384{
2385 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002386 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 case PIXEL_FORMAT_TRANSPARENT:
2388 case PIXEL_FORMAT_TRANSLUCENT:
2389 format = PIXEL_FORMAT_RGBA_8888;
2390 break;
2391 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002392 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 break;
2394 }
2395
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002396 *outLayer = new Layer(this, client, name, w, h, flags);
2397 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2398 if (err == NO_ERROR) {
2399 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002400 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002402
2403 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2404 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405}
2406
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002407status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2408 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2409 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002411 *outLayer = new LayerDim(this, client, name, w, h, flags);
2412 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002413 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002414 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002415}
2416
Mathias Agopianac9fa422013-02-11 16:40:36 -08002417status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418{
Mathias Agopian67106042013-03-14 19:18:13 -07002419 // called by the window manager when it wants to remove a Layer
2420 status_t err = NO_ERROR;
2421 sp<Layer> l(client->getLayerUser(handle));
2422 if (l != NULL) {
2423 err = removeLayer(l);
2424 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2425 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002426 }
2427 return err;
2428}
2429
Mathias Agopian13127d82013-03-05 17:47:11 -08002430status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002431{
Mathias Agopian67106042013-03-14 19:18:13 -07002432 // called by ~LayerCleaner() when all references to the IBinder (handle)
2433 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002434 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002435 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002436 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002437 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002438 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002439 "error removing layer=%p (%s)", l.get(), strerror(-err));
2440 }
2441 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442}
2443
Mathias Agopianb60314a2012-04-10 22:09:54 -07002444// ---------------------------------------------------------------------------
2445
Andy McFadden13a082e2012-08-24 10:16:42 -07002446void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002447 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002448 Vector<ComposerState> state;
2449 Vector<DisplayState> displays;
2450 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002451 d.what = DisplayState::eDisplayProjectionChanged |
2452 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002453 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002454 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002455 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002456 d.frame.makeInvalid();
2457 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002458 d.width = 0;
2459 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002460 displays.add(d);
2461 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002462 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002463
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2465 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002466 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002467}
2468
2469void SurfaceFlinger::initializeDisplays() {
2470 class MessageScreenInitialized : public MessageBase {
2471 SurfaceFlinger* flinger;
2472 public:
2473 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2474 virtual bool handler() {
2475 flinger->onInitializeDisplays();
2476 return true;
2477 }
2478 };
2479 sp<MessageBase> msg = new MessageScreenInitialized(this);
2480 postMessageAsync(msg); // we may be called from main thread, use async message
2481}
2482
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002483void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2484 int mode) {
2485 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2486 this);
2487 int32_t type = hw->getDisplayType();
2488 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002489
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002490 if (mode == currentMode) {
2491 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002492 return;
2493 }
2494
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002495 hw->setPowerMode(mode);
2496 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2497 ALOGW("Trying to set power mode for virtual display");
2498 return;
2499 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002500
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002501 if (currentMode == HWC_POWER_MODE_OFF) {
2502 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002503 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2504 // FIXME: eventthread only knows about the main display right now
2505 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002506 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002507 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002509 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002510 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002511 repaintEverything();
2512 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002513 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002514 disableHardwareVsync(true); // also cancels any in-progress resync
2515
Mathias Agopiancde87a32012-09-13 14:09:01 -07002516 // FIXME: eventthread only knows about the main display right now
2517 mEventThread->onScreenReleased();
2518 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002519
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002520 getHwComposer().setPowerMode(type, mode);
2521 mVisibleRegionsDirty = true;
2522 // from this point on, SF will stop drawing on this display
2523 } else {
2524 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002525 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002526}
2527
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002528void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2529 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002530 SurfaceFlinger& mFlinger;
2531 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002532 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002533 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002534 MessageSetPowerMode(SurfaceFlinger& flinger,
2535 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2536 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002537 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002538 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002539 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002540 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002541 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002542 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002543 ALOGW("Attempt to set power mode = %d for virtual display",
2544 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002545 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002546 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002547 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002548 return true;
2549 }
2550 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002551 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002552 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002553}
2554
2555// ---------------------------------------------------------------------------
2556
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2558{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002560
Mathias Agopianbd115332013-04-18 16:41:04 -07002561 IPCThreadState* ipc = IPCThreadState::self();
2562 const int pid = ipc->getCallingPid();
2563 const int uid = ipc->getCallingUid();
2564 if ((uid != AID_SHELL) &&
2565 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002566 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002567 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002569 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002570 // (this would indicate SF is stuck, but we want to be able to
2571 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002572 status_t err = mStateLock.timedLock(s2ns(1));
2573 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002574 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002575 result.appendFormat(
2576 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2577 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002578 }
2579
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002580 bool dumpAll = true;
2581 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002582 size_t numArgs = args.size();
2583 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002584 if ((index < numArgs) &&
2585 (args[index] == String16("--list"))) {
2586 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002587 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002588 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002589 }
2590
2591 if ((index < numArgs) &&
2592 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002593 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002594 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002595 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002596 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002597
2598 if ((index < numArgs) &&
2599 (args[index] == String16("--latency-clear"))) {
2600 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002601 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002602 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002603 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002604
2605 if ((index < numArgs) &&
2606 (args[index] == String16("--dispsync"))) {
2607 index++;
2608 mPrimaryDispSync.dump(result);
2609 dumpAll = false;
2610 }
Dan Stozab90cf072015-03-05 11:05:59 -08002611
2612 if ((index < numArgs) &&
2613 (args[index] == String16("--static-screen"))) {
2614 index++;
2615 dumpStaticScreenStats(result);
2616 dumpAll = false;
2617 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002618
2619 if ((index < numArgs) &&
2620 (args[index] == String16("--fences"))) {
2621 index++;
2622 mFenceTracker.dump(&result);
2623 dumpAll = false;
2624 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002626
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002627 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002628 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002629 }
2630
Mathias Agopian9795c422009-08-26 16:36:26 -07002631 if (locked) {
2632 mStateLock.unlock();
2633 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634 }
2635 write(fd, result.string(), result.size());
2636 return NO_ERROR;
2637}
2638
Dan Stozac7014012014-02-14 15:03:43 -08002639void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2640 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002641{
2642 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2643 const size_t count = currentLayers.size();
2644 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002645 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002646 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002647 }
2648}
2649
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002650void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002651 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002652{
2653 String8 name;
2654 if (index < args.size()) {
2655 name = String8(args[index]);
2656 index++;
2657 }
2658
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2660 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002661 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002662
2663 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002664 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002665 } else {
2666 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2667 const size_t count = currentLayers.size();
2668 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002669 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002670 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002671 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002672 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002673 }
2674 }
2675}
2676
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002677void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002678 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002679{
2680 String8 name;
2681 if (index < args.size()) {
2682 name = String8(args[index]);
2683 index++;
2684 }
2685
2686 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2687 const size_t count = currentLayers.size();
2688 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002689 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002690 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002691 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002692 }
2693 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002694
Svetoslavd85084b2014-03-20 10:28:31 -07002695 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002696}
2697
Jamie Gennis6547ff42013-07-16 20:12:42 -07002698// This should only be called from the main thread. Otherwise it would need
2699// the lock and should use mCurrentState rather than mDrawingState.
2700void SurfaceFlinger::logFrameStats() {
2701 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2702 const size_t count = drawingLayers.size();
2703 for (size_t i=0 ; i<count ; i++) {
2704 const sp<Layer>& layer(drawingLayers[i]);
2705 layer->logFrameStats();
2706 }
2707
2708 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2709}
2710
Andy McFadden4803b742012-09-24 19:07:20 -07002711/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2712{
2713 static const char* config =
2714 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002715#ifdef HAS_CONTEXT_PRIORITY
2716 " HAS_CONTEXT_PRIORITY"
2717#endif
2718#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2719 " NEVER_DEFAULT_TO_ASYNC_MODE"
2720#endif
2721#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2722 " TARGET_DISABLE_TRIPLE_BUFFERING"
2723#endif
2724 "]";
2725 result.append(config);
2726}
2727
Dan Stozab90cf072015-03-05 11:05:59 -08002728void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2729{
2730 result.appendFormat("Static screen stats:\n");
2731 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2732 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2733 float percent = 100.0f *
2734 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2735 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2736 b + 1, bucketTimeSec, percent);
2737 }
2738 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2739 float percent = 100.0f *
2740 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2741 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2742 NUM_BUCKETS - 1, bucketTimeSec, percent);
2743}
2744
Dan Stozae77c7662016-05-13 11:37:28 -07002745void SurfaceFlinger::recordBufferingStats(const char* layerName,
2746 std::vector<OccupancyTracker::Segment>&& history) {
2747 Mutex::Autolock lock(mBufferingStatsMutex);
2748 auto& stats = mBufferingStats[layerName];
2749 for (const auto& segment : history) {
2750 if (!segment.usedThirdBuffer) {
2751 stats.twoBufferTime += segment.totalTime;
2752 }
2753 if (segment.occupancyAverage < 1.0f) {
2754 stats.doubleBufferedTime += segment.totalTime;
2755 } else if (segment.occupancyAverage < 2.0f) {
2756 stats.tripleBufferedTime += segment.totalTime;
2757 }
2758 ++stats.numSegments;
2759 stats.totalTime += segment.totalTime;
2760 }
2761}
2762
2763void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2764 result.append("Buffering stats:\n");
2765 result.append(" [Layer name] <Active time> <Two buffer> "
2766 "<Double buffered> <Triple buffered>\n");
2767 Mutex::Autolock lock(mBufferingStatsMutex);
2768 typedef std::tuple<std::string, float, float, float> BufferTuple;
2769 std::map<float, BufferTuple, std::greater<float>> sorted;
2770 for (const auto& statsPair : mBufferingStats) {
2771 const char* name = statsPair.first.c_str();
2772 const BufferingStats& stats = statsPair.second;
2773 if (stats.numSegments == 0) {
2774 continue;
2775 }
2776 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2777 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2778 stats.totalTime;
2779 float doubleBufferRatio = static_cast<float>(
2780 stats.doubleBufferedTime) / stats.totalTime;
2781 float tripleBufferRatio = static_cast<float>(
2782 stats.tripleBufferedTime) / stats.totalTime;
2783 sorted.insert({activeTime, {name, twoBufferRatio,
2784 doubleBufferRatio, tripleBufferRatio}});
2785 }
2786 for (const auto& sortedPair : sorted) {
2787 float activeTime = sortedPair.first;
2788 const BufferTuple& values = sortedPair.second;
2789 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2790 std::get<0>(values).c_str(), activeTime,
2791 std::get<1>(values), std::get<2>(values),
2792 std::get<3>(values));
2793 }
2794 result.append("\n");
2795}
2796
2797
Mathias Agopian74d211a2013-04-22 16:55:35 +02002798void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2799 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002800{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002801 bool colorize = false;
2802 if (index < args.size()
2803 && (args[index] == String16("--color"))) {
2804 colorize = true;
2805 index++;
2806 }
2807
2808 Colorizer colorizer(colorize);
2809
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002810 // figure out if we're stuck somewhere
2811 const nsecs_t now = systemTime();
2812 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2813 const nsecs_t inTransaction(mDebugInTransaction);
2814 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2815 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2816
2817 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002818 * Dump library configuration.
2819 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002820
2821 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002822 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002823 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002824 appendSfConfigString(result);
2825 appendUiConfigString(result);
2826 appendGuiConfigString(result);
2827 result.append("\n");
2828
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002829 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002830 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002831 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002832 result.append(SyncFeatures::getInstance().toString());
2833 result.append("\n");
2834
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2836
Andy McFadden41d67d72014-04-25 16:58:34 -07002837 colorizer.bold(result);
2838 result.append("DispSync configuration: ");
2839 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002840 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2841 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2843 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002844 result.append("\n");
2845
Dan Stozab90cf072015-03-05 11:05:59 -08002846 // Dump static screen stats
2847 result.append("\n");
2848 dumpStaticScreenStats(result);
2849 result.append("\n");
2850
Dan Stozae77c7662016-05-13 11:37:28 -07002851 dumpBufferingStats(result);
2852
Andy McFadden4803b742012-09-24 19:07:20 -07002853 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002854 * Dump the visible layer list
2855 */
2856 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2857 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002858 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002859 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002860 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002861 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002862 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002863 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002864 }
2865
2866 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002867 * Dump Display state
2868 */
2869
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002870 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002871 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002872 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002873 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2874 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002875 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002876 }
2877
2878 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002879 * Dump SurfaceFlinger global state
2880 */
2881
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002882 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002883 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002884 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002885
Mathias Agopian888c8222012-08-04 21:10:38 -07002886 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002887 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002888
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002889 colorizer.bold(result);
2890 result.appendFormat("EGL implementation : %s\n",
2891 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2892 colorizer.reset(result);
2893 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002894 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002895
Mathias Agopian875d8e12013-06-07 15:35:48 -07002896 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002897
Mathias Agopian42977342012-08-05 00:40:46 -07002898 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002899 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2900 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002901 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002902 " last eglSwapBuffers() time: %f us\n"
2903 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002904 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002905 " refresh-rate : %f fps\n"
2906 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002907 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002908 " gpu_to_cpu_unsupported : %d\n"
2909 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002910 mLastSwapBufferTime/1000.0,
2911 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002912 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 1e9 / activeConfig->getVsyncPeriod(),
2914 activeConfig->getDpiX(),
2915 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002916 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002917
Mathias Agopian74d211a2013-04-22 16:55:35 +02002918 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002919 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002920
Mathias Agopian74d211a2013-04-22 16:55:35 +02002921 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002922 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002923
2924 /*
2925 * VSYNC state
2926 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002927 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002928
2929 /*
2930 * Dump HWComposer state
2931 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002932 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002933 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002934 colorizer.reset(result);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2936 mHasColorMatrix;
2937 result.appendFormat(" h/w composer %s\n",
2938 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002939 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002940
2941 /*
2942 * Dump gralloc state
2943 */
2944 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2945 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002946}
2947
Mathias Agopian13127d82013-03-05 17:47:11 -08002948const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002949SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002950 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002951 wp<IBinder> dpy;
2952 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2953 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2954 dpy = mDisplays.keyAt(i);
2955 break;
2956 }
2957 }
2958 if (dpy == NULL) {
2959 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2960 // Just use the primary display so we have something to return
2961 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2962 }
2963 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002964}
2965
Keun young Park63f165f2012-08-31 10:53:36 -07002966bool SurfaceFlinger::startDdmConnection()
2967{
2968 void* libddmconnection_dso =
2969 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2970 if (!libddmconnection_dso) {
2971 return false;
2972 }
2973 void (*DdmConnection_start)(const char* name);
2974 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002975 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002976 if (!DdmConnection_start) {
2977 dlclose(libddmconnection_dso);
2978 return false;
2979 }
2980 (*DdmConnection_start)(getServiceName());
2981 return true;
2982}
2983
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984status_t SurfaceFlinger::onTransact(
2985 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2986{
2987 switch (code) {
2988 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002989 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002990 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002992 case CLEAR_ANIMATION_FRAME_STATS:
2993 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002994 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002995 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 {
2997 // codes that require permission check
2998 IPCThreadState* ipc = IPCThreadState::self();
2999 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003000 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003001 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003002 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003003 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003004 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3005 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003007 break;
3008 }
3009 case CAPTURE_SCREEN:
3010 {
3011 // codes that require permission check
3012 IPCThreadState* ipc = IPCThreadState::self();
3013 const int pid = ipc->getCallingPid();
3014 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003015 if ((uid != AID_GRAPHICS) &&
3016 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003017 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003018 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3019 return PERMISSION_DENIED;
3020 }
3021 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003022 }
3023 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3026 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003027 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003028 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003029 IPCThreadState* ipc = IPCThreadState::self();
3030 const int pid = ipc->getCallingPid();
3031 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003032 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003033 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034 return PERMISSION_DENIED;
3035 }
3036 int n;
3037 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003038 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003039 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 return NO_ERROR;
3041 case 1002: // SHOW_UPDATES
3042 n = data.readInt32();
3043 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003044 invalidateHwcGeometry();
3045 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003048 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003049 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003051 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003052 setTransactionFlags(
3053 eTransactionNeeded|
3054 eDisplayTransactionNeeded|
3055 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003056 return NO_ERROR;
3057 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003058 case 1006:{ // send empty update
3059 signalRefresh();
3060 return NO_ERROR;
3061 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003062 case 1008: // toggle use of hw composer
3063 n = data.readInt32();
3064 mDebugDisableHWC = n ? 1 : 0;
3065 invalidateHwcGeometry();
3066 repaintEverything();
3067 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003068 case 1009: // toggle use of transform hint
3069 n = data.readInt32();
3070 mDebugDisableTransformHint = n ? 1 : 0;
3071 invalidateHwcGeometry();
3072 repaintEverything();
3073 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003075 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 reply->writeInt32(0);
3077 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003078 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003079 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 return NO_ERROR;
3081 case 1013: {
3082 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003083 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3084 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003085 return NO_ERROR;
3086 }
3087 case 1014: {
3088 // daltonize
3089 n = data.readInt32();
3090 switch (n % 10) {
3091 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3092 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3093 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3094 }
3095 if (n >= 10) {
3096 mDaltonizer.setMode(Daltonizer::correction);
3097 } else {
3098 mDaltonizer.setMode(Daltonizer::simulation);
3099 }
3100 mDaltonize = n > 0;
3101 invalidateHwcGeometry();
3102 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003103 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003105 case 1015: {
3106 // apply a color matrix
3107 n = data.readInt32();
3108 mHasColorMatrix = n ? 1 : 0;
3109 if (n) {
3110 // color matrix is sent as mat3 matrix followed by vec3
3111 // offset, then packed into a mat4 where the last row is
3112 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003113 for (size_t i = 0 ; i < 4; i++) {
3114 for (size_t j = 0; j < 4; j++) {
3115 mColorMatrix[i][j] = data.readFloat();
3116 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003117 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003118 } else {
3119 mColorMatrix = mat4();
3120 }
3121 invalidateHwcGeometry();
3122 repaintEverything();
3123 return NO_ERROR;
3124 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003125 // This is an experimental interface
3126 // Needs to be shifted to proper binder interface when we productize
3127 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003128 n = data.readInt32();
3129 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003130 return NO_ERROR;
3131 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003132 case 1017: {
3133 n = data.readInt32();
3134 mForceFullDamage = static_cast<bool>(n);
3135 return NO_ERROR;
3136 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003137 case 1018: { // Modify Choreographer's phase offset
3138 n = data.readInt32();
3139 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3140 return NO_ERROR;
3141 }
3142 case 1019: { // Modify SurfaceFlinger's phase offset
3143 n = data.readInt32();
3144 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3145 return NO_ERROR;
3146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 }
3148 }
3149 return err;
3150}
3151
Mathias Agopian53331da2011-08-22 21:44:41 -07003152void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003153 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003154 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003155}
3156
Mathias Agopian59119e62010-10-11 12:37:43 -07003157// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003158// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003159// ---------------------------------------------------------------------------
3160
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003161/* The code below is here to handle b/8734824
3162 *
3163 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003164 * from the surfaceflinger thread to the calling binder thread, where they
3165 * are executed. This allows the calling thread in the calling process to be
3166 * reused and not depend on having "enough" binder threads to handle the
3167 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003168 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003169class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003170 /* Parts of GraphicProducerWrapper are run on two different threads,
3171 * communicating by sending messages via Looper but also by shared member
3172 * data. Coherence maintenance is subtle and in places implicit (ugh).
3173 *
3174 * Don't rely on Looper's sendMessage/handleMessage providing
3175 * release/acquire semantics for any data not actually in the Message.
3176 * Data going from surfaceflinger to binder threads needs to be
3177 * synchronized explicitly.
3178 *
3179 * Barrier open/wait do provide release/acquire semantics. This provides
3180 * implicit synchronization for data coming back from binder to
3181 * surfaceflinger threads.
3182 */
3183
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003184 sp<IGraphicBufferProducer> impl;
3185 sp<Looper> looper;
3186 status_t result;
3187 bool exitPending;
3188 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003189 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003190 uint32_t code;
3191 Parcel const* data;
3192 Parcel* reply;
3193
3194 enum {
3195 MSG_API_CALL,
3196 MSG_EXIT
3197 };
3198
3199 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003200 * Called on surfaceflinger thread. This is called by our "fake"
3201 * BpGraphicBufferProducer. We package the data and reply Parcel and
3202 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003203 */
3204 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003205 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003206 this->code = code;
3207 this->data = &data;
3208 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003209 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003210 // if we've exited, we run the message synchronously right here.
3211 // note (JH): as far as I can tell from looking at the code, this
3212 // never actually happens. if it does, i'm not sure if it happens
3213 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003214 handleMessage(Message(MSG_API_CALL));
3215 } else {
3216 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003217 // Prevent stores to this->{code, data, reply} from being
3218 // reordered later than the construction of Message.
3219 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003220 looper->sendMessage(this, Message(MSG_API_CALL));
3221 barrier.wait();
3222 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003223 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003224 }
3225
3226 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003227 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003228 * call the real BpGraphicBufferProducer.
3229 */
3230 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003231 int what = message.what;
3232 // Prevent reads below from happening before the read from Message
3233 atomic_thread_fence(memory_order_acquire);
3234 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003235 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003236 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003237 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003238 exitRequested = true;
3239 }
3240 }
3241
3242public:
Jesse Hallb154c422014-07-13 12:47:02 -07003243 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3244 : impl(impl),
3245 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003246 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003247 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003248 exitRequested(false),
3249 code(0),
3250 data(NULL),
3251 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003252 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003253
Jesse Hallb154c422014-07-13 12:47:02 -07003254 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003255 status_t waitForResponse() {
3256 do {
3257 looper->pollOnce(-1);
3258 } while (!exitRequested);
3259 return result;
3260 }
3261
Jesse Hallb154c422014-07-13 12:47:02 -07003262 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003263 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003264 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003265 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003266 // Ensure this->result is visible to the binder thread before it
3267 // handles the message.
3268 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003269 looper->sendMessage(this, Message(MSG_EXIT));
3270 }
3271};
3272
3273
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003274status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3275 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003276 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003277 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003278 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003279
3280 if (CC_UNLIKELY(display == 0))
3281 return BAD_VALUE;
3282
3283 if (CC_UNLIKELY(producer == 0))
3284 return BAD_VALUE;
3285
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003286 // if we have secure windows on this display, never allow the screen capture
3287 // unless the producer interface is local (i.e.: we can take a screenshot for
3288 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003289 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003290
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003291 // Convert to surfaceflinger's internal rotation type.
3292 Transform::orientation_flags rotationFlags;
3293 switch (rotation) {
3294 case ISurfaceComposer::eRotateNone:
3295 rotationFlags = Transform::ROT_0;
3296 break;
3297 case ISurfaceComposer::eRotate90:
3298 rotationFlags = Transform::ROT_90;
3299 break;
3300 case ISurfaceComposer::eRotate180:
3301 rotationFlags = Transform::ROT_180;
3302 break;
3303 case ISurfaceComposer::eRotate270:
3304 rotationFlags = Transform::ROT_270;
3305 break;
3306 default:
3307 rotationFlags = Transform::ROT_0;
3308 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3309 break;
3310 }
3311
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003312 class MessageCaptureScreen : public MessageBase {
3313 SurfaceFlinger* flinger;
3314 sp<IBinder> display;
3315 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003316 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003317 uint32_t reqWidth, reqHeight;
3318 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003319 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003320 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003321 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003322 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003323 public:
3324 MessageCaptureScreen(SurfaceFlinger* flinger,
3325 const sp<IBinder>& display,
3326 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003327 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003328 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003329 bool useIdentityTransform,
3330 Transform::orientation_flags rotation,
3331 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003332 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003333 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003334 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003335 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003336 rotation(rotation), result(PERMISSION_DENIED),
3337 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003338 {
3339 }
3340 status_t getResult() const {
3341 return result;
3342 }
3343 virtual bool handler() {
3344 Mutex::Autolock _l(flinger->mStateLock);
3345 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003346 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003347 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003348 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003349 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003350 return true;
3351 }
3352 };
3353
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003354 // this creates a "fake" BBinder which will serve as a "fake" remote
3355 // binder to receive the marshaled calls and forward them to the
3356 // real remote (a BpGraphicBufferProducer)
3357 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3358
3359 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3360 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003361 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003362 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003363 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003364 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003365
3366 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003367 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003368 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003369 }
3370 return res;
3371}
3372
Mathias Agopian180f10d2013-04-10 22:55:41 -07003373
3374void SurfaceFlinger::renderScreenImplLocked(
3375 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003376 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003377 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003378 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003379{
3380 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003381 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003382
3383 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003384 const int32_t hw_w = hw->getWidth();
3385 const int32_t hw_h = hw->getHeight();
3386 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003387 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003388
Dan Stozac1879002014-05-22 15:59:05 -07003389 // if a default or invalid sourceCrop is passed in, set reasonable values
3390 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3391 !sourceCrop.isValid()) {
3392 sourceCrop.setLeftTop(Point(0, 0));
3393 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3394 }
3395
3396 // ensure that sourceCrop is inside screen
3397 if (sourceCrop.left < 0) {
3398 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3399 }
Dan Stozabe31f442014-06-11 11:20:54 -07003400 if (sourceCrop.right > hw_w) {
3401 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003402 }
3403 if (sourceCrop.top < 0) {
3404 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3405 }
Dan Stozabe31f442014-06-11 11:20:54 -07003406 if (sourceCrop.bottom > hw_h) {
3407 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003408 }
3409
Mathias Agopian180f10d2013-04-10 22:55:41 -07003410 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003411 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003412
3413 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003414 engine.setViewportAndProjection(
3415 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003416 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003417
3418 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003419 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003420
3421 const LayerVector& layers( mDrawingState.layersSortedByZ );
3422 const size_t count = layers.size();
3423 for (size_t i=0 ; i<count ; ++i) {
3424 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003425 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003426 if (state.layerStack == hw->getLayerStack()) {
3427 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3428 if (layer->isVisible()) {
3429 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003430 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003431 if (filtering) layer->setFiltering(false);
3432 }
3433 }
3434 }
3435 }
3436
Mathias Agopian931bda12013-08-28 18:11:46 -07003437 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003438}
3439
3440
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003441status_t SurfaceFlinger::captureScreenImplLocked(
3442 const sp<const DisplayDevice>& hw,
3443 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003444 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003445 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003446 bool useIdentityTransform, Transform::orientation_flags rotation,
3447 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003448{
3449 ATRACE_CALL();
3450
Mathias Agopian180f10d2013-04-10 22:55:41 -07003451 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003452 uint32_t hw_w = hw->getWidth();
3453 uint32_t hw_h = hw->getHeight();
3454
3455 if (rotation & Transform::ROT_90) {
3456 std::swap(hw_w, hw_h);
3457 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003458
Mathias Agopian180f10d2013-04-10 22:55:41 -07003459 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3460 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3461 reqWidth, reqHeight, hw_w, hw_h);
3462 return BAD_VALUE;
3463 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003464
Mathias Agopian180f10d2013-04-10 22:55:41 -07003465 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3466 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3467
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003468 bool secureLayerIsVisible = false;
3469 const LayerVector& layers(mDrawingState.layersSortedByZ);
3470 const size_t count = layers.size();
3471 for (size_t i = 0 ; i < count ; ++i) {
3472 const sp<Layer>& layer(layers[i]);
3473 const Layer::State& state(layer->getDrawingState());
3474 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3475 state.z <= maxLayerZ && layer->isVisible() &&
3476 layer->isSecure()) {
3477 secureLayerIsVisible = true;
3478 }
3479 }
3480
3481 if (!isLocalScreenshot && secureLayerIsVisible) {
3482 ALOGW("FB is protected: PERMISSION_DENIED");
3483 return PERMISSION_DENIED;
3484 }
3485
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003486 // create a surface (because we're a producer, and we need to
3487 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003488 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003489 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003490
Michael Lentine5a16a622015-05-21 13:48:24 -07003491 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3492 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003493 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3494 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003495
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003496 int err = 0;
3497 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003498 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003499 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3500 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003501
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003502 if (err == NO_ERROR) {
3503 ANativeWindowBuffer* buffer;
3504 /* TODO: Once we have the sync framework everywhere this can use
3505 * server-side waits on the fence that dequeueBuffer returns.
3506 */
3507 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3508 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003509 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003510 // create an EGLImage from the buffer so we can later
3511 // turn it into a texture
3512 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3513 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3514 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003515 // this binds the given EGLImage as a framebuffer for the
3516 // duration of this scope.
3517 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3518 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003519 // this will in fact render into our dequeued buffer
3520 // via an FBO, which means we didn't have to create
3521 // an EGLSurface and therefore we're not
3522 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003523 renderScreenImplLocked(
3524 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3525 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003526
Riley Andrews86639902014-08-15 12:27:24 -07003527 // Attempt to create a sync khr object that can produce a sync point. If that
3528 // isn't available, create a non-dupable sync object in the fallback path and
3529 // wait on it directly.
3530 EGLSyncKHR sync;
3531 if (!DEBUG_SCREENSHOTS) {
3532 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003533 // native fence fd will not be populated until flush() is done.
3534 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003535 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003536 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003537 }
Riley Andrews86639902014-08-15 12:27:24 -07003538 if (sync != EGL_NO_SYNC_KHR) {
3539 // get the sync fd
3540 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3541 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3542 ALOGW("captureScreen: failed to dup sync khr object");
3543 syncFd = -1;
3544 }
3545 eglDestroySyncKHR(mEGLDisplay, sync);
3546 } else {
3547 // fallback path
3548 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3549 if (sync != EGL_NO_SYNC_KHR) {
3550 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3551 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3552 EGLint eglErr = eglGetError();
3553 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3554 ALOGW("captureScreen: fence wait timed out");
3555 } else {
3556 ALOGW_IF(eglErr != EGL_SUCCESS,
3557 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3558 }
3559 eglDestroySyncKHR(mEGLDisplay, sync);
3560 } else {
3561 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3562 }
3563 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003564 if (DEBUG_SCREENSHOTS) {
3565 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3566 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3567 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3568 hw, minLayerZ, maxLayerZ);
3569 delete [] pixels;
3570 }
3571
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003572 } else {
3573 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3574 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003575 window->cancelBuffer(window, buffer, syncFd);
3576 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003577 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003578 // destroy our image
3579 eglDestroyImageKHR(mEGLDisplay, image);
3580 } else {
3581 result = BAD_VALUE;
3582 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003583 if (buffer) {
3584 // queueBuffer takes ownership of syncFd
3585 result = window->queueBuffer(window, buffer, syncFd);
3586 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003587 }
3588 } else {
3589 result = BAD_VALUE;
3590 }
3591 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3592 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003593
Mathias Agopian74c40c02010-09-29 13:02:36 -07003594 return result;
3595}
3596
Mathias Agopiand5556842013-09-19 17:08:37 -07003597void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3598 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003599 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003600 for (size_t y=0 ; y<h ; y++) {
3601 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3602 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003603 if (p[x] != 0xFF000000) return;
3604 }
3605 }
3606 ALOGE("*** we just took a black screenshot ***\n"
3607 "requested minz=%d, maxz=%d, layerStack=%d",
3608 minLayerZ, maxLayerZ, hw->getLayerStack());
3609 const LayerVector& layers( mDrawingState.layersSortedByZ );
3610 const size_t count = layers.size();
3611 for (size_t i=0 ; i<count ; ++i) {
3612 const sp<Layer>& layer(layers[i]);
3613 const Layer::State& state(layer->getDrawingState());
3614 const bool visible = (state.layerStack == hw->getLayerStack())
3615 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3616 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003617 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003618 visible ? '+' : '-',
3619 i, layer->getName().string(), state.layerStack, state.z,
3620 layer->isVisible(), state.flags, state.alpha);
3621 }
3622 }
3623}
3624
Pablo Ceballosce796e72016-02-04 19:10:51 -08003625bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3626 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3627 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3628}
3629
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003630// ---------------------------------------------------------------------------
3631
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003632SurfaceFlinger::LayerVector::LayerVector() {
3633}
3634
3635SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003636 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003637}
3638
3639int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3640 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003641{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003642 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003643 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3644 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003645
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003646 uint32_t ls = l->getCurrentState().layerStack;
3647 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003648 if (ls != rs)
3649 return ls - rs;
3650
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003651 uint32_t lz = l->getCurrentState().z;
3652 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003653 if (lz != rz)
3654 return lz - rz;
3655
3656 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003657}
3658
3659// ---------------------------------------------------------------------------
3660
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003661SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003662 : type(DisplayDevice::DISPLAY_ID_INVALID),
3663 layerStack(DisplayDevice::NO_LAYER_STACK),
3664 orientation(0),
3665 width(0),
3666 height(0),
3667 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003668}
3669
Pablo Ceballos53390e12015-08-04 11:25:59 -07003670SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3671 DisplayDevice::DisplayType type, bool isSecure)
3672 : type(type),
3673 layerStack(DisplayDevice::NO_LAYER_STACK),
3674 orientation(0),
3675 width(0),
3676 height(0),
3677 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003678 viewport.makeInvalid();
3679 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003680}
3681
3682// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003685
3686
3687#if defined(__gl_h_)
3688#error "don't include gl/gl.h in this file"
3689#endif
3690
3691#if defined(__gl2_h_)
3692#error "don't include gl2/gl2.h in this file"
3693#endif