blob: fdc36505cf7c917bef6ecb77e442d568de36c225 [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
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080019#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
22#include <math.h>
Keun young Park63f165f2012-08-31 10:53:36 -070023#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080024#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070025#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070026
27#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070034#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036
Mathias Agopianc666cae2012-07-25 18:56:13 -070037#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070038#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070039
Mathias Agopian921e6ac2012-07-23 23:11:29 -070040#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070041#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070042#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080044#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080045#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070046
47#include <ui/GraphicBufferAllocator.h>
48#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070049#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080050
Mathias Agopiancde87a32012-09-13 14:09:01 -070051#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052#include <utils/String8.h>
53#include <utils/String16.h>
54#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080055#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056
Mathias Agopian921e6ac2012-07-23 23:11:29 -070057#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070058#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian3e25fd82013-04-22 17:52:16 +020060#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080063#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070064#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070065#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070066#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080067#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopiana4912602012-07-12 14:25:33 -070072#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070073#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070074#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Mathias Agopianff2ed702013-09-01 21:36:12 -070076#include "Effects/Daltonizer.h"
77
Mathias Agopian875d8e12013-06-07 15:35:48 -070078#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070080
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081#define DISPLAY_COUNT 1
82
Mathias Agopianfee2b462013-07-03 12:34:01 -070083/*
84 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
85 * black pixels.
86 */
87#define DEBUG_SCREENSHOTS false
88
Mathias Agopianca088332013-03-28 17:44:13 -070089EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
90
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070092
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070093// This is the phase offset in nanoseconds of the software vsync event
94// relative to the vsync event reported by HWComposer. The software vsync
95// event is when SurfaceFlinger and Choreographer-based applications run each
96// frame.
97//
98// This phase offset allows adjustment of the minimum latency from application
99// wake-up (by Choregographer) time to the time at which the resulting window
100// image is displayed. This value may be either positive (after the HW vsync)
101// or negative (before the HW vsync). Setting it to 0 will result in a
102// minimum latency of two vsync periods because the app and SurfaceFlinger
103// will run just after the HW vsync. Setting it to a positive number will
104// result in the minimum latency being:
105//
106// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
107//
108// Note that reducing this latency makes it more likely for the applications
109// to not have their window content image ready in time. When this happens
110// the latency will end up being an additional vsync period, and animations
111// will hiccup. Therefore, this latency should be tuned somewhat
112// conservatively (or at least with awareness of the trade-off being made).
113static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
114
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700115// This is the phase offset at which SurfaceFlinger's composition runs.
116static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118// ---------------------------------------------------------------------------
119
Mathias Agopian99b49842011-06-27 16:05:52 -0700120const String16 sHardwareTest("android.permission.HARDWARE_TEST");
121const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
122const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
123const String16 sDump("android.permission.DUMP");
124
125// ---------------------------------------------------------------------------
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700128 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700130 mTransactionPending(false),
131 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700132 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700134 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800135 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mVisibleRegionsDirty(false),
Mathias Agopiana350ff92010-08-10 17:14:02 -0700137 mHwWorkListDirty(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800138 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700140 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700141 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700142 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700143 mDebugInSwapBuffers(0),
144 mLastSwapBufferTime(0),
145 mDebugInTransaction(0),
146 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700147 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700148 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700149 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700150 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700151 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800152 mHasColorMatrix(false),
153 mHasPoweredOff(false),
154 mFrameBuckets(),
155 mTotalTime(0),
156 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157{
Steve Blocka19954a2012-01-04 20:05:49 +0000158 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159
160 // debugging stuff...
161 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700162
Mathias Agopianb4b17302013-03-20 18:36:41 -0700163 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700164 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700165
Dan Stoza14cd37c2015-07-09 12:43:33 -0700166 property_get("debug.sf.drop_missed_frames", value, "0");
167 mDropMissedFrames = atoi(value);
168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 property_get("debug.sf.showupdates", value, "0");
170 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700171
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172 property_get("debug.sf.ddms", value, "0");
173 mDebugDDMS = atoi(value);
174 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700175 if (!startDdmConnection()) {
176 // start failed, and DDMS debugging not enabled
177 mDebugDDMS = 0;
178 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700180 ALOGI_IF(mDebugRegion, "showupdates enabled");
181 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182}
183
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800184void SurfaceFlinger::onFirstRef()
185{
186 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800187}
188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189SurfaceFlinger::~SurfaceFlinger()
190{
Mathias Agopiana4912602012-07-12 14:25:33 -0700191 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
192 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
193 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194}
195
Dan Stozac7014012014-02-14 15:03:43 -0800196void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197{
198 // the window manager died on us. prepare its eulogy.
199
Andy McFadden13a082e2012-08-24 10:16:42 -0700200 // restore initial conditions (default device unblank, etc)
201 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800202
203 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700204 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205}
206
Mathias Agopian7e27f052010-05-28 14:22:23 -0700207sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208{
Mathias Agopian96f08192010-06-02 23:28:45 -0700209 sp<ISurfaceComposerClient> bclient;
210 sp<Client> client(new Client(this));
211 status_t err = client->initCheck();
212 if (err == NO_ERROR) {
213 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 return bclient;
216}
217
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700218sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
219 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700220{
221 class DisplayToken : public BBinder {
222 sp<SurfaceFlinger> flinger;
223 virtual ~DisplayToken() {
224 // no more references, this display must be terminated
225 Mutex::Autolock _l(flinger->mStateLock);
226 flinger->mCurrentState.displays.removeItem(this);
227 flinger->setTransactionFlags(eDisplayTransactionNeeded);
228 }
229 public:
230 DisplayToken(const sp<SurfaceFlinger>& flinger)
231 : flinger(flinger) {
232 }
233 };
234
235 sp<BBinder> token = new DisplayToken(this);
236
237 Mutex::Autolock _l(mStateLock);
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700238 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700239 info.displayName = displayName;
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700240 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241 mCurrentState.displays.add(token, info);
242
243 return token;
244}
245
Jesse Hall6c913be2013-08-08 12:15:49 -0700246void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
247 Mutex::Autolock _l(mStateLock);
248
249 ssize_t idx = mCurrentState.displays.indexOfKey(display);
250 if (idx < 0) {
251 ALOGW("destroyDisplay: invalid display token");
252 return;
253 }
254
255 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
256 if (!info.isVirtualDisplay()) {
257 ALOGE("destroyDisplay called for non-virtual display");
258 return;
259 }
260
261 mCurrentState.displays.removeItemsAt(idx);
262 setTransactionFlags(eDisplayTransactionNeeded);
263}
264
Jesse Hall692c7232012-11-08 15:41:56 -0800265void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
266 ALOGW_IF(mBuiltinDisplays[type],
267 "Overwriting display token for display type %d", type);
268 mBuiltinDisplays[type] = new BBinder();
269 DisplayDeviceState info(type);
270 // All non-virtual displays are currently considered secure.
271 info.isSecure = true;
272 mCurrentState.displays.add(mBuiltinDisplays[type], info);
273}
274
Mathias Agopiane57f2922012-08-09 16:29:12 -0700275sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700276 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
278 return NULL;
279 }
Jesse Hall692c7232012-11-08 15:41:56 -0800280 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700281}
282
Jamie Gennis9a78c902011-01-12 18:30:40 -0800283sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
284{
285 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
286 return gba;
287}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289void SurfaceFlinger::bootFinished()
290{
291 const nsecs_t now = systemTime();
292 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000293 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700294 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700295
296 // wait patiently for the window manager death
297 const String16 name("window");
298 sp<IBinder> window(defaultServiceManager()->getService(name));
299 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700300 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700301 }
302
303 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700304 // formerly we would just kill the process, but we now ask it to exit so it
305 // can choose where to stop the animation.
306 property_set("service.bootanim.exit", "1");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307}
308
Mathias Agopian3f844832013-08-07 21:24:32 -0700309void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700310 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700311 RenderEngine& engine;
312 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700313 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700314 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
315 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700316 }
317 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700318 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700319 return true;
320 }
321 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700322 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700323}
324
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700325class DispSyncSource : public VSyncSource, private DispSync::Callback {
326public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700327 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
328 const char* label) :
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700329 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700330 mTraceVsync(traceVsync),
Andy McFadden5167ec62014-05-22 13:08:43 -0700331 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
332 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700333 mDispSync(dispSync),
334 mCallbackMutex(),
335 mCallback(),
336 mVsyncMutex(),
337 mPhaseOffset(phaseOffset),
338 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700339
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700340 virtual ~DispSyncSource() {}
341
342 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700343 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700344 if (enable) {
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700345 status_t err = mDispSync->addEventListener(mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700346 static_cast<DispSync::Callback*>(this));
347 if (err != NO_ERROR) {
348 ALOGE("error registering vsync callback: %s (%d)",
349 strerror(-err), err);
350 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700351 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352 } else {
353 status_t err = mDispSync->removeEventListener(
354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error unregistering vsync callback: %s (%d)",
357 strerror(-err), err);
358 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700359 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700360 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700361 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700362 }
363
364 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700365 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700366 mCallback = callback;
367 }
368
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700369 virtual void setPhaseOffset(nsecs_t phaseOffset) {
370 Mutex::Autolock lock(mVsyncMutex);
371
372 // Normalize phaseOffset to [0, period)
373 auto period = mDispSync->getPeriod();
374 phaseOffset %= period;
375 if (phaseOffset < 0) {
376 // If we're here, then phaseOffset is in (-period, 0). After this
377 // operation, it will be in (0, period)
378 phaseOffset += period;
379 }
380 mPhaseOffset = phaseOffset;
381
382 // If we're not enabled, we don't need to mess with the listeners
383 if (!mEnabled) {
384 return;
385 }
386
387 // Remove the listener with the old offset
388 status_t err = mDispSync->removeEventListener(
389 static_cast<DispSync::Callback*>(this));
390 if (err != NO_ERROR) {
391 ALOGE("error unregistering vsync callback: %s (%d)",
392 strerror(-err), err);
393 }
394
395 // Add a listener with the new offset
396 err = mDispSync->addEventListener(mPhaseOffset,
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error registering vsync callback: %s (%d)",
400 strerror(-err), err);
401 }
402 }
403
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700404private:
405 virtual void onDispSyncEvent(nsecs_t when) {
406 sp<VSyncSource::Callback> callback;
407 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700408 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 callback = mCallback;
410
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700411 if (mTraceVsync) {
412 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700413 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700414 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 }
416
417 if (callback != NULL) {
418 callback->onVSyncEvent(when);
419 }
420 }
421
422 int mValue;
423
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700424 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700425 const String8 mVsyncOnLabel;
426 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700427
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700429
430 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700432
433 Mutex mVsyncMutex; // Protects the following
434 nsecs_t mPhaseOffset;
435 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436};
437
438void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700439 ALOGI( "SurfaceFlinger's main thread ready to run. "
440 "Initializing graphics H/W...");
441
Jesse Hall692c7232012-11-08 15:41:56 -0800442 Mutex::Autolock _l(mStateLock);
443
Andy McFaddenb0d1dd32012-09-10 14:08:09 -0700444 // initialize EGL for the default display
Jesse Hall34a09ba2012-07-29 22:35:34 -0700445 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
446 eglInitialize(mEGLDisplay, NULL, NULL);
Mathias Agopiana4912602012-07-12 14:25:33 -0700447
Saurabh Shahf9481052015-06-15 17:55:51 -0700448 // start the EventThread
449 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
450 vsyncPhaseOffsetNs, true, "app");
451 mEventThread = new EventThread(vsyncSrc);
452 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
453 sfVsyncPhaseOffsetNs, true, "sf");
454 mSFEventThread = new EventThread(sfVsyncSrc);
455 mEventQueue.setEventThread(mSFEventThread);
456
Andy McFaddenb0d1dd32012-09-10 14:08:09 -0700457 // Initialize the H/W composer object. There may or may not be an
458 // actual hardware composer underneath.
459 mHwc = new HWComposer(this,
460 *static_cast<HWComposer::EventHandler *>(this));
461
Mathias Agopian875d8e12013-06-07 15:35:48 -0700462 // get a RenderEngine for the given display / config (can't fail)
Jesse Hall05f8c702013-12-23 20:44:38 -0800463 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
Mathias Agopian875d8e12013-06-07 15:35:48 -0700464
465 // retrieve the EGL context that was selected/created
466 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700467
Mathias Agopianda27af92012-09-13 18:17:13 -0700468 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
469 "couldn't create EGLContext");
470
Mathias Agopiancde87a32012-09-13 14:09:01 -0700471 // initialize our non-virtual displays
Jesse Hall9e663de2013-08-16 14:28:37 -0700472 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Mathias Agopianf5a33922012-09-19 18:16:22 -0700473 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700474 // set-up the displays that are already connected
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700475 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700476 // All non-virtual displays are currently considered secure.
477 bool isSecure = true;
Jesse Hall692c7232012-11-08 15:41:56 -0800478 createBuiltinDisplayLocked(type);
479 wp<IBinder> token = mBuiltinDisplays[i];
480
Dan Stozab9b08832014-03-13 11:55:57 -0700481 sp<IGraphicBufferProducer> producer;
482 sp<IGraphicBufferConsumer> consumer;
483 BufferQueue::createBufferQueue(&producer, &consumer,
484 new GraphicBufferAlloc());
485
486 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
487 consumer);
Jesse Hall19e87292013-12-23 21:02:15 -0800488 int32_t hwcId = allocateHwcDisplayId(type);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700489 sp<DisplayDevice> hw = new DisplayDevice(this,
Jesse Hall19e87292013-12-23 21:02:15 -0800490 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
Dan Stozab9b08832014-03-13 11:55:57 -0700491 fbs, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -0800492 mRenderEngine->getEGLConfig());
Mathias Agopianf5a33922012-09-19 18:16:22 -0700493 if (i > DisplayDevice::DISPLAY_PRIMARY) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -0700494 // FIXME: currently we don't get blank/unblank requests
Mathias Agopianf5a33922012-09-19 18:16:22 -0700495 // for displays other than the main display, so we always
496 // assume a connected display is unblanked.
Greg Hackmann86efcc02014-03-07 12:44:02 -0800497 ALOGD("marking display %zu as acquired/unblanked", i);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700498 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
Mathias Agopianf5a33922012-09-19 18:16:22 -0700499 }
500 mDisplays.add(token, hw);
501 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 }
Mathias Agopiancde87a32012-09-13 14:09:01 -0700503
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700504 // make the GLContext current so that we can create textures when creating Layers
505 // (which may happens before we render something)
506 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
507
Jamie Gennisd1700752013-10-14 12:22:52 -0700508 mEventControlThread = new EventControlThread(this);
509 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
510
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 // set a fake vsync period if there is no HWComposer
512 if (mHwc->initCheck() != NO_ERROR) {
513 mPrimaryDispSync.setPeriod(16666667);
514 }
515
Mathias Agopian92a979a2012-08-02 18:32:23 -0700516 // initialize our drawing state
517 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700518
Andy McFadden13a082e2012-08-24 10:16:42 -0700519 // set initial conditions (e.g. unblank default device)
520 initializeDisplays();
521
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700522 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700523 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524}
525
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700526int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700527 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700528 type : mHwc->allocateDisplayId();
529}
530
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531void SurfaceFlinger::startBootAnim() {
532 // start boot animation
533 property_set("service.bootanim.exit", "0");
534 property_set("ctl.start", "bootanim");
535}
536
Mathias Agopian875d8e12013-06-07 15:35:48 -0700537size_t SurfaceFlinger::getMaxTextureSize() const {
538 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700539}
540
Mathias Agopian875d8e12013-06-07 15:35:48 -0700541size_t SurfaceFlinger::getMaxViewportDims() const {
542 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700543}
544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800546
Jamie Gennis582270d2011-08-17 18:19:00 -0700547bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800548 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800549 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800550 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700551 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800552}
553
Dan Stoza7f7da322014-05-02 15:26:25 -0700554status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
555 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700556 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700557 return BAD_VALUE;
558 }
559
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500560 if (!display.get())
561 return NAME_NOT_FOUND;
562
Jesse Hall692c7232012-11-08 15:41:56 -0800563 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700564 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800565 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700566 type = i;
567 break;
568 }
569 }
570
571 if (type < 0) {
572 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700573 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700574
Mathias Agopian8b736f12012-08-13 17:54:26 -0700575 // TODO: Not sure if display density should handled by SF any longer
576 class Density {
577 static int getDensityFromProperty(char const* propName) {
578 char property[PROPERTY_VALUE_MAX];
579 int density = 0;
580 if (property_get(propName, property, NULL) > 0) {
581 density = atoi(property);
582 }
583 return density;
584 }
585 public:
586 static int getEmuDensity() {
587 return getDensityFromProperty("qemu.sf.lcd_density"); }
588 static int getBuildDensity() {
589 return getDensityFromProperty("ro.sf.lcd_density"); }
590 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700591
Dan Stoza7f7da322014-05-02 15:26:25 -0700592 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700593
Dan Stoza7f7da322014-05-02 15:26:25 -0700594 const Vector<HWComposer::DisplayConfig>& hwConfigs =
595 getHwComposer().getConfigs(type);
596 for (size_t c = 0; c < hwConfigs.size(); ++c) {
597 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
598 DisplayInfo info = DisplayInfo();
599
600 float xdpi = hwConfig.xdpi;
601 float ydpi = hwConfig.ydpi;
602
603 if (type == DisplayDevice::DISPLAY_PRIMARY) {
604 // The density of the device is provided by a build property
605 float density = Density::getBuildDensity() / 160.0f;
606 if (density == 0) {
607 // the build doesn't provide a density -- this is wrong!
608 // use xdpi instead
609 ALOGE("ro.sf.lcd_density must be defined as a build property");
610 density = xdpi / 160.0f;
611 }
612 if (Density::getEmuDensity()) {
613 // if "qemu.sf.lcd_density" is specified, it overrides everything
614 xdpi = ydpi = density = Density::getEmuDensity();
615 density /= 160.0f;
616 }
617 info.density = density;
618
619 // TODO: this needs to go away (currently needed only by webkit)
620 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
621 info.orientation = hw->getOrientation();
622 } else {
623 // TODO: where should this value come from?
624 static const int TV_DENSITY = 213;
625 info.density = TV_DENSITY / 160.0f;
626 info.orientation = 0;
627 }
628
629 info.w = hwConfig.width;
630 info.h = hwConfig.height;
631 info.xdpi = xdpi;
632 info.ydpi = ydpi;
633 info.fps = float(1e9 / hwConfig.refresh);
Andy McFadden91b2ca82014-06-13 14:04:23 -0700634 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stozaf2699fc2015-08-31 12:06:48 -0700635 info.colorTransform = hwConfig.colorTransform;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700636
637 // This is how far in advance a buffer must be queued for
638 // presentation at a given time. If you want a buffer to appear
639 // on the screen at time N, you must submit the buffer before
640 // (N - presentationDeadline).
641 //
642 // Normally it's one full refresh period (to give SF a chance to
643 // latch the buffer), but this can be reduced by configuring a
644 // DispSync offset. Any additional delays introduced by the hardware
645 // composer or panel must be accounted for here.
646 //
647 // We add an additional 1ms to allow for processing time and
648 // differences between the ideal and actual refresh rate.
649 info.presentationDeadline =
650 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700651
652 // All non-virtual displays are currently considered secure.
653 info.secure = true;
654
655 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700656 }
657
Dan Stoza7f7da322014-05-02 15:26:25 -0700658 return NO_ERROR;
659}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700660
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800661status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700662 DisplayStatInfo* stats) {
663 if (stats == NULL) {
664 return BAD_VALUE;
665 }
666
667 // FIXME for now we always return stats for the primary display
668 memset(stats, 0, sizeof(*stats));
669 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
670 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
671 return NO_ERROR;
672}
673
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700674int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700675 sp<DisplayDevice> device(getDisplayDevice(display));
676 if (device != NULL) {
677 return device->getActiveConfig();
678 }
679 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700680}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700681
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700682void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
683 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
684 this);
685 int32_t type = hw->getDisplayType();
686 int currentMode = hw->getActiveConfig();
687
688 if (mode == currentMode) {
689 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
690 return;
691 }
692
693 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
694 ALOGW("Trying to set config for virtual display");
695 return;
696 }
697
698 hw->setActiveConfig(mode);
699 getHwComposer().setActiveConfig(type, mode);
700}
701
702status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
703 class MessageSetActiveConfig: public MessageBase {
704 SurfaceFlinger& mFlinger;
705 sp<IBinder> mDisplay;
706 int mMode;
707 public:
708 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
709 int mode) :
710 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
711 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700712 Vector<DisplayInfo> configs;
713 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700714 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700715 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700716 mMode, configs.size());
717 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700718 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
719 if (hw == NULL) {
720 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700721 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700722 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
723 ALOGW("Attempt to set active config = %d for virtual display",
724 mMode);
725 } else {
726 mFlinger.setActiveConfigInternal(hw, mMode);
727 }
728 return true;
729 }
730 };
731 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
732 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700733 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700734}
735
Svetoslavd85084b2014-03-20 10:28:31 -0700736status_t SurfaceFlinger::clearAnimationFrameStats() {
737 Mutex::Autolock _l(mStateLock);
738 mAnimFrameTracker.clearStats();
739 return NO_ERROR;
740}
741
742status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
743 Mutex::Autolock _l(mStateLock);
744 mAnimFrameTracker.getStats(outStats);
745 return NO_ERROR;
746}
747
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800748// ----------------------------------------------------------------------------
749
750sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800751 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700752}
753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800754// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800755
756void SurfaceFlinger::waitForEvent() {
757 mEventQueue.waitMessage();
758}
759
760void SurfaceFlinger::signalTransaction() {
761 mEventQueue.invalidate();
762}
763
764void SurfaceFlinger::signalLayerUpdate() {
765 mEventQueue.invalidate();
766}
767
768void SurfaceFlinger::signalRefresh() {
769 mEventQueue.refresh();
770}
771
772status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue.postMessage(msg, reltime);
775}
776
777status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800778 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800779 status_t res = mEventQueue.postMessage(msg, reltime);
780 if (res == NO_ERROR) {
781 msg->wait();
782 }
783 return res;
784}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700786void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700787 do {
788 waitForEvent();
789 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790}
791
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700792void SurfaceFlinger::enableHardwareVsync() {
793 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700794 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700795 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700796 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
797 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700798 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700799 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700800}
801
Jesse Hall948fe0c2013-10-14 12:56:09 -0700802void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700803 Mutex::Autolock _l(mHWVsyncLock);
804
Jesse Hall948fe0c2013-10-14 12:56:09 -0700805 if (makeAvailable) {
806 mHWVsyncAvailable = true;
807 } else if (!mHWVsyncAvailable) {
808 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
809 return;
810 }
811
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700812 const nsecs_t period =
813 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
814
815 mPrimaryDispSync.reset();
816 mPrimaryDispSync.setPeriod(period);
817
818 if (!mPrimaryHWVsyncEnabled) {
819 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700820 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
821 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700822 mPrimaryHWVsyncEnabled = true;
823 }
824}
825
Jesse Hall948fe0c2013-10-14 12:56:09 -0700826void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700827 Mutex::Autolock _l(mHWVsyncLock);
828 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700829 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
830 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700831 mPrimaryDispSync.endResync();
832 mPrimaryHWVsyncEnabled = false;
833 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700834 if (makeUnavailable) {
835 mHWVsyncAvailable = false;
836 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700837}
838
839void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700840 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700841
Jamie Gennisd1700752013-10-14 12:22:52 -0700842 { // Scope for the lock
843 Mutex::Autolock _l(mHWVsyncLock);
844 if (type == 0 && mPrimaryHWVsyncEnabled) {
845 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700846 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700847 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700848
849 if (needsHwVsync) {
850 enableHardwareVsync();
851 } else {
852 disableHardwareVsync(false);
853 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700854}
855
856void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
857 if (mEventThread == NULL) {
858 // This is a temporary workaround for b/7145521. A non-null pointer
859 // does not mean EventThread has finished initializing, so this
860 // is not a correct fix.
861 ALOGW("WARNING: EventThread not started, ignoring hotplug");
862 return;
863 }
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700864
Jesse Hall9e663de2013-08-16 14:28:37 -0700865 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700866 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800867 if (connected) {
868 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700869 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800870 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
871 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700872 }
873 setTransactionFlags(eDisplayTransactionNeeded);
874
Andy McFadden9e9689c2012-10-10 18:17:51 -0700875 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700876 }
Mathias Agopian86303202012-07-24 22:46:10 -0700877}
878
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700879void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700880 ATRACE_CALL();
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700881 getHwComposer().eventControl(disp, event, enabled);
Mathias Agopian86303202012-07-24 22:46:10 -0700882}
883
Mathias Agopian4fec8732012-06-29 14:12:52 -0700884void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800885 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800886 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800887 case MessageQueue::TRANSACTION: {
888 handleMessageTransaction();
889 break;
890 }
891 case MessageQueue::INVALIDATE: {
892 bool refreshNeeded = handleMessageTransaction();
893 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800894 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800895 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800896 // Signal a refresh if a transaction modified the window state,
897 // a new buffer was latched, or if HWC has requested a full
898 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800899 signalRefresh();
900 }
901 break;
902 }
903 case MessageQueue::REFRESH: {
904 handleMessageRefresh();
905 break;
906 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800907 }
908}
909
Dan Stoza6b9454d2014-11-07 16:00:59 -0800910bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700911 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700912 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700913 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800914 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700915 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800916 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700917}
918
Dan Stoza6b9454d2014-11-07 16:00:59 -0800919bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700920 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800921 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700922}
923
924void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700925 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700926
927 static nsecs_t previousExpectedPresent = 0;
928 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
929 static bool previousFrameMissed = false;
930 bool frameMissed = (expectedPresent == previousExpectedPresent);
931 if (frameMissed != previousFrameMissed) {
932 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
933 }
934 previousFrameMissed = frameMissed;
935
936 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
937 // Latch buffers, but don't send anything to HWC, then signal another
938 // wakeup for the next vsync
939 preComposition();
940 repaintEverything();
941 } else {
942 preComposition();
943 rebuildLayerStacks();
944 setUpHWComposer();
945 doDebugFlashRegions();
946 doComposition();
947 postComposition();
948 }
949
950 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700951}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700952
Mathias Agopiancd60f992012-08-16 16:28:27 -0700953void SurfaceFlinger::doDebugFlashRegions()
954{
955 // is debugging enabled
956 if (CC_LIKELY(!mDebugRegion))
957 return;
958
959 const bool repaintEverything = mRepaintEverything;
960 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
961 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700962 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700963 // transform the dirty region into this screen's coordinate space
964 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
965 if (!dirtyRegion.isEmpty()) {
966 // redraw the whole screen
967 doComposeSurfaces(hw, Region(hw->bounds()));
968
969 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700970 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -0700971 RenderEngine& engine(getRenderEngine());
972 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
973
Mathias Agopiancd60f992012-08-16 16:28:27 -0700974 hw->compositionComplete();
Mathias Agopianda27af92012-09-13 18:17:13 -0700975 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -0700976 }
977 }
978 }
979
980 postFramebuffer();
981
982 if (mDebugRegion > 1) {
983 usleep(mDebugRegion * 1000);
984 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -0700985
986 HWComposer& hwc(getHwComposer());
987 if (hwc.initCheck() == NO_ERROR) {
988 status_t err = hwc.prepare();
989 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
990 }
Mathias Agopiancd60f992012-08-16 16:28:27 -0700991}
992
993void SurfaceFlinger::preComposition()
994{
995 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700996 const LayerVector& layers(mDrawingState.layersSortedByZ);
997 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700998 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700999 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001000 needExtraInvalidate = true;
1001 }
1002 }
1003 if (needExtraInvalidate) {
1004 signalLayerUpdate();
1005 }
1006}
1007
1008void SurfaceFlinger::postComposition()
1009{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001010 const LayerVector& layers(mDrawingState.layersSortedByZ);
1011 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001012 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001013 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001014 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001015
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001016 const HWComposer& hwc = getHwComposer();
1017 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1018
1019 if (presentFence->isValid()) {
1020 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1021 enableHardwareVsync();
1022 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001023 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001024 }
1025 }
1026
Dan Stozab90cf072015-03-05 11:05:59 -08001027 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001028 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001029 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001030 enableHardwareVsync();
1031 }
1032 }
1033
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001034 if (mAnimCompositionPending) {
1035 mAnimCompositionPending = false;
1036
Jesse Halla9a1b002013-02-27 16:39:25 -08001037 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001038 mAnimFrameTracker.setActualPresentFence(presentFence);
1039 } else {
1040 // The HWC doesn't support present fences, so use the refresh
1041 // timestamp instead.
1042 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1043 mAnimFrameTracker.setActualPresentTime(presentTime);
1044 }
1045 mAnimFrameTracker.advanceFrame();
1046 }
Dan Stozab90cf072015-03-05 11:05:59 -08001047
1048 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1049 return;
1050 }
1051
1052 nsecs_t currentTime = systemTime();
1053 if (mHasPoweredOff) {
1054 mHasPoweredOff = false;
1055 } else {
1056 nsecs_t period = mPrimaryDispSync.getPeriod();
1057 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1058 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1059 if (numPeriods < NUM_BUCKETS - 1) {
1060 mFrameBuckets[numPeriods] += elapsedTime;
1061 } else {
1062 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1063 }
1064 mTotalTime += elapsedTime;
1065 }
1066 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001067}
1068
1069void SurfaceFlinger::rebuildLayerStacks() {
1070 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001071 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001072 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001073 mVisibleRegionsDirty = false;
1074 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001075
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001076 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001077 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001078 Region opaqueRegion;
1079 Region dirtyRegion;
Mathias Agopian13127d82013-03-05 17:47:11 -08001080 Vector< sp<Layer> > layersSortedByZ;
Mathias Agopian42977342012-08-05 00:40:46 -07001081 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001082 const Transform& tr(hw->getTransform());
1083 const Rect bounds(hw->getBounds());
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001084 if (hw->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001085 SurfaceFlinger::computeVisibleRegions(layers,
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001086 hw->getLayerStack(), dirtyRegion, opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001087
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001088 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001089 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001090 const sp<Layer>& layer(layers[i]);
1091 const Layer::State& s(layer->getDrawingState());
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001092 if (s.layerStack == hw->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001093 Region drawRegion(tr.transform(
1094 layer->visibleNonTransparentRegion));
1095 drawRegion.andSelf(bounds);
1096 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001097 layersSortedByZ.add(layer);
1098 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001099 }
1100 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001101 }
Mathias Agopian42977342012-08-05 00:40:46 -07001102 hw->setVisibleLayersSortedByZ(layersSortedByZ);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001103 hw->undefinedRegion.set(bounds);
1104 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1105 hw->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001106 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001107 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001108}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001109
Mathias Agopiancd60f992012-08-16 16:28:27 -07001110void SurfaceFlinger::setUpHWComposer() {
Jesse Hall028dc8f2013-08-20 16:35:32 -07001111 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001112 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1113 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1114 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1115
1116 // If nothing has changed (!dirty), don't recompose.
1117 // If something changed, but we don't currently have any visible layers,
1118 // and didn't when we last did a composition, then skip it this time.
1119 // The second rule does two things:
1120 // - When all layers are removed from a display, we'll emit one black
1121 // frame, then nothing more until we get new layers.
1122 // - When a display is created with a private layer stack, we won't
1123 // emit any black frames until a layer is added to the layer stack.
1124 bool mustRecompose = dirty && !(empty && wasEmpty);
1125
1126 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1127 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1128 mustRecompose ? "doing" : "skipping",
1129 dirty ? "+" : "-",
1130 empty ? "+" : "-",
1131 wasEmpty ? "+" : "-");
1132
Dan Stoza71433162014-02-04 16:22:36 -08001133 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001134
1135 if (mustRecompose) {
1136 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1137 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001138 }
1139
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001140 HWComposer& hwc(getHwComposer());
1141 if (hwc.initCheck() == NO_ERROR) {
1142 // build the h/w work list
Jamie Gennisa4310c82012-09-25 20:26:00 -07001143 if (CC_UNLIKELY(mHwWorkListDirty)) {
1144 mHwWorkListDirty = false;
1145 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1146 sp<const DisplayDevice> hw(mDisplays[dpy]);
1147 const int32_t id = hw->getHwcDisplayId();
1148 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001149 const Vector< sp<Layer> >& currentLayers(
Jamie Gennisa4310c82012-09-25 20:26:00 -07001150 hw->getVisibleLayersSortedByZ());
1151 const size_t count = currentLayers.size();
1152 if (hwc.createWorkList(id, count) == NO_ERROR) {
1153 HWComposer::LayerListIterator cur = hwc.begin(id);
1154 const HWComposer::LayerListIterator end = hwc.end(id);
1155 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001156 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001157 layer->setGeometry(hw, *cur);
Alan Viverette9c5a3332013-09-12 20:04:35 -07001158 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
Jamie Gennisa4310c82012-09-25 20:26:00 -07001159 cur->setSkip(true);
1160 }
1161 }
1162 }
1163 }
1164 }
1165 }
1166
1167 // set the per-frame data
Mathias Agopian92a979a2012-08-02 18:32:23 -07001168 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001169 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001170 const int32_t id = hw->getHwcDisplayId();
1171 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001172 const Vector< sp<Layer> >& currentLayers(
Mathias Agopiancd60f992012-08-16 16:28:27 -07001173 hw->getVisibleLayersSortedByZ());
Mathias Agopiane60b0682012-08-21 23:34:09 -07001174 const size_t count = currentLayers.size();
Jamie Gennisa4310c82012-09-25 20:26:00 -07001175 HWComposer::LayerListIterator cur = hwc.begin(id);
1176 const HWComposer::LayerListIterator end = hwc.end(id);
1177 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1178 /*
1179 * update the per-frame h/w composer data for each layer
1180 * and build the transparent region of the FB
1181 */
Mathias Agopian13127d82013-03-05 17:47:11 -08001182 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001183 layer->setPerFrameData(hw, *cur);
Mathias Agopian1e260872012-08-08 18:35:12 -07001184 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001185 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001186 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001187
Riley Andrews03414a12014-07-01 14:22:59 -07001188 // If possible, attempt to use the cursor overlay on each display.
1189 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1190 sp<const DisplayDevice> hw(mDisplays[dpy]);
1191 const int32_t id = hw->getHwcDisplayId();
1192 if (id >= 0) {
1193 const Vector< sp<Layer> >& currentLayers(
1194 hw->getVisibleLayersSortedByZ());
1195 const size_t count = currentLayers.size();
1196 HWComposer::LayerListIterator cur = hwc.begin(id);
1197 const HWComposer::LayerListIterator end = hwc.end(id);
1198 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1199 const sp<Layer>& layer(currentLayers[i]);
1200 if (layer->isPotentialCursor()) {
1201 cur->setIsCursorLayerHint();
1202 break;
1203 }
1204 }
1205 }
1206 }
1207
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001208 status_t err = hwc.prepare();
1209 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
Jesse Hall38efe862013-04-06 23:12:29 -07001210
1211 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1212 sp<const DisplayDevice> hw(mDisplays[dpy]);
1213 hw->prepareFrame(hwc);
1214 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001215 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001216}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001217
Mathias Agopiancd60f992012-08-16 16:28:27 -07001218void SurfaceFlinger::doComposition() {
1219 ATRACE_CALL();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001220 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001221 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001222 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001223 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001224 // transform the dirty region into this screen's coordinate space
1225 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001226
1227 // repaint the framebuffer (if needed)
1228 doDisplayComposition(hw, dirtyRegion);
1229
Mathias Agopiancd60f992012-08-16 16:28:27 -07001230 hw->dirtyRegion.clear();
1231 hw->flip(hw->swapRegion);
1232 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001233 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001234 // inform the h/w that we're done compositing
Mathias Agopian42977342012-08-05 00:40:46 -07001235 hw->compositionComplete();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001236 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001237 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001238}
1239
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001240void SurfaceFlinger::postFramebuffer()
1241{
Mathias Agopian841cde52012-03-01 15:44:37 -08001242 ATRACE_CALL();
Mathias Agopianb048cef2012-02-04 15:44:04 -08001243
Mathias Agopiana44b0412011-10-16 18:46:35 -07001244 const nsecs_t now = systemTime();
1245 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001246
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001247 HWComposer& hwc(getHwComposer());
Jesse Hallef194142012-06-14 14:45:17 -07001248 if (hwc.initCheck() == NO_ERROR) {
Mathias Agopian2a231842012-09-24 18:12:35 -07001249 if (!hwc.supportsFramebufferTarget()) {
1250 // EGL spec says:
1251 // "surface must be bound to the calling thread's current context,
1252 // for the current rendering API."
Mathias Agopian875d8e12013-06-07 15:35:48 -07001253 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopian2a231842012-09-24 18:12:35 -07001254 }
Mathias Agopiane60b0682012-08-21 23:34:09 -07001255 hwc.commit();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001256 }
1257
Mathias Agopian6da15f42013-09-25 20:40:07 -07001258 // make the default display current because the VirtualDisplayDevice code cannot
1259 // deal with dequeueBuffer() being called outside of the composition loop; however
1260 // the code below can call glFlush() which is allowed (and does in some case) call
1261 // dequeueBuffer().
1262 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1263
Mathias Agopian92a979a2012-08-02 18:32:23 -07001264 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001265 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopian13127d82013-03-05 17:47:11 -08001266 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
Mathias Agopianda27af92012-09-13 18:17:13 -07001267 hw->onSwapBuffersCompleted(hwc);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001268 const size_t count = currentLayers.size();
Mathias Agopiane60b0682012-08-21 23:34:09 -07001269 int32_t id = hw->getHwcDisplayId();
1270 if (id >=0 && hwc.initCheck() == NO_ERROR) {
Mathias Agopian1e260872012-08-08 18:35:12 -07001271 HWComposer::LayerListIterator cur = hwc.begin(id);
1272 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001273 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001274 currentLayers[i]->onLayerDisplayed(hw, &*cur);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001275 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001276 } else {
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001277 for (size_t i = 0; i < count; i++) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001278 currentLayers[i]->onLayerDisplayed(hw, NULL);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001279 }
Jesse Hallef194142012-06-14 14:45:17 -07001280 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001281 }
1282
Mathias Agopiana44b0412011-10-16 18:46:35 -07001283 mLastSwapBufferTime = systemTime() - now;
1284 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001285
1286 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1287 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1288 logFrameStats();
1289 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001290}
1291
Mathias Agopian87baae12012-07-31 12:38:26 -07001292void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293{
Mathias Agopian841cde52012-03-01 15:44:37 -08001294 ATRACE_CALL();
1295
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001296 // here we keep a copy of the drawing state (that is the state that's
1297 // going to be overwritten by handleTransactionLocked()) outside of
1298 // mStateLock so that the side-effects of the State assignment
1299 // don't happen with mStateLock held (which can cause deadlocks).
1300 State drawingState(mDrawingState);
1301
Mathias Agopianca4d3602011-05-19 15:38:14 -07001302 Mutex::Autolock _l(mStateLock);
1303 const nsecs_t now = systemTime();
1304 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001305
Mathias Agopianca4d3602011-05-19 15:38:14 -07001306 // Here we're guaranteed that some transaction flags are set
1307 // so we can call handleTransactionLocked() unconditionally.
1308 // We call getTransactionFlags(), which will also clear the flags,
1309 // with mStateLock held to guarantee that mCurrentState won't change
1310 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001311
Mathias Agopiane57f2922012-08-09 16:29:12 -07001312 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001313 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001314
Mathias Agopianca4d3602011-05-19 15:38:14 -07001315 mLastTransactionTime = systemTime() - now;
1316 mDebugInTransaction = 0;
1317 invalidateHwcGeometry();
1318 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001319}
1320
Mathias Agopian87baae12012-07-31 12:38:26 -07001321void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001322{
1323 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324 const size_t count = currentLayers.size();
1325
1326 /*
1327 * Traversal of the children
1328 * (perform the transaction for each of them if needed)
1329 */
1330
Mathias Agopian3559b072012-08-15 13:46:03 -07001331 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001333 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1335 if (!trFlags) continue;
1336
1337 const uint32_t flags = layer->doTransaction(0);
1338 if (flags & Layer::eVisibleRegion)
1339 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001340 }
1341 }
1342
1343 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001344 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001345 */
1346
Mathias Agopiane57f2922012-08-09 16:29:12 -07001347 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001348 // here we take advantage of Vector's copy-on-write semantics to
1349 // improve performance by skipping the transaction entirely when
1350 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001351 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1352 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001353 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001355 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001356 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001357
1358 // find the displays that were removed
1359 // (ie: in drawing state but not in current state)
1360 // also handle displays that changed
1361 // (ie: displays that are in both lists)
1362 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001363 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1364 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001365 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001366 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001367 // Call makeCurrent() on the primary display so we can
1368 // be sure that nothing associated with this display
1369 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001370 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001371 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001372 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1373 if (hw != NULL)
1374 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001375 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001376 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001377 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001378 } else {
1379 ALOGW("trying to remove the main display");
1380 }
1381 } else {
1382 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001383 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001384 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001385 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1386 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001387 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001388 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001389 // recreating the DisplayDevice, so we just remove it
1390 // from the drawing state, so that it get re-added
1391 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001392 sp<DisplayDevice> hw(getDisplayDevice(display));
1393 if (hw != NULL)
1394 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001395 mDisplays.removeItem(display);
1396 mDrawingState.displays.removeItemsAt(i);
1397 dc--; i--;
1398 // at this point we must loop to the next item
1399 continue;
1400 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001401
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001402 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001403 if (disp != NULL) {
1404 if (state.layerStack != draw[i].layerStack) {
1405 disp->setLayerStack(state.layerStack);
1406 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001407 if ((state.orientation != draw[i].orientation)
1408 || (state.viewport != draw[i].viewport)
1409 || (state.frame != draw[i].frame))
1410 {
1411 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001412 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001413 }
Michael Lentine47e45402014-07-18 15:34:25 -07001414 if (state.width != draw[i].width || state.height != draw[i].height) {
1415 disp->setDisplaySize(state.width, state.height);
1416 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001417 }
1418 }
1419 }
1420
1421 // find displays that were added
1422 // (ie: in current state but not in drawing state)
1423 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001424 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001425 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001426
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001427 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001428 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001429 sp<IGraphicBufferProducer> bqProducer;
1430 sp<IGraphicBufferConsumer> bqConsumer;
1431 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1432 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001433
Jesse Hall02d86562013-03-25 14:43:23 -07001434 int32_t hwcDisplayId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001435 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001436 // Virtual displays without a surface are dormant:
1437 // they have external state (layer stack, projection,
1438 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001439 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001440
Dan Stoza1f3efb12014-10-15 16:34:55 -07001441 int width = 0;
1442 int status = state.surface->query(
1443 NATIVE_WINDOW_WIDTH, &width);
1444 ALOGE_IF(status != NO_ERROR,
1445 "Unable to query width (%d)", status);
1446 int height = 0;
1447 status = state.surface->query(
1448 NATIVE_WINDOW_HEIGHT, &height);
1449 ALOGE_IF(status != NO_ERROR,
1450 "Unable to query height (%d)", status);
1451 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1452 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1453 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1454 hwcDisplayId = allocateHwcDisplayId(state.type);
1455 }
1456
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001457 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
Dan Stozab9b08832014-03-13 11:55:57 -07001458 *mHwc, hwcDisplayId, state.surface,
1459 bqProducer, bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001460
1461 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001462 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001463 }
1464 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001465 ALOGE_IF(state.surface!=NULL,
1466 "adding a supported display, but rendering "
1467 "surface is provided (%p), ignoring it",
1468 state.surface.get());
Jesse Hall02d86562013-03-25 14:43:23 -07001469 hwcDisplayId = allocateHwcDisplayId(state.type);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001470 // for supported (by hwc) displays we provide our
1471 // own rendering surface
Dan Stozab9b08832014-03-13 11:55:57 -07001472 dispSurface = new FramebufferSurface(*mHwc, state.type,
1473 bqConsumer);
1474 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001475 }
1476
1477 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001478 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001479 sp<DisplayDevice> hw = new DisplayDevice(this,
Jesse Hall19e87292013-12-23 21:02:15 -08001480 state.type, hwcDisplayId,
1481 mHwc->getFormat(hwcDisplayId), state.isSecure,
Jesse Hall05f8c702013-12-23 20:44:38 -08001482 display, dispSurface, producer,
1483 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001484 hw->setLayerStack(state.layerStack);
1485 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001486 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001487 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001488 mDisplays.add(display, hw);
Jesse Hall1c569c42013-04-05 13:44:52 -07001489 if (state.isVirtualDisplay()) {
1490 if (hwcDisplayId >= 0) {
1491 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1492 hw->getWidth(), hw->getHeight(),
1493 hw->getFormat());
1494 }
1495 } else {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001496 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001497 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001498 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001499 }
1500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001501 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001502 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001503
Mathias Agopian84300952012-11-21 16:02:13 -08001504 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1505 // The transform hint might have changed for some layers
1506 // (either because a display has changed, or because a layer
1507 // as changed).
1508 //
1509 // Walk through all the layers in currentLayers,
1510 // and update their transform hint.
1511 //
1512 // If a layer is visible only on a single display, then that
1513 // display is used to calculate the hint, otherwise we use the
1514 // default display.
1515 //
1516 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1517 // the hint is set before we acquire a buffer from the surface texture.
1518 //
1519 // NOTE: layer transactions have taken place already, so we use their
1520 // drawing state. However, SurfaceFlinger's own transaction has not
1521 // happened yet, so we must use the current state layer list
1522 // (soon to become the drawing state list).
1523 //
1524 sp<const DisplayDevice> disp;
1525 uint32_t currentlayerStack = 0;
1526 for (size_t i=0; i<count; i++) {
1527 // NOTE: we rely on the fact that layers are sorted by
1528 // layerStack first (so we don't have to traverse the list
1529 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001530 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001531 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001532 if (i==0 || currentlayerStack != layerStack) {
1533 currentlayerStack = layerStack;
1534 // figure out if this layerstack is mirrored
1535 // (more than one display) if so, pick the default display,
1536 // if not, pick the only display it's on.
1537 disp.clear();
1538 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1539 sp<const DisplayDevice> hw(mDisplays[dpy]);
1540 if (hw->getLayerStack() == currentlayerStack) {
1541 if (disp == NULL) {
1542 disp = hw;
1543 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001544 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001545 break;
1546 }
1547 }
1548 }
1549 }
Chet Haase91d25932013-04-11 15:24:55 -07001550 if (disp == NULL) {
1551 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1552 // redraw after transform hint changes. See bug 8508397.
1553
1554 // could be null when this layer is using a layerStack
1555 // that is not visible on any display. Also can occur at
1556 // screen off/on times.
1557 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001558 }
Chet Haase91d25932013-04-11 15:24:55 -07001559 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001560 }
1561 }
1562
1563
Mathias Agopian3559b072012-08-15 13:46:03 -07001564 /*
1565 * Perform our own transaction if needed
1566 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001567
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001568 const LayerVector& layers(mDrawingState.layersSortedByZ);
1569 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001570 // layers have been added
1571 mVisibleRegionsDirty = true;
1572 }
1573
1574 // some layers might have been removed, so
1575 // we need to update the regions they're exposing.
1576 if (mLayersRemoved) {
1577 mLayersRemoved = false;
1578 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001579 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001580 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001581 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001582 if (currentLayers.indexOf(layer) < 0) {
1583 // this layer is not visible anymore
1584 // TODO: we could traverse the tree from front to back and
1585 // compute the actual visible region
1586 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 const Layer::State& s(layer->getDrawingState());
Mathias Agopian1501d542012-09-04 21:04:09 -07001588 Region visibleReg = s.transform.transform(
1589 Region(Rect(s.active.w, s.active.h)));
1590 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001591 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001592 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001593 }
1594
1595 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001596
1597 updateCursorAsync();
1598}
1599
1600void SurfaceFlinger::updateCursorAsync()
1601{
1602 HWComposer& hwc(getHwComposer());
1603 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1604 sp<const DisplayDevice> hw(mDisplays[dpy]);
1605 const int32_t id = hw->getHwcDisplayId();
1606 if (id < 0) {
1607 continue;
1608 }
1609 const Vector< sp<Layer> >& currentLayers(
1610 hw->getVisibleLayersSortedByZ());
1611 const size_t count = currentLayers.size();
1612 HWComposer::LayerListIterator cur = hwc.begin(id);
1613 const HWComposer::LayerListIterator end = hwc.end(id);
1614 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1615 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1616 continue;
1617 }
1618 const sp<Layer>& layer(currentLayers[i]);
1619 Rect cursorPos = layer->getPosition(hw);
1620 hwc.setCursorPositionAsync(id, cursorPos);
1621 break;
1622 }
1623 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001624}
1625
1626void SurfaceFlinger::commitTransaction()
1627{
1628 if (!mLayersPendingRemoval.isEmpty()) {
1629 // Notify removed layers now that they can't be drawn from
1630 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1631 mLayersPendingRemoval[i]->onRemoved();
1632 }
1633 mLayersPendingRemoval.clear();
1634 }
1635
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001636 // If this transaction is part of a window animation then the next frame
1637 // we composite should be considered an animation as well.
1638 mAnimCompositionPending = mAnimTransactionPending;
1639
Mathias Agopian4fec8732012-06-29 14:12:52 -07001640 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001641 mTransactionPending = false;
1642 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001643 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001644}
1645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001646void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001647 const LayerVector& currentLayers, uint32_t layerStack,
1648 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001649{
Mathias Agopian841cde52012-03-01 15:44:37 -08001650 ATRACE_CALL();
1651
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001652 Region aboveOpaqueLayers;
1653 Region aboveCoveredLayers;
1654 Region dirty;
1655
Mathias Agopian87baae12012-07-31 12:38:26 -07001656 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001657
1658 size_t i = currentLayers.size();
1659 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001660 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001661
1662 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001663 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001664
Jesse Hall01e29052013-02-19 16:13:35 -08001665 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001666 if (s.layerStack != layerStack)
1667 continue;
1668
Mathias Agopianab028732010-03-16 16:41:46 -07001669 /*
1670 * opaqueRegion: area of a surface that is fully opaque.
1671 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001672 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001673
1674 /*
1675 * visibleRegion: area of a surface that is visible on screen
1676 * and not fully transparent. This is essentially the layer's
1677 * footprint minus the opaque regions above it.
1678 * Areas covered by a translucent surface are considered visible.
1679 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001680 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001681
1682 /*
1683 * coveredRegion: area of a surface that is covered by all
1684 * visible regions above it (which includes the translucent areas).
1685 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001686 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001687
Jesse Halla8026d22012-09-25 13:25:04 -07001688 /*
1689 * transparentRegion: area of a surface that is hinted to be completely
1690 * transparent. This is only used to tell when the layer has no visible
1691 * non-transparent regions and can be removed from the layer list. It
1692 * does not affect the visibleRegion of this layer or any layers
1693 * beneath it. The hint may not be correct if apps don't respect the
1694 * SurfaceView restrictions (which, sadly, some don't).
1695 */
1696 Region transparentRegion;
1697
Mathias Agopianab028732010-03-16 16:41:46 -07001698
1699 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001700 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001701 const bool translucent = !layer->isOpaque(s);
Mathias Agopian5219a062013-02-26 16:37:53 -08001702 Rect bounds(s.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001703 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001704 if (!visibleRegion.isEmpty()) {
1705 // Remove the transparent area from the visible region
1706 if (translucent) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707 const Transform tr(s.transform);
1708 if (tr.transformed()) {
1709 if (tr.preserveRects()) {
1710 // transform the transparent region
Mathias Agopian2ca79392013-04-02 18:30:32 -07001711 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712 } else {
1713 // transformation too complex, can't do the
1714 // transparent region optimization.
Jesse Halla8026d22012-09-25 13:25:04 -07001715 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716 }
1717 } else {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001718 transparentRegion = s.activeTransparentRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001719 }
Mathias Agopianab028732010-03-16 16:41:46 -07001720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001721
Mathias Agopianab028732010-03-16 16:41:46 -07001722 // compute the opaque region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723 const int32_t layerOrientation = s.transform.getOrientation();
Mathias Agopianab028732010-03-16 16:41:46 -07001724 if (s.alpha==255 && !translucent &&
1725 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1726 // the opaque region is the layer's footprint
1727 opaqueRegion = visibleRegion;
1728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001729 }
1730 }
1731
Mathias Agopianab028732010-03-16 16:41:46 -07001732 // Clip the covered region to the visible region
1733 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1734
1735 // Update aboveCoveredLayers for next (lower) layer
1736 aboveCoveredLayers.orSelf(visibleRegion);
1737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001738 // subtract the opaque region covered by the layers above us
1739 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001740
1741 // compute this layer's dirty region
1742 if (layer->contentDirty) {
1743 // we need to invalidate the whole region
1744 dirty = visibleRegion;
1745 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001746 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001747 layer->contentDirty = false;
1748 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001749 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001750 * the exposed region consists of two components:
1751 * 1) what's VISIBLE now and was COVERED before
1752 * 2) what's EXPOSED now less what was EXPOSED before
1753 *
1754 * note that (1) is conservative, we start with the whole
1755 * visible region but only keep what used to be covered by
1756 * something -- which mean it may have been exposed.
1757 *
1758 * (2) handles areas that were not covered by anything but got
1759 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001760 */
Mathias Agopianab028732010-03-16 16:41:46 -07001761 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001762 const Region oldVisibleRegion = layer->visibleRegion;
1763 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001764 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1765 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001766 }
1767 dirty.subtractSelf(aboveOpaqueLayers);
1768
1769 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001770 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001771
Mathias Agopianab028732010-03-16 16:41:46 -07001772 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001774
Jesse Halla8026d22012-09-25 13:25:04 -07001775 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001776 layer->setVisibleRegion(visibleRegion);
1777 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001778 layer->setVisibleNonTransparentRegion(
1779 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001780 }
1781
Mathias Agopian87baae12012-07-31 12:38:26 -07001782 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001783}
1784
Mathias Agopian87baae12012-07-31 12:38:26 -07001785void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1786 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001787 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001788 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1789 if (hw->getLayerStack() == layerStack) {
1790 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001791 }
1792 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001793}
1794
Dan Stoza6b9454d2014-11-07 16:00:59 -08001795bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001796{
Mathias Agopian4fec8732012-06-29 14:12:52 -07001797 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001798
Mathias Agopian4fec8732012-06-29 14:12:52 -07001799 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001800 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001801 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001802
1803 // Store the set of layers that need updates. This set must not change as
1804 // buffers are being latched, as this could result in a deadlock.
1805 // Example: Two producers share the same command stream and:
1806 // 1.) Layer 0 is latched
1807 // 2.) Layer 0 gets a new frame
1808 // 2.) Layer 1 gets a new frame
1809 // 3.) Layer 1 is latched.
1810 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1811 // second frame. But layer 0's second frame could be waiting on display.
1812 Vector<Layer*> layersWithQueuedFrames;
1813 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001814 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001815 if (layer->hasQueuedFrame()) {
1816 frameQueued = true;
1817 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1818 layersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001819 } else {
1820 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001821 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001822 } else {
1823 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001824 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001825 }
1826 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1827 Layer* layer = layersWithQueuedFrames[i];
Mathias Agopian87baae12012-07-31 12:38:26 -07001828 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001829 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001830 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001831 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001832 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001833
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001834 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001835
1836 // If we will need to wake up at some time in the future to deal with a
1837 // queued frame that shouldn't be displayed during this vsync period, wake
1838 // up during the next vsync period to check again.
1839 if (frameQueued && layersWithQueuedFrames.empty()) {
1840 signalLayerUpdate();
1841 }
1842
1843 // Only continue with the refresh if there is actually new work to do
1844 return !layersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001845}
1846
Mathias Agopianad456f92011-01-13 17:53:01 -08001847void SurfaceFlinger::invalidateHwcGeometry()
1848{
1849 mHwWorkListDirty = true;
1850}
1851
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001852
Mathias Agopiancd60f992012-08-16 16:28:27 -07001853void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001854 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001855{
Dan Stoza71433162014-02-04 16:22:36 -08001856 // We only need to actually compose the display if:
1857 // 1) It is being handled by hardware composer, which may need this to
1858 // keep its virtual display state machine in sync, or
1859 // 2) There is work to be done (the dirty region isn't empty)
1860 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1861 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1862 return;
1863 }
1864
Mathias Agopian87baae12012-07-31 12:38:26 -07001865 Region dirtyRegion(inDirtyRegion);
1866
Mathias Agopianb8a55602009-06-26 19:06:36 -07001867 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001868 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001869
Mathias Agopian42977342012-08-05 00:40:46 -07001870 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001871 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001872 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1873 // takes a rectangle, we must make sure to update that whole
1874 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001875 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001876 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001877 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001878 // We need to redraw the rectangle that will be updated
1879 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001880 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001881 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001882 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001883 } else {
1884 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001885 dirtyRegion.set(hw->bounds());
1886 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001887 }
1888 }
1889
Alan Viverette9c5a3332013-09-12 20:04:35 -07001890 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001891 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001892 } else {
1893 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001894 mat4 colorMatrix = mColorMatrix;
1895 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001896 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001897 }
Dan Stozaf0087992014-10-20 15:46:09 -07001898 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001899 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001900 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001901 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001902
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001903 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001904 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001905
1906 // swap buffers (presentation)
1907 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908}
1909
Michael Lentine3f121fc2014-10-01 11:17:28 -07001910bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001911{
Mathias Agopian3f844832013-08-07 21:24:32 -07001912 RenderEngine& engine(getRenderEngine());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001913 const int32_t id = hw->getHwcDisplayId();
Mathias Agopian86303202012-07-24 22:46:10 -07001914 HWComposer& hwc(getHwComposer());
Mathias Agopian1e260872012-08-08 18:35:12 -07001915 HWComposer::LayerListIterator cur = hwc.begin(id);
1916 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001917
Jesse Halld05a17f2013-09-30 16:49:30 -07001918 bool hasGlesComposition = hwc.hasGlesComposition(id);
Mathias Agopian85d751c2012-08-29 16:59:24 -07001919 if (hasGlesComposition) {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001920 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001921 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1922 hw->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001923 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1924 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1925 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1926 }
1927 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001928 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001929
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001930 // Never touch the framebuffer if we don't have any framebuffer layers
Mathias Agopian85d751c2012-08-29 16:59:24 -07001931 const bool hasHwcComposition = hwc.hasHwcComposition(id);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001932 if (hasHwcComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001933 // when using overlays, we assume a fully transparent framebuffer
1934 // NOTE: we could reduce how much we need to clear, for instance
1935 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001936 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001937 // We'll revisit later if needed.
Mathias Agopian3f844832013-08-07 21:24:32 -07001938 engine.clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001939 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001940 // we start with the whole screen area
1941 const Region bounds(hw->getBounds());
1942
1943 // we remove the scissor part
1944 // we're left with the letterbox region
1945 // (common case is that letterbox ends-up being empty)
1946 const Region letterbox(bounds.subtract(hw->getScissor()));
1947
1948 // compute the area to clear
1949 Region region(hw->undefinedRegion.merge(letterbox));
1950
1951 // but limit it to the dirty region
1952 region.andSelf(dirty);
1953
Mathias Agopianb9494d52012-04-18 02:28:45 -07001954 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001955 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001956 // can happen with SurfaceView
Mathias Agopian55801e42012-08-27 18:54:24 -07001957 drawWormhole(hw, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001958 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001959 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001960
Mathias Agopian766dc492012-10-30 18:08:06 -07001961 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1962 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001963 // scissor on the main display. It should never be needed
1964 // anyways (though in theory it could since the API allows it).
1965 const Rect& bounds(hw->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001966 const Rect& scissor(hw->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001967 if (scissor != bounds) {
1968 // scissor doesn't match the screen's dimensions, so we
1969 // need to clear everything outside of it and enable
1970 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001971
Mathias Agopianf45c5102012-10-24 16:29:17 -07001972 // enable scissor for this frame
Mathias Agopian3f844832013-08-07 21:24:32 -07001973 const uint32_t height = hw->getHeight();
1974 engine.setScissor(scissor.left, height - scissor.bottom,
1975 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001976 }
1977 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001978 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001979
Mathias Agopian85d751c2012-08-29 16:59:24 -07001980 /*
1981 * and then, render the layers targeted at the framebuffer
1982 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001983
Mathias Agopian13127d82013-03-05 17:47:11 -08001984 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001985 const size_t count = layers.size();
1986 const Transform& tr = hw->getTransform();
1987 if (cur != end) {
1988 // we're using h/w composer
1989 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001990 const sp<Layer>& layer(layers[i]);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001991 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07001992 if (!clip.isEmpty()) {
1993 switch (cur->getCompositionType()) {
Riley Andrews03414a12014-07-01 14:22:59 -07001994 case HWC_CURSOR_OVERLAY:
Mathias Agopian85d751c2012-08-29 16:59:24 -07001995 case HWC_OVERLAY: {
Mathias Agopianac683022013-10-01 15:36:52 -07001996 const Layer::State& state(layer->getDrawingState());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001997 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1998 && i
Andy McFadden4125a4f2014-01-29 17:17:11 -08001999 && layer->isOpaque(state) && (state.alpha == 0xFF)
Mathias Agopian85d751c2012-08-29 16:59:24 -07002000 && hasGlesComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001 // never clear the very first layer since we're
2002 // guaranteed the FB is already cleared
2003 layer->clearWithOpenGL(hw, clip);
2004 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002005 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002007 case HWC_FRAMEBUFFER: {
2008 layer->draw(hw, clip);
2009 break;
2010 }
Mathias Agopianda27af92012-09-13 18:17:13 -07002011 case HWC_FRAMEBUFFER_TARGET: {
2012 // this should not happen as the iterator shouldn't
2013 // let us get there.
Greg Hackmann86efcc02014-03-07 12:44:02 -08002014 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
Mathias Agopianda27af92012-09-13 18:17:13 -07002015 break;
2016 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002018 }
2019 layer->setAcquireFence(hw, *cur);
2020 }
2021 } else {
2022 // we're not using h/w composer
2023 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002024 const sp<Layer>& layer(layers[i]);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002025 const Region clip(dirty.intersect(
2026 tr.transform(layer->visibleRegion)));
2027 if (!clip.isEmpty()) {
2028 layer->draw(hw, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002029 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002030 }
2031 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002032
2033 // disable scissor at the end of the frame
Mathias Agopian3f844832013-08-07 21:24:32 -07002034 engine.disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002035 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036}
2037
Mathias Agopian3f844832013-08-07 21:24:32 -07002038void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002039 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002040 RenderEngine& engine(getRenderEngine());
2041 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042}
2043
Dan Stoza7d89d062015-04-30 13:29:25 -07002044status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002045 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002046 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002047 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002048{
Dan Stoza7d89d062015-04-30 13:29:25 -07002049 // add this layer to the current state list
2050 {
2051 Mutex::Autolock _l(mStateLock);
2052 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2053 return NO_MEMORY;
2054 }
2055 mCurrentState.layersSortedByZ.add(lbc);
2056 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2057 }
2058
Mathias Agopian96f08192010-06-02 23:28:45 -07002059 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002060 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002061
Dan Stoza7d89d062015-04-30 13:29:25 -07002062 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002063}
2064
Mathias Agopian3f844832013-08-07 21:24:32 -07002065status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002067 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002069 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002070 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002071 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 return NO_ERROR;
2073 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002074 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002075}
2076
Dan Stozac7014012014-02-14 15:03:43 -08002077uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002078 return android_atomic_release_load(&mTransactionFlags);
2079}
2080
Mathias Agopian3f844832013-08-07 21:24:32 -07002081uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2083}
2084
Mathias Agopian3f844832013-08-07 21:24:32 -07002085uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2087 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002088 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002089 }
2090 return old;
2091}
2092
Mathias Agopian8b33f032012-07-24 20:43:54 -07002093void SurfaceFlinger::setTransactionState(
2094 const Vector<ComposerState>& state,
2095 const Vector<DisplayState>& displays,
2096 uint32_t flags)
2097{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002098 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002099 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002100 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002101
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002102 if (flags & eAnimation) {
2103 // For window updates that are part of an animation we must wait for
2104 // previous animation "frames" to be handled.
2105 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002106 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002107 if (CC_UNLIKELY(err != NO_ERROR)) {
2108 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002109 // caller after a few seconds.
2110 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2111 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002112 mAnimTransactionPending = false;
2113 break;
2114 }
2115 }
2116 }
2117
Mathias Agopiane57f2922012-08-09 16:29:12 -07002118 size_t count = displays.size();
2119 for (size_t i=0 ; i<count ; i++) {
2120 const DisplayState& s(displays[i]);
2121 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002122 }
2123
Mathias Agopiane57f2922012-08-09 16:29:12 -07002124 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002125 for (size_t i=0 ; i<count ; i++) {
2126 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002127 // Here we need to check that the interface we're given is indeed
2128 // one of our own. A malicious client could give us a NULL
2129 // IInterface, or one of its own or even one of our own but a
2130 // different type. All these situations would cause us to crash.
2131 //
2132 // NOTE: it would be better to use RTTI as we could directly check
2133 // that we have a Client*. however, RTTI is disabled in Android.
2134 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002135 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002136 if (binder != NULL) {
2137 String16 desc(binder->getInterfaceDescriptor());
2138 if (desc == ISurfaceComposerClient::descriptor) {
2139 sp<Client> client( static_cast<Client *>(s.client.get()) );
2140 transactionFlags |= setClientStateLocked(client, s.state);
2141 }
2142 }
2143 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002144 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002145
Mathias Agopian386aa982011-11-07 21:58:03 -08002146 if (transactionFlags) {
2147 // this triggers the transaction
2148 setTransactionFlags(transactionFlags);
2149
2150 // if this is a synchronous transaction, wait for it to take effect
2151 // before returning.
2152 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002153 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002154 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002155 if (flags & eAnimation) {
2156 mAnimTransactionPending = true;
2157 }
2158 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002159 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2160 if (CC_UNLIKELY(err != NO_ERROR)) {
2161 // just in case something goes wrong in SF, return to the
2162 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002163 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2164 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002165 break;
2166 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168 }
2169}
2170
Mathias Agopiane57f2922012-08-09 16:29:12 -07002171uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2172{
Jesse Hall9a143922012-10-04 16:29:19 -07002173 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2174 if (dpyIdx < 0)
2175 return 0;
2176
Mathias Agopiane57f2922012-08-09 16:29:12 -07002177 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002178 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002179 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002180 const uint32_t what = s.what;
2181 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002182 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002183 disp.surface = s.surface;
2184 flags |= eDisplayTransactionNeeded;
2185 }
2186 }
2187 if (what & DisplayState::eLayerStackChanged) {
2188 if (disp.layerStack != s.layerStack) {
2189 disp.layerStack = s.layerStack;
2190 flags |= eDisplayTransactionNeeded;
2191 }
2192 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002193 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002194 if (disp.orientation != s.orientation) {
2195 disp.orientation = s.orientation;
2196 flags |= eDisplayTransactionNeeded;
2197 }
2198 if (disp.frame != s.frame) {
2199 disp.frame = s.frame;
2200 flags |= eDisplayTransactionNeeded;
2201 }
2202 if (disp.viewport != s.viewport) {
2203 disp.viewport = s.viewport;
2204 flags |= eDisplayTransactionNeeded;
2205 }
2206 }
Michael Lentine47e45402014-07-18 15:34:25 -07002207 if (what & DisplayState::eDisplaySizeChanged) {
2208 if (disp.width != s.width) {
2209 disp.width = s.width;
2210 flags |= eDisplayTransactionNeeded;
2211 }
2212 if (disp.height != s.height) {
2213 disp.height = s.height;
2214 flags |= eDisplayTransactionNeeded;
2215 }
2216 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002217 }
2218 return flags;
2219}
2220
2221uint32_t SurfaceFlinger::setClientStateLocked(
2222 const sp<Client>& client,
2223 const layer_state_t& s)
2224{
2225 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002226 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002227 if (layer != 0) {
2228 const uint32_t what = s.what;
2229 if (what & layer_state_t::ePositionChanged) {
2230 if (layer->setPosition(s.x, s.y))
2231 flags |= eTraversalNeeded;
2232 }
2233 if (what & layer_state_t::eLayerChanged) {
2234 // NOTE: index needs to be calculated before we update the state
2235 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2236 if (layer->setLayer(s.z)) {
2237 mCurrentState.layersSortedByZ.removeAt(idx);
2238 mCurrentState.layersSortedByZ.add(layer);
2239 // we need traversal (state changed)
2240 // AND transaction (list changed)
2241 flags |= eTransactionNeeded|eTraversalNeeded;
2242 }
2243 }
2244 if (what & layer_state_t::eSizeChanged) {
2245 if (layer->setSize(s.w, s.h)) {
2246 flags |= eTraversalNeeded;
2247 }
2248 }
2249 if (what & layer_state_t::eAlphaChanged) {
2250 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2251 flags |= eTraversalNeeded;
2252 }
2253 if (what & layer_state_t::eMatrixChanged) {
2254 if (layer->setMatrix(s.matrix))
2255 flags |= eTraversalNeeded;
2256 }
2257 if (what & layer_state_t::eTransparentRegionChanged) {
2258 if (layer->setTransparentRegionHint(s.transparentRegion))
2259 flags |= eTraversalNeeded;
2260 }
Dan Stoza23116082015-06-18 14:58:39 -07002261 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002262 if (layer->setFlags(s.flags, s.mask))
2263 flags |= eTraversalNeeded;
2264 }
2265 if (what & layer_state_t::eCropChanged) {
2266 if (layer->setCrop(s.crop))
2267 flags |= eTraversalNeeded;
2268 }
2269 if (what & layer_state_t::eLayerStackChanged) {
2270 // NOTE: index needs to be calculated before we update the state
2271 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2272 if (layer->setLayerStack(s.layerStack)) {
2273 mCurrentState.layersSortedByZ.removeAt(idx);
2274 mCurrentState.layersSortedByZ.add(layer);
2275 // we need traversal (state changed)
2276 // AND transaction (list changed)
2277 flags |= eTransactionNeeded|eTraversalNeeded;
2278 }
2279 }
2280 }
2281 return flags;
2282}
2283
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002284status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002285 const String8& name,
2286 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002287 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2288 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002290 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002291 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002292 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002293 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002294 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002295 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002296
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002297 status_t result = NO_ERROR;
2298
2299 sp<Layer> layer;
2300
Mathias Agopian3165cc22012-08-08 19:42:09 -07002301 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2302 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002303 result = createNormalLayer(client,
2304 name, w, h, flags, format,
2305 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002307 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002308 result = createDimLayer(client,
2309 name, w, h, flags,
2310 handle, gbp, &layer);
2311 break;
2312 default:
2313 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314 break;
2315 }
2316
Dan Stoza7d89d062015-04-30 13:29:25 -07002317 if (result != NO_ERROR) {
2318 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002320
2321 result = addClientLayer(client, *handle, *gbp, layer);
2322 if (result != NO_ERROR) {
2323 return result;
2324 }
2325
2326 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002327 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328}
2329
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002330status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2331 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2332 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333{
2334 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002335 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 case PIXEL_FORMAT_TRANSPARENT:
2337 case PIXEL_FORMAT_TRANSLUCENT:
2338 format = PIXEL_FORMAT_RGBA_8888;
2339 break;
2340 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002341 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 break;
2343 }
2344
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002345 *outLayer = new Layer(this, client, name, w, h, flags);
2346 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2347 if (err == NO_ERROR) {
2348 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002349 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002351
2352 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2353 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002356status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2357 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2358 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002360 *outLayer = new LayerDim(this, client, name, w, h, flags);
2361 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002362 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002363 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002364}
2365
Mathias Agopianac9fa422013-02-11 16:40:36 -08002366status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367{
Mathias Agopian67106042013-03-14 19:18:13 -07002368 // called by the window manager when it wants to remove a Layer
2369 status_t err = NO_ERROR;
2370 sp<Layer> l(client->getLayerUser(handle));
2371 if (l != NULL) {
2372 err = removeLayer(l);
2373 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2374 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002375 }
2376 return err;
2377}
2378
Mathias Agopian13127d82013-03-05 17:47:11 -08002379status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002380{
Mathias Agopian67106042013-03-14 19:18:13 -07002381 // called by ~LayerCleaner() when all references to the IBinder (handle)
2382 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002383 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002384 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002385 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002386 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002387 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002388 "error removing layer=%p (%s)", l.get(), strerror(-err));
2389 }
2390 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391}
2392
Mathias Agopianb60314a2012-04-10 22:09:54 -07002393// ---------------------------------------------------------------------------
2394
Andy McFadden13a082e2012-08-24 10:16:42 -07002395void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002396 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002397 Vector<ComposerState> state;
2398 Vector<DisplayState> displays;
2399 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002400 d.what = DisplayState::eDisplayProjectionChanged |
2401 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002402 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002403 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002404 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002405 d.frame.makeInvalid();
2406 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002407 d.width = 0;
2408 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002409 displays.add(d);
2410 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002411 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002412
2413 const nsecs_t period =
2414 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2415 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002416}
2417
2418void SurfaceFlinger::initializeDisplays() {
2419 class MessageScreenInitialized : public MessageBase {
2420 SurfaceFlinger* flinger;
2421 public:
2422 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2423 virtual bool handler() {
2424 flinger->onInitializeDisplays();
2425 return true;
2426 }
2427 };
2428 sp<MessageBase> msg = new MessageScreenInitialized(this);
2429 postMessageAsync(msg); // we may be called from main thread, use async message
2430}
2431
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002432void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2433 int mode) {
2434 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2435 this);
2436 int32_t type = hw->getDisplayType();
2437 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002438
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002439 if (mode == currentMode) {
2440 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002441 return;
2442 }
2443
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002444 hw->setPowerMode(mode);
2445 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2446 ALOGW("Trying to set power mode for virtual display");
2447 return;
2448 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002449
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002450 if (currentMode == HWC_POWER_MODE_OFF) {
2451 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002452 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2453 // FIXME: eventthread only knows about the main display right now
2454 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002455 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002458 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002459 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002460 repaintEverything();
2461 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002462 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002463 disableHardwareVsync(true); // also cancels any in-progress resync
2464
Mathias Agopiancde87a32012-09-13 14:09:01 -07002465 // FIXME: eventthread only knows about the main display right now
2466 mEventThread->onScreenReleased();
2467 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002468
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002469 getHwComposer().setPowerMode(type, mode);
2470 mVisibleRegionsDirty = true;
2471 // from this point on, SF will stop drawing on this display
2472 } else {
2473 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002474 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002475}
2476
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002477void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2478 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002479 SurfaceFlinger& mFlinger;
2480 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002481 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002482 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002483 MessageSetPowerMode(SurfaceFlinger& flinger,
2484 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2485 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002486 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002487 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002488 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002489 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002490 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002491 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002492 ALOGW("Attempt to set power mode = %d for virtual display",
2493 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002494 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002495 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002496 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002497 return true;
2498 }
2499 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002500 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002501 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002502}
2503
2504// ---------------------------------------------------------------------------
2505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2507{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002509
Mathias Agopianbd115332013-04-18 16:41:04 -07002510 IPCThreadState* ipc = IPCThreadState::self();
2511 const int pid = ipc->getCallingPid();
2512 const int uid = ipc->getCallingUid();
2513 if ((uid != AID_SHELL) &&
2514 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002515 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002516 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002518 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002519 // (this would indicate SF is stuck, but we want to be able to
2520 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002521 status_t err = mStateLock.timedLock(s2ns(1));
2522 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002523 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002524 result.appendFormat(
2525 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2526 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002527 }
2528
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002529 bool dumpAll = true;
2530 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002531 size_t numArgs = args.size();
2532 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002533 if ((index < numArgs) &&
2534 (args[index] == String16("--list"))) {
2535 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002536 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002537 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002538 }
2539
2540 if ((index < numArgs) &&
2541 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002542 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002543 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002544 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002545 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002546
2547 if ((index < numArgs) &&
2548 (args[index] == String16("--latency-clear"))) {
2549 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002550 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002551 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002552 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002553
2554 if ((index < numArgs) &&
2555 (args[index] == String16("--dispsync"))) {
2556 index++;
2557 mPrimaryDispSync.dump(result);
2558 dumpAll = false;
2559 }
Dan Stozab90cf072015-03-05 11:05:59 -08002560
2561 if ((index < numArgs) &&
2562 (args[index] == String16("--static-screen"))) {
2563 index++;
2564 dumpStaticScreenStats(result);
2565 dumpAll = false;
2566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002568
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002569 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002570 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002571 }
2572
Mathias Agopian9795c422009-08-26 16:36:26 -07002573 if (locked) {
2574 mStateLock.unlock();
2575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 }
2577 write(fd, result.string(), result.size());
2578 return NO_ERROR;
2579}
2580
Dan Stozac7014012014-02-14 15:03:43 -08002581void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2582 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002583{
2584 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2585 const size_t count = currentLayers.size();
2586 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002587 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002588 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002589 }
2590}
2591
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002592void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002593 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002594{
2595 String8 name;
2596 if (index < args.size()) {
2597 name = String8(args[index]);
2598 index++;
2599 }
2600
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002601 const nsecs_t period =
2602 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002603 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002604
2605 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002606 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002607 } else {
2608 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2609 const size_t count = currentLayers.size();
2610 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002611 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002612 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002613 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002614 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002615 }
2616 }
2617}
2618
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002619void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002620 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002621{
2622 String8 name;
2623 if (index < args.size()) {
2624 name = String8(args[index]);
2625 index++;
2626 }
2627
2628 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2629 const size_t count = currentLayers.size();
2630 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002631 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002632 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002633 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002634 }
2635 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002636
Svetoslavd85084b2014-03-20 10:28:31 -07002637 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002638}
2639
Jamie Gennis6547ff42013-07-16 20:12:42 -07002640// This should only be called from the main thread. Otherwise it would need
2641// the lock and should use mCurrentState rather than mDrawingState.
2642void SurfaceFlinger::logFrameStats() {
2643 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2644 const size_t count = drawingLayers.size();
2645 for (size_t i=0 ; i<count ; i++) {
2646 const sp<Layer>& layer(drawingLayers[i]);
2647 layer->logFrameStats();
2648 }
2649
2650 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2651}
2652
Andy McFadden4803b742012-09-24 19:07:20 -07002653/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2654{
2655 static const char* config =
2656 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002657#ifdef HAS_CONTEXT_PRIORITY
2658 " HAS_CONTEXT_PRIORITY"
2659#endif
2660#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2661 " NEVER_DEFAULT_TO_ASYNC_MODE"
2662#endif
2663#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2664 " TARGET_DISABLE_TRIPLE_BUFFERING"
2665#endif
2666 "]";
2667 result.append(config);
2668}
2669
Dan Stozab90cf072015-03-05 11:05:59 -08002670void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2671{
2672 result.appendFormat("Static screen stats:\n");
2673 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2674 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2675 float percent = 100.0f *
2676 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2677 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2678 b + 1, bucketTimeSec, percent);
2679 }
2680 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2681 float percent = 100.0f *
2682 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2683 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2684 NUM_BUCKETS - 1, bucketTimeSec, percent);
2685}
2686
Mathias Agopian74d211a2013-04-22 16:55:35 +02002687void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2688 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002689{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002690 bool colorize = false;
2691 if (index < args.size()
2692 && (args[index] == String16("--color"))) {
2693 colorize = true;
2694 index++;
2695 }
2696
2697 Colorizer colorizer(colorize);
2698
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002699 // figure out if we're stuck somewhere
2700 const nsecs_t now = systemTime();
2701 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2702 const nsecs_t inTransaction(mDebugInTransaction);
2703 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2704 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2705
2706 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002707 * Dump library configuration.
2708 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002709
2710 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002711 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002712 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002713 appendSfConfigString(result);
2714 appendUiConfigString(result);
2715 appendGuiConfigString(result);
2716 result.append("\n");
2717
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002718 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002719 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002720 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002721 result.append(SyncFeatures::getInstance().toString());
2722 result.append("\n");
2723
Andy McFadden41d67d72014-04-25 16:58:34 -07002724 colorizer.bold(result);
2725 result.append("DispSync configuration: ");
2726 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002727 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2728 "present offset %d ns (refresh %" PRId64 " ns)",
Andy McFadden41d67d72014-04-25 16:58:34 -07002729 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2730 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2731 result.append("\n");
2732
Dan Stozab90cf072015-03-05 11:05:59 -08002733 // Dump static screen stats
2734 result.append("\n");
2735 dumpStaticScreenStats(result);
2736 result.append("\n");
2737
Andy McFadden4803b742012-09-24 19:07:20 -07002738 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002739 * Dump the visible layer list
2740 */
2741 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2742 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002743 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002744 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002745 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002746 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002747 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002748 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002749 }
2750
2751 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002752 * Dump Display state
2753 */
2754
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002755 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002756 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002757 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002758 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2759 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002760 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002761 }
2762
2763 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002764 * Dump SurfaceFlinger global state
2765 */
2766
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002767 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002768 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002769 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002770
Mathias Agopian888c8222012-08-04 21:10:38 -07002771 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002772 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002773
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002774 colorizer.bold(result);
2775 result.appendFormat("EGL implementation : %s\n",
2776 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2777 colorizer.reset(result);
2778 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002779 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002780
Mathias Agopian875d8e12013-06-07 15:35:48 -07002781 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002782
Mathias Agopian42977342012-08-05 00:40:46 -07002783 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002784 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2785 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002786 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002787 " last eglSwapBuffers() time: %f us\n"
2788 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002789 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002790 " refresh-rate : %f fps\n"
2791 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002792 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002793 " gpu_to_cpu_unsupported : %d\n"
2794 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002795 mLastSwapBufferTime/1000.0,
2796 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002797 mTransactionFlags,
Andy McFaddenb0d1dd32012-09-10 14:08:09 -07002798 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2799 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002800 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002801 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002802
Mathias Agopian74d211a2013-04-22 16:55:35 +02002803 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002804 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002805
Mathias Agopian74d211a2013-04-22 16:55:35 +02002806 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002807 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002808
2809 /*
2810 * VSYNC state
2811 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002812 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002813
2814 /*
2815 * Dump HWComposer state
2816 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002817 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002818 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002819 colorizer.reset(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002820 result.appendFormat(" h/w composer %s and %s\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002821 hwc.initCheck()==NO_ERROR ? "present" : "not present",
Alan Viverette9c5a3332013-09-12 20:04:35 -07002822 (mDebugDisableHWC || mDebugRegion || mDaltonize
2823 || mHasColorMatrix) ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002824 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002825
2826 /*
2827 * Dump gralloc state
2828 */
2829 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2830 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002831}
2832
Mathias Agopian13127d82013-03-05 17:47:11 -08002833const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002834SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002835 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002836 wp<IBinder> dpy;
2837 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2838 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2839 dpy = mDisplays.keyAt(i);
2840 break;
2841 }
2842 }
2843 if (dpy == NULL) {
2844 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2845 // Just use the primary display so we have something to return
2846 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2847 }
2848 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002849}
2850
Keun young Park63f165f2012-08-31 10:53:36 -07002851bool SurfaceFlinger::startDdmConnection()
2852{
2853 void* libddmconnection_dso =
2854 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2855 if (!libddmconnection_dso) {
2856 return false;
2857 }
2858 void (*DdmConnection_start)(const char* name);
2859 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002860 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002861 if (!DdmConnection_start) {
2862 dlclose(libddmconnection_dso);
2863 return false;
2864 }
2865 (*DdmConnection_start)(getServiceName());
2866 return true;
2867}
2868
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869status_t SurfaceFlinger::onTransact(
2870 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2871{
2872 switch (code) {
2873 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002874 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002875 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002877 case CLEAR_ANIMATION_FRAME_STATS:
2878 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002879 case SET_POWER_MODE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 {
2881 // codes that require permission check
2882 IPCThreadState* ipc = IPCThreadState::self();
2883 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002884 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002885 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002886 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002887 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002888 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2889 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002891 break;
2892 }
2893 case CAPTURE_SCREEN:
2894 {
2895 // codes that require permission check
2896 IPCThreadState* ipc = IPCThreadState::self();
2897 const int pid = ipc->getCallingPid();
2898 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002899 if ((uid != AID_GRAPHICS) &&
2900 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002901 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002902 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2903 return PERMISSION_DENIED;
2904 }
2905 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 }
2907 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002908
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002909 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2910 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002911 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002912 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002913 IPCThreadState* ipc = IPCThreadState::self();
2914 const int pid = ipc->getCallingPid();
2915 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002916 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002917 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918 return PERMISSION_DENIED;
2919 }
2920 int n;
2921 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07002922 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07002923 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924 return NO_ERROR;
2925 case 1002: // SHOW_UPDATES
2926 n = data.readInt32();
2927 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07002928 invalidateHwcGeometry();
2929 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07002932 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002933 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002935 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07002936 setTransactionFlags(
2937 eTransactionNeeded|
2938 eDisplayTransactionNeeded|
2939 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002940 return NO_ERROR;
2941 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002942 case 1006:{ // send empty update
2943 signalRefresh();
2944 return NO_ERROR;
2945 }
Mathias Agopian53331da2011-08-22 21:44:41 -07002946 case 1008: // toggle use of hw composer
2947 n = data.readInt32();
2948 mDebugDisableHWC = n ? 1 : 0;
2949 invalidateHwcGeometry();
2950 repaintEverything();
2951 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07002952 case 1009: // toggle use of transform hint
2953 n = data.readInt32();
2954 mDebugDisableTransformHint = n ? 1 : 0;
2955 invalidateHwcGeometry();
2956 repaintEverything();
2957 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07002959 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 reply->writeInt32(0);
2961 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002962 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08002963 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 return NO_ERROR;
2965 case 1013: {
2966 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07002967 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2968 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07002969 return NO_ERROR;
2970 }
2971 case 1014: {
2972 // daltonize
2973 n = data.readInt32();
2974 switch (n % 10) {
2975 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2976 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2977 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2978 }
2979 if (n >= 10) {
2980 mDaltonizer.setMode(Daltonizer::correction);
2981 } else {
2982 mDaltonizer.setMode(Daltonizer::simulation);
2983 }
2984 mDaltonize = n > 0;
2985 invalidateHwcGeometry();
2986 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07002987 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07002989 case 1015: {
2990 // apply a color matrix
2991 n = data.readInt32();
2992 mHasColorMatrix = n ? 1 : 0;
2993 if (n) {
2994 // color matrix is sent as mat3 matrix followed by vec3
2995 // offset, then packed into a mat4 where the last row is
2996 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07002997 for (size_t i = 0 ; i < 4; i++) {
2998 for (size_t j = 0; j < 4; j++) {
2999 mColorMatrix[i][j] = data.readFloat();
3000 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003001 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003002 } else {
3003 mColorMatrix = mat4();
3004 }
3005 invalidateHwcGeometry();
3006 repaintEverything();
3007 return NO_ERROR;
3008 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003009 // This is an experimental interface
3010 // Needs to be shifted to proper binder interface when we productize
3011 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003012 n = data.readInt32();
3013 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003014 return NO_ERROR;
3015 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003016 case 1017: {
3017 n = data.readInt32();
3018 mForceFullDamage = static_cast<bool>(n);
3019 return NO_ERROR;
3020 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003021 case 1018: { // Modify Choreographer's phase offset
3022 n = data.readInt32();
3023 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3024 return NO_ERROR;
3025 }
3026 case 1019: { // Modify SurfaceFlinger's phase offset
3027 n = data.readInt32();
3028 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3029 return NO_ERROR;
3030 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031 }
3032 }
3033 return err;
3034}
3035
Mathias Agopian53331da2011-08-22 21:44:41 -07003036void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003037 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003038 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003039}
3040
Mathias Agopian59119e62010-10-11 12:37:43 -07003041// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003042// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003043// ---------------------------------------------------------------------------
3044
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003045/* The code below is here to handle b/8734824
3046 *
3047 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003048 * from the surfaceflinger thread to the calling binder thread, where they
3049 * are executed. This allows the calling thread in the calling process to be
3050 * reused and not depend on having "enough" binder threads to handle the
3051 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003052 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003053class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003054 /* Parts of GraphicProducerWrapper are run on two different threads,
3055 * communicating by sending messages via Looper but also by shared member
3056 * data. Coherence maintenance is subtle and in places implicit (ugh).
3057 *
3058 * Don't rely on Looper's sendMessage/handleMessage providing
3059 * release/acquire semantics for any data not actually in the Message.
3060 * Data going from surfaceflinger to binder threads needs to be
3061 * synchronized explicitly.
3062 *
3063 * Barrier open/wait do provide release/acquire semantics. This provides
3064 * implicit synchronization for data coming back from binder to
3065 * surfaceflinger threads.
3066 */
3067
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003068 sp<IGraphicBufferProducer> impl;
3069 sp<Looper> looper;
3070 status_t result;
3071 bool exitPending;
3072 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003073 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003074 uint32_t code;
3075 Parcel const* data;
3076 Parcel* reply;
3077
3078 enum {
3079 MSG_API_CALL,
3080 MSG_EXIT
3081 };
3082
3083 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003084 * Called on surfaceflinger thread. This is called by our "fake"
3085 * BpGraphicBufferProducer. We package the data and reply Parcel and
3086 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003087 */
3088 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003089 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003090 this->code = code;
3091 this->data = &data;
3092 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003093 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003094 // if we've exited, we run the message synchronously right here.
3095 // note (JH): as far as I can tell from looking at the code, this
3096 // never actually happens. if it does, i'm not sure if it happens
3097 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003098 handleMessage(Message(MSG_API_CALL));
3099 } else {
3100 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003101 // Prevent stores to this->{code, data, reply} from being
3102 // reordered later than the construction of Message.
3103 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003104 looper->sendMessage(this, Message(MSG_API_CALL));
3105 barrier.wait();
3106 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003107 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003108 }
3109
3110 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003111 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003112 * call the real BpGraphicBufferProducer.
3113 */
3114 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003115 int what = message.what;
3116 // Prevent reads below from happening before the read from Message
3117 atomic_thread_fence(memory_order_acquire);
3118 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003119 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003120 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003121 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003122 exitRequested = true;
3123 }
3124 }
3125
3126public:
Jesse Hallb154c422014-07-13 12:47:02 -07003127 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3128 : impl(impl),
3129 looper(new Looper(true)),
3130 exitPending(false),
3131 exitRequested(false)
3132 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003133
Jesse Hallb154c422014-07-13 12:47:02 -07003134 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003135 status_t waitForResponse() {
3136 do {
3137 looper->pollOnce(-1);
3138 } while (!exitRequested);
3139 return result;
3140 }
3141
Jesse Hallb154c422014-07-13 12:47:02 -07003142 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003143 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003144 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003145 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003146 // Ensure this->result is visible to the binder thread before it
3147 // handles the message.
3148 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003149 looper->sendMessage(this, Message(MSG_EXIT));
3150 }
3151};
3152
3153
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003154status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3155 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003156 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003157 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003158 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003159
3160 if (CC_UNLIKELY(display == 0))
3161 return BAD_VALUE;
3162
3163 if (CC_UNLIKELY(producer == 0))
3164 return BAD_VALUE;
3165
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003166 // if we have secure windows on this display, never allow the screen capture
3167 // unless the producer interface is local (i.e.: we can take a screenshot for
3168 // ourselves).
Marco Nelissen097ca272014-11-14 08:01:01 -08003169 if (!IInterface::asBinder(producer)->localBinder()) {
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003170 Mutex::Autolock _l(mStateLock);
3171 sp<const DisplayDevice> hw(getDisplayDevice(display));
3172 if (hw->getSecureLayerVisible()) {
3173 ALOGW("FB is protected: PERMISSION_DENIED");
3174 return PERMISSION_DENIED;
3175 }
3176 }
3177
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003178 // Convert to surfaceflinger's internal rotation type.
3179 Transform::orientation_flags rotationFlags;
3180 switch (rotation) {
3181 case ISurfaceComposer::eRotateNone:
3182 rotationFlags = Transform::ROT_0;
3183 break;
3184 case ISurfaceComposer::eRotate90:
3185 rotationFlags = Transform::ROT_90;
3186 break;
3187 case ISurfaceComposer::eRotate180:
3188 rotationFlags = Transform::ROT_180;
3189 break;
3190 case ISurfaceComposer::eRotate270:
3191 rotationFlags = Transform::ROT_270;
3192 break;
3193 default:
3194 rotationFlags = Transform::ROT_0;
3195 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3196 break;
3197 }
3198
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003199 class MessageCaptureScreen : public MessageBase {
3200 SurfaceFlinger* flinger;
3201 sp<IBinder> display;
3202 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003203 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003204 uint32_t reqWidth, reqHeight;
3205 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003206 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003207 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003208 status_t result;
3209 public:
3210 MessageCaptureScreen(SurfaceFlinger* flinger,
3211 const sp<IBinder>& display,
3212 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003213 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003214 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003215 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003216 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003217 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003218 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003219 useIdentityTransform(useIdentityTransform),
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003220 rotation(rotation),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003221 result(PERMISSION_DENIED)
3222 {
3223 }
3224 status_t getResult() const {
3225 return result;
3226 }
3227 virtual bool handler() {
3228 Mutex::Autolock _l(flinger->mStateLock);
3229 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003230 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003231 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003232 useIdentityTransform, rotation);
Marco Nelissen097ca272014-11-14 08:01:01 -08003233 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003234 return true;
3235 }
3236 };
3237
Mathias Agopian9eb1f052013-04-10 16:27:17 -07003238 // make sure to process transactions before screenshots -- a transaction
3239 // might already be pending but scheduled for VSYNC; this guarantees we
3240 // will handle it before the screenshot. When VSYNC finally arrives
3241 // the scheduled transaction will be a no-op. If no transactions are
3242 // scheduled at this time, this will end-up being a no-op as well.
3243 mEventQueue.invalidateTransactionNow();
3244
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003245 // this creates a "fake" BBinder which will serve as a "fake" remote
3246 // binder to receive the marshaled calls and forward them to the
3247 // real remote (a BpGraphicBufferProducer)
3248 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3249
3250 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3251 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003252 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003253 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003254 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003255 useIdentityTransform, rotationFlags);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003256
3257 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003258 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003259 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003260 }
3261 return res;
3262}
3263
Mathias Agopian180f10d2013-04-10 22:55:41 -07003264
3265void SurfaceFlinger::renderScreenImplLocked(
3266 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003267 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003268 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003269 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003270{
3271 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003272 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003273
3274 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003275 const int32_t hw_w = hw->getWidth();
3276 const int32_t hw_h = hw->getHeight();
3277 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003278 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003279
Dan Stozac1879002014-05-22 15:59:05 -07003280 // if a default or invalid sourceCrop is passed in, set reasonable values
3281 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3282 !sourceCrop.isValid()) {
3283 sourceCrop.setLeftTop(Point(0, 0));
3284 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3285 }
3286
3287 // ensure that sourceCrop is inside screen
3288 if (sourceCrop.left < 0) {
3289 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3290 }
Dan Stozabe31f442014-06-11 11:20:54 -07003291 if (sourceCrop.right > hw_w) {
3292 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003293 }
3294 if (sourceCrop.top < 0) {
3295 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3296 }
Dan Stozabe31f442014-06-11 11:20:54 -07003297 if (sourceCrop.bottom > hw_h) {
3298 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003299 }
3300
Mathias Agopian180f10d2013-04-10 22:55:41 -07003301 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003302 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003303
3304 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003305 engine.setViewportAndProjection(
3306 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003307 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003308
3309 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003310 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003311
3312 const LayerVector& layers( mDrawingState.layersSortedByZ );
3313 const size_t count = layers.size();
3314 for (size_t i=0 ; i<count ; ++i) {
3315 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003316 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003317 if (state.layerStack == hw->getLayerStack()) {
3318 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3319 if (layer->isVisible()) {
3320 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003321 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003322 if (filtering) layer->setFiltering(false);
3323 }
3324 }
3325 }
3326 }
3327
3328 // compositionComplete is needed for older driver
3329 hw->compositionComplete();
Mathias Agopian931bda12013-08-28 18:11:46 -07003330 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003331}
3332
3333
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003334status_t SurfaceFlinger::captureScreenImplLocked(
3335 const sp<const DisplayDevice>& hw,
3336 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003337 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003338 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003339 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003340{
3341 ATRACE_CALL();
3342
Mathias Agopian180f10d2013-04-10 22:55:41 -07003343 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003344 uint32_t hw_w = hw->getWidth();
3345 uint32_t hw_h = hw->getHeight();
3346
3347 if (rotation & Transform::ROT_90) {
3348 std::swap(hw_w, hw_h);
3349 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003350
Mathias Agopian180f10d2013-04-10 22:55:41 -07003351 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3352 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3353 reqWidth, reqHeight, hw_w, hw_h);
3354 return BAD_VALUE;
3355 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003356
Mathias Agopian180f10d2013-04-10 22:55:41 -07003357 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3358 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3359
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003360 // create a surface (because we're a producer, and we need to
3361 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003362 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003363 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003364
Michael Lentine5a16a622015-05-21 13:48:24 -07003365 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3366 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003367 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3368 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003369
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003370 int err = 0;
3371 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003372 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003373 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3374 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003375
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003376 if (err == NO_ERROR) {
3377 ANativeWindowBuffer* buffer;
3378 /* TODO: Once we have the sync framework everywhere this can use
3379 * server-side waits on the fence that dequeueBuffer returns.
3380 */
3381 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3382 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003383 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003384 // create an EGLImage from the buffer so we can later
3385 // turn it into a texture
3386 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3387 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3388 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003389 // this binds the given EGLImage as a framebuffer for the
3390 // duration of this scope.
3391 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3392 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003393 // this will in fact render into our dequeued buffer
3394 // via an FBO, which means we didn't have to create
3395 // an EGLSurface and therefore we're not
3396 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003397 renderScreenImplLocked(
3398 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3399 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003400
Riley Andrews86639902014-08-15 12:27:24 -07003401 // Attempt to create a sync khr object that can produce a sync point. If that
3402 // isn't available, create a non-dupable sync object in the fallback path and
3403 // wait on it directly.
3404 EGLSyncKHR sync;
3405 if (!DEBUG_SCREENSHOTS) {
3406 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003407 // native fence fd will not be populated until flush() is done.
3408 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003409 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003410 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003411 }
Riley Andrews86639902014-08-15 12:27:24 -07003412 if (sync != EGL_NO_SYNC_KHR) {
3413 // get the sync fd
3414 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3415 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3416 ALOGW("captureScreen: failed to dup sync khr object");
3417 syncFd = -1;
3418 }
3419 eglDestroySyncKHR(mEGLDisplay, sync);
3420 } else {
3421 // fallback path
3422 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3423 if (sync != EGL_NO_SYNC_KHR) {
3424 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3425 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3426 EGLint eglErr = eglGetError();
3427 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3428 ALOGW("captureScreen: fence wait timed out");
3429 } else {
3430 ALOGW_IF(eglErr != EGL_SUCCESS,
3431 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3432 }
3433 eglDestroySyncKHR(mEGLDisplay, sync);
3434 } else {
3435 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3436 }
3437 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003438 if (DEBUG_SCREENSHOTS) {
3439 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3440 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3441 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3442 hw, minLayerZ, maxLayerZ);
3443 delete [] pixels;
3444 }
3445
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003446 } else {
3447 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3448 result = INVALID_OPERATION;
3449 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003450 // destroy our image
3451 eglDestroyImageKHR(mEGLDisplay, image);
3452 } else {
3453 result = BAD_VALUE;
3454 }
Jesse Hallafe2b1f2014-10-21 11:09:17 -07003455 // queueBuffer takes ownership of syncFd
Michael Lentine5a16a622015-05-21 13:48:24 -07003456 result = window->queueBuffer(window, buffer, syncFd);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003457 }
3458 } else {
3459 result = BAD_VALUE;
3460 }
3461 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3462 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003463
Mathias Agopian74c40c02010-09-29 13:02:36 -07003464 return result;
3465}
3466
Mathias Agopiand5556842013-09-19 17:08:37 -07003467void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3468 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003469 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003470 for (size_t y=0 ; y<h ; y++) {
3471 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3472 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003473 if (p[x] != 0xFF000000) return;
3474 }
3475 }
3476 ALOGE("*** we just took a black screenshot ***\n"
3477 "requested minz=%d, maxz=%d, layerStack=%d",
3478 minLayerZ, maxLayerZ, hw->getLayerStack());
3479 const LayerVector& layers( mDrawingState.layersSortedByZ );
3480 const size_t count = layers.size();
3481 for (size_t i=0 ; i<count ; ++i) {
3482 const sp<Layer>& layer(layers[i]);
3483 const Layer::State& state(layer->getDrawingState());
3484 const bool visible = (state.layerStack == hw->getLayerStack())
3485 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3486 && (layer->isVisible());
Greg Hackmann86efcc02014-03-07 12:44:02 -08003487 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003488 visible ? '+' : '-',
3489 i, layer->getName().string(), state.layerStack, state.z,
3490 layer->isVisible(), state.flags, state.alpha);
3491 }
3492 }
3493}
3494
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003495// ---------------------------------------------------------------------------
3496
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003497SurfaceFlinger::LayerVector::LayerVector() {
3498}
3499
3500SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003501 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003502}
3503
3504int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3505 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003506{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003507 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003508 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3509 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003510
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003511 uint32_t ls = l->getCurrentState().layerStack;
3512 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003513 if (ls != rs)
3514 return ls - rs;
3515
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003516 uint32_t lz = l->getCurrentState().z;
3517 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003518 if (lz != rz)
3519 return lz - rz;
3520
3521 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003522}
3523
3524// ---------------------------------------------------------------------------
3525
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003526SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Michael Lentine47e45402014-07-18 15:34:25 -07003527 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003528}
3529
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003530SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
Michael Lentine47e45402014-07-18 15:34:25 -07003531 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003532 viewport.makeInvalid();
3533 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003534}
3535
3536// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003539
3540
3541#if defined(__gl_h_)
3542#error "don't include gl/gl.h in this file"
3543#endif
3544
3545#if defined(__gl2_h_)
3546#error "don't include gl2/gl2.h in this file"
3547#endif