blob: 01ffac29bb663965ce67bd2a63b71ffbac44e8fb [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;
635
636 // This is how far in advance a buffer must be queued for
637 // presentation at a given time. If you want a buffer to appear
638 // on the screen at time N, you must submit the buffer before
639 // (N - presentationDeadline).
640 //
641 // Normally it's one full refresh period (to give SF a chance to
642 // latch the buffer), but this can be reduced by configuring a
643 // DispSync offset. Any additional delays introduced by the hardware
644 // composer or panel must be accounted for here.
645 //
646 // We add an additional 1ms to allow for processing time and
647 // differences between the ideal and actual refresh rate.
648 info.presentationDeadline =
649 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700650
651 // All non-virtual displays are currently considered secure.
652 info.secure = true;
653
654 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700655 }
656
Dan Stoza7f7da322014-05-02 15:26:25 -0700657 return NO_ERROR;
658}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700659
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800660status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700661 DisplayStatInfo* stats) {
662 if (stats == NULL) {
663 return BAD_VALUE;
664 }
665
666 // FIXME for now we always return stats for the primary display
667 memset(stats, 0, sizeof(*stats));
668 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
669 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
670 return NO_ERROR;
671}
672
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700673int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700674 sp<DisplayDevice> device(getDisplayDevice(display));
675 if (device != NULL) {
676 return device->getActiveConfig();
677 }
678 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700679}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700680
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700681void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
682 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
683 this);
684 int32_t type = hw->getDisplayType();
685 int currentMode = hw->getActiveConfig();
686
687 if (mode == currentMode) {
688 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
689 return;
690 }
691
692 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
693 ALOGW("Trying to set config for virtual display");
694 return;
695 }
696
697 hw->setActiveConfig(mode);
698 getHwComposer().setActiveConfig(type, mode);
699}
700
701status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
702 class MessageSetActiveConfig: public MessageBase {
703 SurfaceFlinger& mFlinger;
704 sp<IBinder> mDisplay;
705 int mMode;
706 public:
707 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
708 int mode) :
709 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
710 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700711 Vector<DisplayInfo> configs;
712 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700713 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700714 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700715 mMode, configs.size());
716 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700717 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
718 if (hw == NULL) {
719 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700720 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700721 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
722 ALOGW("Attempt to set active config = %d for virtual display",
723 mMode);
724 } else {
725 mFlinger.setActiveConfigInternal(hw, mMode);
726 }
727 return true;
728 }
729 };
730 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
731 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700732 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700733}
734
Svetoslavd85084b2014-03-20 10:28:31 -0700735status_t SurfaceFlinger::clearAnimationFrameStats() {
736 Mutex::Autolock _l(mStateLock);
737 mAnimFrameTracker.clearStats();
738 return NO_ERROR;
739}
740
741status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
742 Mutex::Autolock _l(mStateLock);
743 mAnimFrameTracker.getStats(outStats);
744 return NO_ERROR;
745}
746
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800747// ----------------------------------------------------------------------------
748
749sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800750 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700751}
752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800753// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800754
755void SurfaceFlinger::waitForEvent() {
756 mEventQueue.waitMessage();
757}
758
759void SurfaceFlinger::signalTransaction() {
760 mEventQueue.invalidate();
761}
762
763void SurfaceFlinger::signalLayerUpdate() {
764 mEventQueue.invalidate();
765}
766
767void SurfaceFlinger::signalRefresh() {
768 mEventQueue.refresh();
769}
770
771status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800772 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800773 return mEventQueue.postMessage(msg, reltime);
774}
775
776status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800777 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800778 status_t res = mEventQueue.postMessage(msg, reltime);
779 if (res == NO_ERROR) {
780 msg->wait();
781 }
782 return res;
783}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700785void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700786 do {
787 waitForEvent();
788 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800789}
790
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700791void SurfaceFlinger::enableHardwareVsync() {
792 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700793 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700794 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700795 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
796 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700797 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700798 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700799}
800
Jesse Hall948fe0c2013-10-14 12:56:09 -0700801void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700802 Mutex::Autolock _l(mHWVsyncLock);
803
Jesse Hall948fe0c2013-10-14 12:56:09 -0700804 if (makeAvailable) {
805 mHWVsyncAvailable = true;
806 } else if (!mHWVsyncAvailable) {
807 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
808 return;
809 }
810
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700811 const nsecs_t period =
812 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
813
814 mPrimaryDispSync.reset();
815 mPrimaryDispSync.setPeriod(period);
816
817 if (!mPrimaryHWVsyncEnabled) {
818 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700819 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
820 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700821 mPrimaryHWVsyncEnabled = true;
822 }
823}
824
Jesse Hall948fe0c2013-10-14 12:56:09 -0700825void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700826 Mutex::Autolock _l(mHWVsyncLock);
827 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700828 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
829 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700830 mPrimaryDispSync.endResync();
831 mPrimaryHWVsyncEnabled = false;
832 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700833 if (makeUnavailable) {
834 mHWVsyncAvailable = false;
835 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700836}
837
838void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700839 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700840
Jamie Gennisd1700752013-10-14 12:22:52 -0700841 { // Scope for the lock
842 Mutex::Autolock _l(mHWVsyncLock);
843 if (type == 0 && mPrimaryHWVsyncEnabled) {
844 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700845 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700846 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700847
848 if (needsHwVsync) {
849 enableHardwareVsync();
850 } else {
851 disableHardwareVsync(false);
852 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700853}
854
855void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
856 if (mEventThread == NULL) {
857 // This is a temporary workaround for b/7145521. A non-null pointer
858 // does not mean EventThread has finished initializing, so this
859 // is not a correct fix.
860 ALOGW("WARNING: EventThread not started, ignoring hotplug");
861 return;
862 }
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700863
Jesse Hall9e663de2013-08-16 14:28:37 -0700864 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700865 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800866 if (connected) {
867 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700868 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800869 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
870 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700871 }
872 setTransactionFlags(eDisplayTransactionNeeded);
873
Andy McFadden9e9689c2012-10-10 18:17:51 -0700874 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700875 }
Mathias Agopian86303202012-07-24 22:46:10 -0700876}
877
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700878void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700879 ATRACE_CALL();
Mathias Agopian81cd5d32012-10-04 02:34:38 -0700880 getHwComposer().eventControl(disp, event, enabled);
Mathias Agopian86303202012-07-24 22:46:10 -0700881}
882
Mathias Agopian4fec8732012-06-29 14:12:52 -0700883void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800884 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800885 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800886 case MessageQueue::TRANSACTION: {
887 handleMessageTransaction();
888 break;
889 }
890 case MessageQueue::INVALIDATE: {
891 bool refreshNeeded = handleMessageTransaction();
892 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800893 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800894 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800895 // Signal a refresh if a transaction modified the window state,
896 // a new buffer was latched, or if HWC has requested a full
897 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800898 signalRefresh();
899 }
900 break;
901 }
902 case MessageQueue::REFRESH: {
903 handleMessageRefresh();
904 break;
905 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800906 }
907}
908
Dan Stoza6b9454d2014-11-07 16:00:59 -0800909bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700910 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700911 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700912 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800913 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700914 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800915 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700916}
917
Dan Stoza6b9454d2014-11-07 16:00:59 -0800918bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700919 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800920 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700921}
922
923void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700924 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700925
926 static nsecs_t previousExpectedPresent = 0;
927 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
928 static bool previousFrameMissed = false;
929 bool frameMissed = (expectedPresent == previousExpectedPresent);
930 if (frameMissed != previousFrameMissed) {
931 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
932 }
933 previousFrameMissed = frameMissed;
934
935 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
936 // Latch buffers, but don't send anything to HWC, then signal another
937 // wakeup for the next vsync
938 preComposition();
939 repaintEverything();
940 } else {
941 preComposition();
942 rebuildLayerStacks();
943 setUpHWComposer();
944 doDebugFlashRegions();
945 doComposition();
946 postComposition();
947 }
948
949 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700950}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700951
Mathias Agopiancd60f992012-08-16 16:28:27 -0700952void SurfaceFlinger::doDebugFlashRegions()
953{
954 // is debugging enabled
955 if (CC_LIKELY(!mDebugRegion))
956 return;
957
958 const bool repaintEverything = mRepaintEverything;
959 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
960 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700961 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700962 // transform the dirty region into this screen's coordinate space
963 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
964 if (!dirtyRegion.isEmpty()) {
965 // redraw the whole screen
966 doComposeSurfaces(hw, Region(hw->bounds()));
967
968 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700969 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -0700970 RenderEngine& engine(getRenderEngine());
971 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
972
Mathias Agopiancd60f992012-08-16 16:28:27 -0700973 hw->compositionComplete();
Mathias Agopianda27af92012-09-13 18:17:13 -0700974 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -0700975 }
976 }
977 }
978
979 postFramebuffer();
980
981 if (mDebugRegion > 1) {
982 usleep(mDebugRegion * 1000);
983 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -0700984
985 HWComposer& hwc(getHwComposer());
986 if (hwc.initCheck() == NO_ERROR) {
987 status_t err = hwc.prepare();
988 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
989 }
Mathias Agopiancd60f992012-08-16 16:28:27 -0700990}
991
992void SurfaceFlinger::preComposition()
993{
994 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700995 const LayerVector& layers(mDrawingState.layersSortedByZ);
996 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700997 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700998 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700999 needExtraInvalidate = true;
1000 }
1001 }
1002 if (needExtraInvalidate) {
1003 signalLayerUpdate();
1004 }
1005}
1006
1007void SurfaceFlinger::postComposition()
1008{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001009 const LayerVector& layers(mDrawingState.layersSortedByZ);
1010 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001011 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001012 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001013 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001014
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001015 const HWComposer& hwc = getHwComposer();
1016 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1017
1018 if (presentFence->isValid()) {
1019 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1020 enableHardwareVsync();
1021 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001022 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001023 }
1024 }
1025
Dan Stozab90cf072015-03-05 11:05:59 -08001026 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001027 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001028 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029 enableHardwareVsync();
1030 }
1031 }
1032
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001033 if (mAnimCompositionPending) {
1034 mAnimCompositionPending = false;
1035
Jesse Halla9a1b002013-02-27 16:39:25 -08001036 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001037 mAnimFrameTracker.setActualPresentFence(presentFence);
1038 } else {
1039 // The HWC doesn't support present fences, so use the refresh
1040 // timestamp instead.
1041 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1042 mAnimFrameTracker.setActualPresentTime(presentTime);
1043 }
1044 mAnimFrameTracker.advanceFrame();
1045 }
Dan Stozab90cf072015-03-05 11:05:59 -08001046
1047 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1048 return;
1049 }
1050
1051 nsecs_t currentTime = systemTime();
1052 if (mHasPoweredOff) {
1053 mHasPoweredOff = false;
1054 } else {
1055 nsecs_t period = mPrimaryDispSync.getPeriod();
1056 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1057 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1058 if (numPeriods < NUM_BUCKETS - 1) {
1059 mFrameBuckets[numPeriods] += elapsedTime;
1060 } else {
1061 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1062 }
1063 mTotalTime += elapsedTime;
1064 }
1065 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001066}
1067
1068void SurfaceFlinger::rebuildLayerStacks() {
1069 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001070 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001071 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001072 mVisibleRegionsDirty = false;
1073 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001074
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001075 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001076 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001077 Region opaqueRegion;
1078 Region dirtyRegion;
Mathias Agopian13127d82013-03-05 17:47:11 -08001079 Vector< sp<Layer> > layersSortedByZ;
Mathias Agopian42977342012-08-05 00:40:46 -07001080 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001081 const Transform& tr(hw->getTransform());
1082 const Rect bounds(hw->getBounds());
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001083 if (hw->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001084 SurfaceFlinger::computeVisibleRegions(layers,
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001085 hw->getLayerStack(), dirtyRegion, opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001086
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001087 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001088 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001089 const sp<Layer>& layer(layers[i]);
1090 const Layer::State& s(layer->getDrawingState());
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001091 if (s.layerStack == hw->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001092 Region drawRegion(tr.transform(
1093 layer->visibleNonTransparentRegion));
1094 drawRegion.andSelf(bounds);
1095 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001096 layersSortedByZ.add(layer);
1097 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001098 }
1099 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001100 }
Mathias Agopian42977342012-08-05 00:40:46 -07001101 hw->setVisibleLayersSortedByZ(layersSortedByZ);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001102 hw->undefinedRegion.set(bounds);
1103 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1104 hw->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001105 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001106 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001107}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001108
Mathias Agopiancd60f992012-08-16 16:28:27 -07001109void SurfaceFlinger::setUpHWComposer() {
Jesse Hall028dc8f2013-08-20 16:35:32 -07001110 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001111 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1112 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1113 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1114
1115 // If nothing has changed (!dirty), don't recompose.
1116 // If something changed, but we don't currently have any visible layers,
1117 // and didn't when we last did a composition, then skip it this time.
1118 // The second rule does two things:
1119 // - When all layers are removed from a display, we'll emit one black
1120 // frame, then nothing more until we get new layers.
1121 // - When a display is created with a private layer stack, we won't
1122 // emit any black frames until a layer is added to the layer stack.
1123 bool mustRecompose = dirty && !(empty && wasEmpty);
1124
1125 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1126 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1127 mustRecompose ? "doing" : "skipping",
1128 dirty ? "+" : "-",
1129 empty ? "+" : "-",
1130 wasEmpty ? "+" : "-");
1131
Dan Stoza71433162014-02-04 16:22:36 -08001132 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001133
1134 if (mustRecompose) {
1135 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1136 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001137 }
1138
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001139 HWComposer& hwc(getHwComposer());
1140 if (hwc.initCheck() == NO_ERROR) {
1141 // build the h/w work list
Jamie Gennisa4310c82012-09-25 20:26:00 -07001142 if (CC_UNLIKELY(mHwWorkListDirty)) {
1143 mHwWorkListDirty = false;
1144 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1145 sp<const DisplayDevice> hw(mDisplays[dpy]);
1146 const int32_t id = hw->getHwcDisplayId();
1147 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001148 const Vector< sp<Layer> >& currentLayers(
Jamie Gennisa4310c82012-09-25 20:26:00 -07001149 hw->getVisibleLayersSortedByZ());
1150 const size_t count = currentLayers.size();
1151 if (hwc.createWorkList(id, count) == NO_ERROR) {
1152 HWComposer::LayerListIterator cur = hwc.begin(id);
1153 const HWComposer::LayerListIterator end = hwc.end(id);
1154 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001155 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001156 layer->setGeometry(hw, *cur);
Alan Viverette9c5a3332013-09-12 20:04:35 -07001157 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
Jamie Gennisa4310c82012-09-25 20:26:00 -07001158 cur->setSkip(true);
1159 }
1160 }
1161 }
1162 }
1163 }
1164 }
1165
1166 // set the per-frame data
Mathias Agopian92a979a2012-08-02 18:32:23 -07001167 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001168 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001169 const int32_t id = hw->getHwcDisplayId();
1170 if (id >= 0) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001171 const Vector< sp<Layer> >& currentLayers(
Mathias Agopiancd60f992012-08-16 16:28:27 -07001172 hw->getVisibleLayersSortedByZ());
Mathias Agopiane60b0682012-08-21 23:34:09 -07001173 const size_t count = currentLayers.size();
Jamie Gennisa4310c82012-09-25 20:26:00 -07001174 HWComposer::LayerListIterator cur = hwc.begin(id);
1175 const HWComposer::LayerListIterator end = hwc.end(id);
1176 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1177 /*
1178 * update the per-frame h/w composer data for each layer
1179 * and build the transparent region of the FB
1180 */
Mathias Agopian13127d82013-03-05 17:47:11 -08001181 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennisa4310c82012-09-25 20:26:00 -07001182 layer->setPerFrameData(hw, *cur);
Mathias Agopian1e260872012-08-08 18:35:12 -07001183 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001184 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001185 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001186
Riley Andrews03414a12014-07-01 14:22:59 -07001187 // If possible, attempt to use the cursor overlay on each display.
1188 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1189 sp<const DisplayDevice> hw(mDisplays[dpy]);
1190 const int32_t id = hw->getHwcDisplayId();
1191 if (id >= 0) {
1192 const Vector< sp<Layer> >& currentLayers(
1193 hw->getVisibleLayersSortedByZ());
1194 const size_t count = currentLayers.size();
1195 HWComposer::LayerListIterator cur = hwc.begin(id);
1196 const HWComposer::LayerListIterator end = hwc.end(id);
1197 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1198 const sp<Layer>& layer(currentLayers[i]);
1199 if (layer->isPotentialCursor()) {
1200 cur->setIsCursorLayerHint();
1201 break;
1202 }
1203 }
1204 }
1205 }
1206
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001207 status_t err = hwc.prepare();
1208 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
Jesse Hall38efe862013-04-06 23:12:29 -07001209
1210 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1211 sp<const DisplayDevice> hw(mDisplays[dpy]);
1212 hw->prepareFrame(hwc);
1213 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001214 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001215}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001216
Mathias Agopiancd60f992012-08-16 16:28:27 -07001217void SurfaceFlinger::doComposition() {
1218 ATRACE_CALL();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001219 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001220 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001221 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001222 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001223 // transform the dirty region into this screen's coordinate space
1224 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001225
1226 // repaint the framebuffer (if needed)
1227 doDisplayComposition(hw, dirtyRegion);
1228
Mathias Agopiancd60f992012-08-16 16:28:27 -07001229 hw->dirtyRegion.clear();
1230 hw->flip(hw->swapRegion);
1231 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001232 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001233 // inform the h/w that we're done compositing
Mathias Agopian42977342012-08-05 00:40:46 -07001234 hw->compositionComplete();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001235 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001236 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001237}
1238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239void SurfaceFlinger::postFramebuffer()
1240{
Mathias Agopian841cde52012-03-01 15:44:37 -08001241 ATRACE_CALL();
Mathias Agopianb048cef2012-02-04 15:44:04 -08001242
Mathias Agopiana44b0412011-10-16 18:46:35 -07001243 const nsecs_t now = systemTime();
1244 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001245
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001246 HWComposer& hwc(getHwComposer());
Jesse Hallef194142012-06-14 14:45:17 -07001247 if (hwc.initCheck() == NO_ERROR) {
Mathias Agopian2a231842012-09-24 18:12:35 -07001248 if (!hwc.supportsFramebufferTarget()) {
1249 // EGL spec says:
1250 // "surface must be bound to the calling thread's current context,
1251 // for the current rendering API."
Mathias Agopian875d8e12013-06-07 15:35:48 -07001252 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopian2a231842012-09-24 18:12:35 -07001253 }
Mathias Agopiane60b0682012-08-21 23:34:09 -07001254 hwc.commit();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001255 }
1256
Mathias Agopian6da15f42013-09-25 20:40:07 -07001257 // make the default display current because the VirtualDisplayDevice code cannot
1258 // deal with dequeueBuffer() being called outside of the composition loop; however
1259 // the code below can call glFlush() which is allowed (and does in some case) call
1260 // dequeueBuffer().
1261 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1262
Mathias Agopian92a979a2012-08-02 18:32:23 -07001263 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001264 sp<const DisplayDevice> hw(mDisplays[dpy]);
Mathias Agopian13127d82013-03-05 17:47:11 -08001265 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
Mathias Agopianda27af92012-09-13 18:17:13 -07001266 hw->onSwapBuffersCompleted(hwc);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001267 const size_t count = currentLayers.size();
Mathias Agopiane60b0682012-08-21 23:34:09 -07001268 int32_t id = hw->getHwcDisplayId();
1269 if (id >=0 && hwc.initCheck() == NO_ERROR) {
Mathias Agopian1e260872012-08-08 18:35:12 -07001270 HWComposer::LayerListIterator cur = hwc.begin(id);
1271 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001272 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001273 currentLayers[i]->onLayerDisplayed(hw, &*cur);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001274 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001275 } else {
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001276 for (size_t i = 0; i < count; i++) {
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001277 currentLayers[i]->onLayerDisplayed(hw, NULL);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001278 }
Jesse Hallef194142012-06-14 14:45:17 -07001279 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001280 }
1281
Mathias Agopiana44b0412011-10-16 18:46:35 -07001282 mLastSwapBufferTime = systemTime() - now;
1283 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001284
1285 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1286 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1287 logFrameStats();
1288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001289}
1290
Mathias Agopian87baae12012-07-31 12:38:26 -07001291void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292{
Mathias Agopian841cde52012-03-01 15:44:37 -08001293 ATRACE_CALL();
1294
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001295 // here we keep a copy of the drawing state (that is the state that's
1296 // going to be overwritten by handleTransactionLocked()) outside of
1297 // mStateLock so that the side-effects of the State assignment
1298 // don't happen with mStateLock held (which can cause deadlocks).
1299 State drawingState(mDrawingState);
1300
Mathias Agopianca4d3602011-05-19 15:38:14 -07001301 Mutex::Autolock _l(mStateLock);
1302 const nsecs_t now = systemTime();
1303 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001304
Mathias Agopianca4d3602011-05-19 15:38:14 -07001305 // Here we're guaranteed that some transaction flags are set
1306 // so we can call handleTransactionLocked() unconditionally.
1307 // We call getTransactionFlags(), which will also clear the flags,
1308 // with mStateLock held to guarantee that mCurrentState won't change
1309 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001310
Mathias Agopiane57f2922012-08-09 16:29:12 -07001311 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001312 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001313
Mathias Agopianca4d3602011-05-19 15:38:14 -07001314 mLastTransactionTime = systemTime() - now;
1315 mDebugInTransaction = 0;
1316 invalidateHwcGeometry();
1317 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001318}
1319
Mathias Agopian87baae12012-07-31 12:38:26 -07001320void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001321{
1322 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001323 const size_t count = currentLayers.size();
1324
1325 /*
1326 * Traversal of the children
1327 * (perform the transaction for each of them if needed)
1328 */
1329
Mathias Agopian3559b072012-08-15 13:46:03 -07001330 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001331 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001332 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001333 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1334 if (!trFlags) continue;
1335
1336 const uint32_t flags = layer->doTransaction(0);
1337 if (flags & Layer::eVisibleRegion)
1338 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001339 }
1340 }
1341
1342 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001343 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344 */
1345
Mathias Agopiane57f2922012-08-09 16:29:12 -07001346 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001347 // here we take advantage of Vector's copy-on-write semantics to
1348 // improve performance by skipping the transaction entirely when
1349 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001350 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1351 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001352 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001353 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001354 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001355 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001356
1357 // find the displays that were removed
1358 // (ie: in drawing state but not in current state)
1359 // also handle displays that changed
1360 // (ie: displays that are in both lists)
1361 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001362 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1363 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001364 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001365 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001366 // Call makeCurrent() on the primary display so we can
1367 // be sure that nothing associated with this display
1368 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001369 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001370 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001371 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1372 if (hw != NULL)
1373 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001374 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001375 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001376 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001377 } else {
1378 ALOGW("trying to remove the main display");
1379 }
1380 } else {
1381 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001382 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001383 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001384 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1385 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001386 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001387 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001388 // recreating the DisplayDevice, so we just remove it
1389 // from the drawing state, so that it get re-added
1390 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001391 sp<DisplayDevice> hw(getDisplayDevice(display));
1392 if (hw != NULL)
1393 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001394 mDisplays.removeItem(display);
1395 mDrawingState.displays.removeItemsAt(i);
1396 dc--; i--;
1397 // at this point we must loop to the next item
1398 continue;
1399 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001400
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001401 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001402 if (disp != NULL) {
1403 if (state.layerStack != draw[i].layerStack) {
1404 disp->setLayerStack(state.layerStack);
1405 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001406 if ((state.orientation != draw[i].orientation)
1407 || (state.viewport != draw[i].viewport)
1408 || (state.frame != draw[i].frame))
1409 {
1410 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001411 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001412 }
Michael Lentine47e45402014-07-18 15:34:25 -07001413 if (state.width != draw[i].width || state.height != draw[i].height) {
1414 disp->setDisplaySize(state.width, state.height);
1415 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001416 }
1417 }
1418 }
1419
1420 // find displays that were added
1421 // (ie: in current state but not in drawing state)
1422 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001423 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001424 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001425
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001426 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001427 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001428 sp<IGraphicBufferProducer> bqProducer;
1429 sp<IGraphicBufferConsumer> bqConsumer;
1430 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1431 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001432
Jesse Hall02d86562013-03-25 14:43:23 -07001433 int32_t hwcDisplayId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001434 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001435 // Virtual displays without a surface are dormant:
1436 // they have external state (layer stack, projection,
1437 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001438 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001439
Dan Stoza1f3efb12014-10-15 16:34:55 -07001440 int width = 0;
1441 int status = state.surface->query(
1442 NATIVE_WINDOW_WIDTH, &width);
1443 ALOGE_IF(status != NO_ERROR,
1444 "Unable to query width (%d)", status);
1445 int height = 0;
1446 status = state.surface->query(
1447 NATIVE_WINDOW_HEIGHT, &height);
1448 ALOGE_IF(status != NO_ERROR,
1449 "Unable to query height (%d)", status);
1450 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1451 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1452 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1453 hwcDisplayId = allocateHwcDisplayId(state.type);
1454 }
1455
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001456 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
Dan Stozab9b08832014-03-13 11:55:57 -07001457 *mHwc, hwcDisplayId, state.surface,
1458 bqProducer, bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001459
1460 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001461 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001462 }
1463 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001464 ALOGE_IF(state.surface!=NULL,
1465 "adding a supported display, but rendering "
1466 "surface is provided (%p), ignoring it",
1467 state.surface.get());
Jesse Hall02d86562013-03-25 14:43:23 -07001468 hwcDisplayId = allocateHwcDisplayId(state.type);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001469 // for supported (by hwc) displays we provide our
1470 // own rendering surface
Dan Stozab9b08832014-03-13 11:55:57 -07001471 dispSurface = new FramebufferSurface(*mHwc, state.type,
1472 bqConsumer);
1473 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001474 }
1475
1476 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001477 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001478 sp<DisplayDevice> hw = new DisplayDevice(this,
Jesse Hall19e87292013-12-23 21:02:15 -08001479 state.type, hwcDisplayId,
1480 mHwc->getFormat(hwcDisplayId), state.isSecure,
Jesse Hall05f8c702013-12-23 20:44:38 -08001481 display, dispSurface, producer,
1482 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001483 hw->setLayerStack(state.layerStack);
1484 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001485 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001486 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001487 mDisplays.add(display, hw);
Jesse Hall1c569c42013-04-05 13:44:52 -07001488 if (state.isVirtualDisplay()) {
1489 if (hwcDisplayId >= 0) {
1490 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1491 hw->getWidth(), hw->getHeight(),
1492 hw->getFormat());
1493 }
1494 } else {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001495 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001496 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001497 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001498 }
1499 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001501 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001502
Mathias Agopian84300952012-11-21 16:02:13 -08001503 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1504 // The transform hint might have changed for some layers
1505 // (either because a display has changed, or because a layer
1506 // as changed).
1507 //
1508 // Walk through all the layers in currentLayers,
1509 // and update their transform hint.
1510 //
1511 // If a layer is visible only on a single display, then that
1512 // display is used to calculate the hint, otherwise we use the
1513 // default display.
1514 //
1515 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1516 // the hint is set before we acquire a buffer from the surface texture.
1517 //
1518 // NOTE: layer transactions have taken place already, so we use their
1519 // drawing state. However, SurfaceFlinger's own transaction has not
1520 // happened yet, so we must use the current state layer list
1521 // (soon to become the drawing state list).
1522 //
1523 sp<const DisplayDevice> disp;
1524 uint32_t currentlayerStack = 0;
1525 for (size_t i=0; i<count; i++) {
1526 // NOTE: we rely on the fact that layers are sorted by
1527 // layerStack first (so we don't have to traverse the list
1528 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001529 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001530 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001531 if (i==0 || currentlayerStack != layerStack) {
1532 currentlayerStack = layerStack;
1533 // figure out if this layerstack is mirrored
1534 // (more than one display) if so, pick the default display,
1535 // if not, pick the only display it's on.
1536 disp.clear();
1537 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1538 sp<const DisplayDevice> hw(mDisplays[dpy]);
1539 if (hw->getLayerStack() == currentlayerStack) {
1540 if (disp == NULL) {
1541 disp = hw;
1542 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001543 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001544 break;
1545 }
1546 }
1547 }
1548 }
Chet Haase91d25932013-04-11 15:24:55 -07001549 if (disp == NULL) {
1550 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1551 // redraw after transform hint changes. See bug 8508397.
1552
1553 // could be null when this layer is using a layerStack
1554 // that is not visible on any display. Also can occur at
1555 // screen off/on times.
1556 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001557 }
Chet Haase91d25932013-04-11 15:24:55 -07001558 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001559 }
1560 }
1561
1562
Mathias Agopian3559b072012-08-15 13:46:03 -07001563 /*
1564 * Perform our own transaction if needed
1565 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001566
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001567 const LayerVector& layers(mDrawingState.layersSortedByZ);
1568 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001569 // layers have been added
1570 mVisibleRegionsDirty = true;
1571 }
1572
1573 // some layers might have been removed, so
1574 // we need to update the regions they're exposing.
1575 if (mLayersRemoved) {
1576 mLayersRemoved = false;
1577 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001578 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001579 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001580 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001581 if (currentLayers.indexOf(layer) < 0) {
1582 // this layer is not visible anymore
1583 // TODO: we could traverse the tree from front to back and
1584 // compute the actual visible region
1585 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001586 const Layer::State& s(layer->getDrawingState());
Mathias Agopian1501d542012-09-04 21:04:09 -07001587 Region visibleReg = s.transform.transform(
1588 Region(Rect(s.active.w, s.active.h)));
1589 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001590 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001591 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001592 }
1593
1594 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001595
1596 updateCursorAsync();
1597}
1598
1599void SurfaceFlinger::updateCursorAsync()
1600{
1601 HWComposer& hwc(getHwComposer());
1602 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1603 sp<const DisplayDevice> hw(mDisplays[dpy]);
1604 const int32_t id = hw->getHwcDisplayId();
1605 if (id < 0) {
1606 continue;
1607 }
1608 const Vector< sp<Layer> >& currentLayers(
1609 hw->getVisibleLayersSortedByZ());
1610 const size_t count = currentLayers.size();
1611 HWComposer::LayerListIterator cur = hwc.begin(id);
1612 const HWComposer::LayerListIterator end = hwc.end(id);
1613 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1614 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1615 continue;
1616 }
1617 const sp<Layer>& layer(currentLayers[i]);
1618 Rect cursorPos = layer->getPosition(hw);
1619 hwc.setCursorPositionAsync(id, cursorPos);
1620 break;
1621 }
1622 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001623}
1624
1625void SurfaceFlinger::commitTransaction()
1626{
1627 if (!mLayersPendingRemoval.isEmpty()) {
1628 // Notify removed layers now that they can't be drawn from
1629 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1630 mLayersPendingRemoval[i]->onRemoved();
1631 }
1632 mLayersPendingRemoval.clear();
1633 }
1634
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001635 // If this transaction is part of a window animation then the next frame
1636 // we composite should be considered an animation as well.
1637 mAnimCompositionPending = mAnimTransactionPending;
1638
Mathias Agopian4fec8732012-06-29 14:12:52 -07001639 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001640 mTransactionPending = false;
1641 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001642 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001643}
1644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001646 const LayerVector& currentLayers, uint32_t layerStack,
1647 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001648{
Mathias Agopian841cde52012-03-01 15:44:37 -08001649 ATRACE_CALL();
1650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001651 Region aboveOpaqueLayers;
1652 Region aboveCoveredLayers;
1653 Region dirty;
1654
Mathias Agopian87baae12012-07-31 12:38:26 -07001655 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001656
1657 size_t i = currentLayers.size();
1658 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001659 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001660
1661 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001662 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001663
Jesse Hall01e29052013-02-19 16:13:35 -08001664 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001665 if (s.layerStack != layerStack)
1666 continue;
1667
Mathias Agopianab028732010-03-16 16:41:46 -07001668 /*
1669 * opaqueRegion: area of a surface that is fully opaque.
1670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001671 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001672
1673 /*
1674 * visibleRegion: area of a surface that is visible on screen
1675 * and not fully transparent. This is essentially the layer's
1676 * footprint minus the opaque regions above it.
1677 * Areas covered by a translucent surface are considered visible.
1678 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001679 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001680
1681 /*
1682 * coveredRegion: area of a surface that is covered by all
1683 * visible regions above it (which includes the translucent areas).
1684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001685 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001686
Jesse Halla8026d22012-09-25 13:25:04 -07001687 /*
1688 * transparentRegion: area of a surface that is hinted to be completely
1689 * transparent. This is only used to tell when the layer has no visible
1690 * non-transparent regions and can be removed from the layer list. It
1691 * does not affect the visibleRegion of this layer or any layers
1692 * beneath it. The hint may not be correct if apps don't respect the
1693 * SurfaceView restrictions (which, sadly, some don't).
1694 */
1695 Region transparentRegion;
1696
Mathias Agopianab028732010-03-16 16:41:46 -07001697
1698 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001699 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001700 const bool translucent = !layer->isOpaque(s);
Mathias Agopian5219a062013-02-26 16:37:53 -08001701 Rect bounds(s.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001702 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001703 if (!visibleRegion.isEmpty()) {
1704 // Remove the transparent area from the visible region
1705 if (translucent) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706 const Transform tr(s.transform);
1707 if (tr.transformed()) {
1708 if (tr.preserveRects()) {
1709 // transform the transparent region
Mathias Agopian2ca79392013-04-02 18:30:32 -07001710 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711 } else {
1712 // transformation too complex, can't do the
1713 // transparent region optimization.
Jesse Halla8026d22012-09-25 13:25:04 -07001714 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001715 }
1716 } else {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001717 transparentRegion = s.activeTransparentRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001718 }
Mathias Agopianab028732010-03-16 16:41:46 -07001719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001720
Mathias Agopianab028732010-03-16 16:41:46 -07001721 // compute the opaque region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001722 const int32_t layerOrientation = s.transform.getOrientation();
Mathias Agopianab028732010-03-16 16:41:46 -07001723 if (s.alpha==255 && !translucent &&
1724 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1725 // the opaque region is the layer's footprint
1726 opaqueRegion = visibleRegion;
1727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001728 }
1729 }
1730
Mathias Agopianab028732010-03-16 16:41:46 -07001731 // Clip the covered region to the visible region
1732 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1733
1734 // Update aboveCoveredLayers for next (lower) layer
1735 aboveCoveredLayers.orSelf(visibleRegion);
1736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001737 // subtract the opaque region covered by the layers above us
1738 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001739
1740 // compute this layer's dirty region
1741 if (layer->contentDirty) {
1742 // we need to invalidate the whole region
1743 dirty = visibleRegion;
1744 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001745 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001746 layer->contentDirty = false;
1747 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001748 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001749 * the exposed region consists of two components:
1750 * 1) what's VISIBLE now and was COVERED before
1751 * 2) what's EXPOSED now less what was EXPOSED before
1752 *
1753 * note that (1) is conservative, we start with the whole
1754 * visible region but only keep what used to be covered by
1755 * something -- which mean it may have been exposed.
1756 *
1757 * (2) handles areas that were not covered by anything but got
1758 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001759 */
Mathias Agopianab028732010-03-16 16:41:46 -07001760 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001761 const Region oldVisibleRegion = layer->visibleRegion;
1762 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001763 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1764 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765 }
1766 dirty.subtractSelf(aboveOpaqueLayers);
1767
1768 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001769 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001770
Mathias Agopianab028732010-03-16 16:41:46 -07001771 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001772 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001773
Jesse Halla8026d22012-09-25 13:25:04 -07001774 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001775 layer->setVisibleRegion(visibleRegion);
1776 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001777 layer->setVisibleNonTransparentRegion(
1778 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779 }
1780
Mathias Agopian87baae12012-07-31 12:38:26 -07001781 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001782}
1783
Mathias Agopian87baae12012-07-31 12:38:26 -07001784void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1785 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001786 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001787 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1788 if (hw->getLayerStack() == layerStack) {
1789 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001790 }
1791 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001792}
1793
Dan Stoza6b9454d2014-11-07 16:00:59 -08001794bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795{
Mathias Agopian4fec8732012-06-29 14:12:52 -07001796 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797
Mathias Agopian4fec8732012-06-29 14:12:52 -07001798 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001799 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001800 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001801
1802 // Store the set of layers that need updates. This set must not change as
1803 // buffers are being latched, as this could result in a deadlock.
1804 // Example: Two producers share the same command stream and:
1805 // 1.) Layer 0 is latched
1806 // 2.) Layer 0 gets a new frame
1807 // 2.) Layer 1 gets a new frame
1808 // 3.) Layer 1 is latched.
1809 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1810 // second frame. But layer 0's second frame could be waiting on display.
1811 Vector<Layer*> layersWithQueuedFrames;
1812 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001813 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001814 if (layer->hasQueuedFrame()) {
1815 frameQueued = true;
1816 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1817 layersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001818 } else {
1819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001820 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001821 } else {
1822 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001823 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001824 }
1825 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1826 Layer* layer = layersWithQueuedFrames[i];
Mathias Agopian87baae12012-07-31 12:38:26 -07001827 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001828 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001829 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001830 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001831 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001832
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001833 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001834
1835 // If we will need to wake up at some time in the future to deal with a
1836 // queued frame that shouldn't be displayed during this vsync period, wake
1837 // up during the next vsync period to check again.
1838 if (frameQueued && layersWithQueuedFrames.empty()) {
1839 signalLayerUpdate();
1840 }
1841
1842 // Only continue with the refresh if there is actually new work to do
1843 return !layersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001844}
1845
Mathias Agopianad456f92011-01-13 17:53:01 -08001846void SurfaceFlinger::invalidateHwcGeometry()
1847{
1848 mHwWorkListDirty = true;
1849}
1850
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001851
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001853 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001854{
Dan Stoza71433162014-02-04 16:22:36 -08001855 // We only need to actually compose the display if:
1856 // 1) It is being handled by hardware composer, which may need this to
1857 // keep its virtual display state machine in sync, or
1858 // 2) There is work to be done (the dirty region isn't empty)
1859 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1860 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1861 return;
1862 }
1863
Mathias Agopian87baae12012-07-31 12:38:26 -07001864 Region dirtyRegion(inDirtyRegion);
1865
Mathias Agopianb8a55602009-06-26 19:06:36 -07001866 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001867 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001868
Mathias Agopian42977342012-08-05 00:40:46 -07001869 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001870 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001871 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1872 // takes a rectangle, we must make sure to update that whole
1873 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001874 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001875 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001876 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001877 // We need to redraw the rectangle that will be updated
1878 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001879 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001880 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001881 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001882 } else {
1883 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001884 dirtyRegion.set(hw->bounds());
1885 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886 }
1887 }
1888
Alan Viverette9c5a3332013-09-12 20:04:35 -07001889 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001890 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001891 } else {
1892 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001893 mat4 colorMatrix = mColorMatrix;
1894 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001895 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001896 }
Dan Stozaf0087992014-10-20 15:46:09 -07001897 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001898 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001899 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001900 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001901
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001902 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001903 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001904
1905 // swap buffers (presentation)
1906 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001907}
1908
Michael Lentine3f121fc2014-10-01 11:17:28 -07001909bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001910{
Mathias Agopian3f844832013-08-07 21:24:32 -07001911 RenderEngine& engine(getRenderEngine());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001912 const int32_t id = hw->getHwcDisplayId();
Mathias Agopian86303202012-07-24 22:46:10 -07001913 HWComposer& hwc(getHwComposer());
Mathias Agopian1e260872012-08-08 18:35:12 -07001914 HWComposer::LayerListIterator cur = hwc.begin(id);
1915 const HWComposer::LayerListIterator end = hwc.end(id);
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001916
Jesse Halld05a17f2013-09-30 16:49:30 -07001917 bool hasGlesComposition = hwc.hasGlesComposition(id);
Mathias Agopian85d751c2012-08-29 16:59:24 -07001918 if (hasGlesComposition) {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001919 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001920 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1921 hw->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001922 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1923 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1924 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1925 }
1926 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001927 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001928
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001929 // Never touch the framebuffer if we don't have any framebuffer layers
Mathias Agopian85d751c2012-08-29 16:59:24 -07001930 const bool hasHwcComposition = hwc.hasHwcComposition(id);
Mathias Agopiane60b0682012-08-21 23:34:09 -07001931 if (hasHwcComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001932 // when using overlays, we assume a fully transparent framebuffer
1933 // NOTE: we could reduce how much we need to clear, for instance
1934 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001935 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001936 // We'll revisit later if needed.
Mathias Agopian3f844832013-08-07 21:24:32 -07001937 engine.clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001938 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001939 // we start with the whole screen area
1940 const Region bounds(hw->getBounds());
1941
1942 // we remove the scissor part
1943 // we're left with the letterbox region
1944 // (common case is that letterbox ends-up being empty)
1945 const Region letterbox(bounds.subtract(hw->getScissor()));
1946
1947 // compute the area to clear
1948 Region region(hw->undefinedRegion.merge(letterbox));
1949
1950 // but limit it to the dirty region
1951 region.andSelf(dirty);
1952
Mathias Agopianb9494d52012-04-18 02:28:45 -07001953 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001954 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001955 // can happen with SurfaceView
Mathias Agopian55801e42012-08-27 18:54:24 -07001956 drawWormhole(hw, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001957 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001958 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001959
Mathias Agopian766dc492012-10-30 18:08:06 -07001960 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1961 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001962 // scissor on the main display. It should never be needed
1963 // anyways (though in theory it could since the API allows it).
1964 const Rect& bounds(hw->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001965 const Rect& scissor(hw->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001966 if (scissor != bounds) {
1967 // scissor doesn't match the screen's dimensions, so we
1968 // need to clear everything outside of it and enable
1969 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001970
Mathias Agopianf45c5102012-10-24 16:29:17 -07001971 // enable scissor for this frame
Mathias Agopian3f844832013-08-07 21:24:32 -07001972 const uint32_t height = hw->getHeight();
1973 engine.setScissor(scissor.left, height - scissor.bottom,
1974 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001975 }
1976 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001977 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001978
Mathias Agopian85d751c2012-08-29 16:59:24 -07001979 /*
1980 * and then, render the layers targeted at the framebuffer
1981 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001982
Mathias Agopian13127d82013-03-05 17:47:11 -08001983 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001984 const size_t count = layers.size();
1985 const Transform& tr = hw->getTransform();
1986 if (cur != end) {
1987 // we're using h/w composer
1988 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001989 const sp<Layer>& layer(layers[i]);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001990 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07001991 if (!clip.isEmpty()) {
1992 switch (cur->getCompositionType()) {
Riley Andrews03414a12014-07-01 14:22:59 -07001993 case HWC_CURSOR_OVERLAY:
Mathias Agopian85d751c2012-08-29 16:59:24 -07001994 case HWC_OVERLAY: {
Mathias Agopianac683022013-10-01 15:36:52 -07001995 const Layer::State& state(layer->getDrawingState());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001996 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1997 && i
Andy McFadden4125a4f2014-01-29 17:17:11 -08001998 && layer->isOpaque(state) && (state.alpha == 0xFF)
Mathias Agopian85d751c2012-08-29 16:59:24 -07001999 && hasGlesComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000 // never clear the very first layer since we're
2001 // guaranteed the FB is already cleared
2002 layer->clearWithOpenGL(hw, clip);
2003 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002004 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002006 case HWC_FRAMEBUFFER: {
2007 layer->draw(hw, clip);
2008 break;
2009 }
Mathias Agopianda27af92012-09-13 18:17:13 -07002010 case HWC_FRAMEBUFFER_TARGET: {
2011 // this should not happen as the iterator shouldn't
2012 // let us get there.
Greg Hackmann86efcc02014-03-07 12:44:02 -08002013 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
Mathias Agopianda27af92012-09-13 18:17:13 -07002014 break;
2015 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002017 }
2018 layer->setAcquireFence(hw, *cur);
2019 }
2020 } else {
2021 // we're not using h/w composer
2022 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002023 const sp<Layer>& layer(layers[i]);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002024 const Region clip(dirty.intersect(
2025 tr.transform(layer->visibleRegion)));
2026 if (!clip.isEmpty()) {
2027 layer->draw(hw, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002028 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002029 }
2030 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002031
2032 // disable scissor at the end of the frame
Mathias Agopian3f844832013-08-07 21:24:32 -07002033 engine.disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002034 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035}
2036
Mathias Agopian3f844832013-08-07 21:24:32 -07002037void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002038 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002039 RenderEngine& engine(getRenderEngine());
2040 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041}
2042
Dan Stoza7d89d062015-04-30 13:29:25 -07002043status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002044 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002045 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002046 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002047{
Dan Stoza7d89d062015-04-30 13:29:25 -07002048 // add this layer to the current state list
2049 {
2050 Mutex::Autolock _l(mStateLock);
2051 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2052 return NO_MEMORY;
2053 }
2054 mCurrentState.layersSortedByZ.add(lbc);
2055 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2056 }
2057
Mathias Agopian96f08192010-06-02 23:28:45 -07002058 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002059 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002060
Dan Stoza7d89d062015-04-30 13:29:25 -07002061 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002062}
2063
Mathias Agopian3f844832013-08-07 21:24:32 -07002064status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002066 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002068 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002069 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002070 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002071 return NO_ERROR;
2072 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002073 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074}
2075
Dan Stozac7014012014-02-14 15:03:43 -08002076uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002077 return android_atomic_release_load(&mTransactionFlags);
2078}
2079
Mathias Agopian3f844832013-08-07 21:24:32 -07002080uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2082}
2083
Mathias Agopian3f844832013-08-07 21:24:32 -07002084uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002085 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2086 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002087 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088 }
2089 return old;
2090}
2091
Mathias Agopian8b33f032012-07-24 20:43:54 -07002092void SurfaceFlinger::setTransactionState(
2093 const Vector<ComposerState>& state,
2094 const Vector<DisplayState>& displays,
2095 uint32_t flags)
2096{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002097 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002098 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002099 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002100
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002101 if (flags & eAnimation) {
2102 // For window updates that are part of an animation we must wait for
2103 // previous animation "frames" to be handled.
2104 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002105 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002106 if (CC_UNLIKELY(err != NO_ERROR)) {
2107 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002108 // caller after a few seconds.
2109 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2110 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002111 mAnimTransactionPending = false;
2112 break;
2113 }
2114 }
2115 }
2116
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 size_t count = displays.size();
2118 for (size_t i=0 ; i<count ; i++) {
2119 const DisplayState& s(displays[i]);
2120 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002121 }
2122
Mathias Agopiane57f2922012-08-09 16:29:12 -07002123 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002124 for (size_t i=0 ; i<count ; i++) {
2125 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002126 // Here we need to check that the interface we're given is indeed
2127 // one of our own. A malicious client could give us a NULL
2128 // IInterface, or one of its own or even one of our own but a
2129 // different type. All these situations would cause us to crash.
2130 //
2131 // NOTE: it would be better to use RTTI as we could directly check
2132 // that we have a Client*. however, RTTI is disabled in Android.
2133 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002134 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002135 if (binder != NULL) {
2136 String16 desc(binder->getInterfaceDescriptor());
2137 if (desc == ISurfaceComposerClient::descriptor) {
2138 sp<Client> client( static_cast<Client *>(s.client.get()) );
2139 transactionFlags |= setClientStateLocked(client, s.state);
2140 }
2141 }
2142 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002143 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002144
Mathias Agopian386aa982011-11-07 21:58:03 -08002145 if (transactionFlags) {
2146 // this triggers the transaction
2147 setTransactionFlags(transactionFlags);
2148
2149 // if this is a synchronous transaction, wait for it to take effect
2150 // before returning.
2151 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002152 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002153 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002154 if (flags & eAnimation) {
2155 mAnimTransactionPending = true;
2156 }
2157 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002158 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2159 if (CC_UNLIKELY(err != NO_ERROR)) {
2160 // just in case something goes wrong in SF, return to the
2161 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002162 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2163 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002164 break;
2165 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167 }
2168}
2169
Mathias Agopiane57f2922012-08-09 16:29:12 -07002170uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2171{
Jesse Hall9a143922012-10-04 16:29:19 -07002172 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2173 if (dpyIdx < 0)
2174 return 0;
2175
Mathias Agopiane57f2922012-08-09 16:29:12 -07002176 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002177 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002178 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002179 const uint32_t what = s.what;
2180 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002181 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002182 disp.surface = s.surface;
2183 flags |= eDisplayTransactionNeeded;
2184 }
2185 }
2186 if (what & DisplayState::eLayerStackChanged) {
2187 if (disp.layerStack != s.layerStack) {
2188 disp.layerStack = s.layerStack;
2189 flags |= eDisplayTransactionNeeded;
2190 }
2191 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002192 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002193 if (disp.orientation != s.orientation) {
2194 disp.orientation = s.orientation;
2195 flags |= eDisplayTransactionNeeded;
2196 }
2197 if (disp.frame != s.frame) {
2198 disp.frame = s.frame;
2199 flags |= eDisplayTransactionNeeded;
2200 }
2201 if (disp.viewport != s.viewport) {
2202 disp.viewport = s.viewport;
2203 flags |= eDisplayTransactionNeeded;
2204 }
2205 }
Michael Lentine47e45402014-07-18 15:34:25 -07002206 if (what & DisplayState::eDisplaySizeChanged) {
2207 if (disp.width != s.width) {
2208 disp.width = s.width;
2209 flags |= eDisplayTransactionNeeded;
2210 }
2211 if (disp.height != s.height) {
2212 disp.height = s.height;
2213 flags |= eDisplayTransactionNeeded;
2214 }
2215 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002216 }
2217 return flags;
2218}
2219
2220uint32_t SurfaceFlinger::setClientStateLocked(
2221 const sp<Client>& client,
2222 const layer_state_t& s)
2223{
2224 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002225 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002226 if (layer != 0) {
2227 const uint32_t what = s.what;
2228 if (what & layer_state_t::ePositionChanged) {
2229 if (layer->setPosition(s.x, s.y))
2230 flags |= eTraversalNeeded;
2231 }
2232 if (what & layer_state_t::eLayerChanged) {
2233 // NOTE: index needs to be calculated before we update the state
2234 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2235 if (layer->setLayer(s.z)) {
2236 mCurrentState.layersSortedByZ.removeAt(idx);
2237 mCurrentState.layersSortedByZ.add(layer);
2238 // we need traversal (state changed)
2239 // AND transaction (list changed)
2240 flags |= eTransactionNeeded|eTraversalNeeded;
2241 }
2242 }
2243 if (what & layer_state_t::eSizeChanged) {
2244 if (layer->setSize(s.w, s.h)) {
2245 flags |= eTraversalNeeded;
2246 }
2247 }
2248 if (what & layer_state_t::eAlphaChanged) {
2249 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2250 flags |= eTraversalNeeded;
2251 }
2252 if (what & layer_state_t::eMatrixChanged) {
2253 if (layer->setMatrix(s.matrix))
2254 flags |= eTraversalNeeded;
2255 }
2256 if (what & layer_state_t::eTransparentRegionChanged) {
2257 if (layer->setTransparentRegionHint(s.transparentRegion))
2258 flags |= eTraversalNeeded;
2259 }
Dan Stoza23116082015-06-18 14:58:39 -07002260 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002261 if (layer->setFlags(s.flags, s.mask))
2262 flags |= eTraversalNeeded;
2263 }
2264 if (what & layer_state_t::eCropChanged) {
2265 if (layer->setCrop(s.crop))
2266 flags |= eTraversalNeeded;
2267 }
2268 if (what & layer_state_t::eLayerStackChanged) {
2269 // NOTE: index needs to be calculated before we update the state
2270 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2271 if (layer->setLayerStack(s.layerStack)) {
2272 mCurrentState.layersSortedByZ.removeAt(idx);
2273 mCurrentState.layersSortedByZ.add(layer);
2274 // we need traversal (state changed)
2275 // AND transaction (list changed)
2276 flags |= eTransactionNeeded|eTraversalNeeded;
2277 }
2278 }
2279 }
2280 return flags;
2281}
2282
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002283status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002284 const String8& name,
2285 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002286 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2287 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002289 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002290 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002291 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002292 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002293 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002294 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002295
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002296 status_t result = NO_ERROR;
2297
2298 sp<Layer> layer;
2299
Mathias Agopian3165cc22012-08-08 19:42:09 -07002300 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2301 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002302 result = createNormalLayer(client,
2303 name, w, h, flags, format,
2304 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002306 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002307 result = createDimLayer(client,
2308 name, w, h, flags,
2309 handle, gbp, &layer);
2310 break;
2311 default:
2312 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313 break;
2314 }
2315
Dan Stoza7d89d062015-04-30 13:29:25 -07002316 if (result != NO_ERROR) {
2317 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002319
2320 result = addClientLayer(client, *handle, *gbp, layer);
2321 if (result != NO_ERROR) {
2322 return result;
2323 }
2324
2325 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002326 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327}
2328
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002329status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2330 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2331 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002332{
2333 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002334 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 case PIXEL_FORMAT_TRANSPARENT:
2336 case PIXEL_FORMAT_TRANSLUCENT:
2337 format = PIXEL_FORMAT_RGBA_8888;
2338 break;
2339 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002340 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 break;
2342 }
2343
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002344 *outLayer = new Layer(this, client, name, w, h, flags);
2345 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2346 if (err == NO_ERROR) {
2347 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002348 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002350
2351 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2352 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353}
2354
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002355status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2356 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2357 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002359 *outLayer = new LayerDim(this, client, name, w, h, flags);
2360 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002361 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002362 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002363}
2364
Mathias Agopianac9fa422013-02-11 16:40:36 -08002365status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366{
Mathias Agopian67106042013-03-14 19:18:13 -07002367 // called by the window manager when it wants to remove a Layer
2368 status_t err = NO_ERROR;
2369 sp<Layer> l(client->getLayerUser(handle));
2370 if (l != NULL) {
2371 err = removeLayer(l);
2372 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2373 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002374 }
2375 return err;
2376}
2377
Mathias Agopian13127d82013-03-05 17:47:11 -08002378status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002379{
Mathias Agopian67106042013-03-14 19:18:13 -07002380 // called by ~LayerCleaner() when all references to the IBinder (handle)
2381 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002382 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002383 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002384 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002385 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002386 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002387 "error removing layer=%p (%s)", l.get(), strerror(-err));
2388 }
2389 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002390}
2391
Mathias Agopianb60314a2012-04-10 22:09:54 -07002392// ---------------------------------------------------------------------------
2393
Andy McFadden13a082e2012-08-24 10:16:42 -07002394void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002395 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002396 Vector<ComposerState> state;
2397 Vector<DisplayState> displays;
2398 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002399 d.what = DisplayState::eDisplayProjectionChanged |
2400 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002401 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002402 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002403 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002404 d.frame.makeInvalid();
2405 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002406 d.width = 0;
2407 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002408 displays.add(d);
2409 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002410 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002411
2412 const nsecs_t period =
2413 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002415}
2416
2417void SurfaceFlinger::initializeDisplays() {
2418 class MessageScreenInitialized : public MessageBase {
2419 SurfaceFlinger* flinger;
2420 public:
2421 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2422 virtual bool handler() {
2423 flinger->onInitializeDisplays();
2424 return true;
2425 }
2426 };
2427 sp<MessageBase> msg = new MessageScreenInitialized(this);
2428 postMessageAsync(msg); // we may be called from main thread, use async message
2429}
2430
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002431void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2432 int mode) {
2433 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2434 this);
2435 int32_t type = hw->getDisplayType();
2436 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002437
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002438 if (mode == currentMode) {
2439 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002440 return;
2441 }
2442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002443 hw->setPowerMode(mode);
2444 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2445 ALOGW("Trying to set power mode for virtual display");
2446 return;
2447 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002448
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002449 if (currentMode == HWC_POWER_MODE_OFF) {
2450 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002451 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2452 // FIXME: eventthread only knows about the main display right now
2453 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002454 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002457 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002458 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002459 repaintEverything();
2460 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002461 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002462 disableHardwareVsync(true); // also cancels any in-progress resync
2463
Mathias Agopiancde87a32012-09-13 14:09:01 -07002464 // FIXME: eventthread only knows about the main display right now
2465 mEventThread->onScreenReleased();
2466 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002467
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002468 getHwComposer().setPowerMode(type, mode);
2469 mVisibleRegionsDirty = true;
2470 // from this point on, SF will stop drawing on this display
2471 } else {
2472 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002473 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002474}
2475
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002476void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2477 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002478 SurfaceFlinger& mFlinger;
2479 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002480 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002481 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002482 MessageSetPowerMode(SurfaceFlinger& flinger,
2483 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2484 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002485 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002486 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002487 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002488 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002489 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002490 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002491 ALOGW("Attempt to set power mode = %d for virtual display",
2492 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002493 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002494 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002495 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002496 return true;
2497 }
2498 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002499 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002500 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002501}
2502
2503// ---------------------------------------------------------------------------
2504
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2506{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002508
Mathias Agopianbd115332013-04-18 16:41:04 -07002509 IPCThreadState* ipc = IPCThreadState::self();
2510 const int pid = ipc->getCallingPid();
2511 const int uid = ipc->getCallingUid();
2512 if ((uid != AID_SHELL) &&
2513 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002514 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002515 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002517 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002518 // (this would indicate SF is stuck, but we want to be able to
2519 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002520 status_t err = mStateLock.timedLock(s2ns(1));
2521 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002522 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002523 result.appendFormat(
2524 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2525 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002526 }
2527
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002528 bool dumpAll = true;
2529 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002530 size_t numArgs = args.size();
2531 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002532 if ((index < numArgs) &&
2533 (args[index] == String16("--list"))) {
2534 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002535 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002536 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002537 }
2538
2539 if ((index < numArgs) &&
2540 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002541 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002542 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002543 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002544 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002545
2546 if ((index < numArgs) &&
2547 (args[index] == String16("--latency-clear"))) {
2548 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002549 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002550 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002551 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002552
2553 if ((index < numArgs) &&
2554 (args[index] == String16("--dispsync"))) {
2555 index++;
2556 mPrimaryDispSync.dump(result);
2557 dumpAll = false;
2558 }
Dan Stozab90cf072015-03-05 11:05:59 -08002559
2560 if ((index < numArgs) &&
2561 (args[index] == String16("--static-screen"))) {
2562 index++;
2563 dumpStaticScreenStats(result);
2564 dumpAll = false;
2565 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002567
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002568 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002569 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002570 }
2571
Mathias Agopian9795c422009-08-26 16:36:26 -07002572 if (locked) {
2573 mStateLock.unlock();
2574 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 }
2576 write(fd, result.string(), result.size());
2577 return NO_ERROR;
2578}
2579
Dan Stozac7014012014-02-14 15:03:43 -08002580void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2581 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002582{
2583 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2584 const size_t count = currentLayers.size();
2585 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002586 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002587 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002588 }
2589}
2590
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002591void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002592 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002593{
2594 String8 name;
2595 if (index < args.size()) {
2596 name = String8(args[index]);
2597 index++;
2598 }
2599
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002600 const nsecs_t period =
2601 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002602 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002603
2604 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002605 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002606 } else {
2607 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2608 const size_t count = currentLayers.size();
2609 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002610 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002611 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002612 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002613 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002614 }
2615 }
2616}
2617
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002618void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002619 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002620{
2621 String8 name;
2622 if (index < args.size()) {
2623 name = String8(args[index]);
2624 index++;
2625 }
2626
2627 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2628 const size_t count = currentLayers.size();
2629 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002630 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002631 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002632 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002633 }
2634 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002635
Svetoslavd85084b2014-03-20 10:28:31 -07002636 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002637}
2638
Jamie Gennis6547ff42013-07-16 20:12:42 -07002639// This should only be called from the main thread. Otherwise it would need
2640// the lock and should use mCurrentState rather than mDrawingState.
2641void SurfaceFlinger::logFrameStats() {
2642 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2643 const size_t count = drawingLayers.size();
2644 for (size_t i=0 ; i<count ; i++) {
2645 const sp<Layer>& layer(drawingLayers[i]);
2646 layer->logFrameStats();
2647 }
2648
2649 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2650}
2651
Andy McFadden4803b742012-09-24 19:07:20 -07002652/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2653{
2654 static const char* config =
2655 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002656#ifdef HAS_CONTEXT_PRIORITY
2657 " HAS_CONTEXT_PRIORITY"
2658#endif
2659#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2660 " NEVER_DEFAULT_TO_ASYNC_MODE"
2661#endif
2662#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2663 " TARGET_DISABLE_TRIPLE_BUFFERING"
2664#endif
2665 "]";
2666 result.append(config);
2667}
2668
Dan Stozab90cf072015-03-05 11:05:59 -08002669void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2670{
2671 result.appendFormat("Static screen stats:\n");
2672 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2673 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2674 float percent = 100.0f *
2675 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2676 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2677 b + 1, bucketTimeSec, percent);
2678 }
2679 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2680 float percent = 100.0f *
2681 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2682 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2683 NUM_BUCKETS - 1, bucketTimeSec, percent);
2684}
2685
Mathias Agopian74d211a2013-04-22 16:55:35 +02002686void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2687 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002688{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002689 bool colorize = false;
2690 if (index < args.size()
2691 && (args[index] == String16("--color"))) {
2692 colorize = true;
2693 index++;
2694 }
2695
2696 Colorizer colorizer(colorize);
2697
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002698 // figure out if we're stuck somewhere
2699 const nsecs_t now = systemTime();
2700 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2701 const nsecs_t inTransaction(mDebugInTransaction);
2702 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2703 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2704
2705 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002706 * Dump library configuration.
2707 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002708
2709 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002710 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002711 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002712 appendSfConfigString(result);
2713 appendUiConfigString(result);
2714 appendGuiConfigString(result);
2715 result.append("\n");
2716
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002717 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002718 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002719 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002720 result.append(SyncFeatures::getInstance().toString());
2721 result.append("\n");
2722
Andy McFadden41d67d72014-04-25 16:58:34 -07002723 colorizer.bold(result);
2724 result.append("DispSync configuration: ");
2725 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002726 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2727 "present offset %d ns (refresh %" PRId64 " ns)",
Andy McFadden41d67d72014-04-25 16:58:34 -07002728 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2729 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2730 result.append("\n");
2731
Dan Stozab90cf072015-03-05 11:05:59 -08002732 // Dump static screen stats
2733 result.append("\n");
2734 dumpStaticScreenStats(result);
2735 result.append("\n");
2736
Andy McFadden4803b742012-09-24 19:07:20 -07002737 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002738 * Dump the visible layer list
2739 */
2740 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2741 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002742 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002743 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002744 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002745 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002746 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002747 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002748 }
2749
2750 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002751 * Dump Display state
2752 */
2753
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002754 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002755 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002756 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002757 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2758 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002759 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002760 }
2761
2762 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002763 * Dump SurfaceFlinger global state
2764 */
2765
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002766 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002767 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002768 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002769
Mathias Agopian888c8222012-08-04 21:10:38 -07002770 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002771 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002772
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002773 colorizer.bold(result);
2774 result.appendFormat("EGL implementation : %s\n",
2775 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2776 colorizer.reset(result);
2777 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002778 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002779
Mathias Agopian875d8e12013-06-07 15:35:48 -07002780 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002781
Mathias Agopian42977342012-08-05 00:40:46 -07002782 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002783 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2784 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002785 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002786 " last eglSwapBuffers() time: %f us\n"
2787 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002788 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002789 " refresh-rate : %f fps\n"
2790 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002791 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002792 " gpu_to_cpu_unsupported : %d\n"
2793 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002794 mLastSwapBufferTime/1000.0,
2795 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002796 mTransactionFlags,
Andy McFaddenb0d1dd32012-09-10 14:08:09 -07002797 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2798 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002799 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
Mathias Agopianed985572013-03-22 00:24:39 -07002800 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002801
Mathias Agopian74d211a2013-04-22 16:55:35 +02002802 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002803 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002804
Mathias Agopian74d211a2013-04-22 16:55:35 +02002805 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002806 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002807
2808 /*
2809 * VSYNC state
2810 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002811 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002812
2813 /*
2814 * Dump HWComposer state
2815 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002816 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002817 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002818 colorizer.reset(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002819 result.appendFormat(" h/w composer %s and %s\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002820 hwc.initCheck()==NO_ERROR ? "present" : "not present",
Alan Viverette9c5a3332013-09-12 20:04:35 -07002821 (mDebugDisableHWC || mDebugRegion || mDaltonize
2822 || mHasColorMatrix) ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002823 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002824
2825 /*
2826 * Dump gralloc state
2827 */
2828 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2829 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002830}
2831
Mathias Agopian13127d82013-03-05 17:47:11 -08002832const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002833SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002834 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002835 wp<IBinder> dpy;
2836 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2837 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2838 dpy = mDisplays.keyAt(i);
2839 break;
2840 }
2841 }
2842 if (dpy == NULL) {
2843 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2844 // Just use the primary display so we have something to return
2845 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2846 }
2847 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002848}
2849
Keun young Park63f165f2012-08-31 10:53:36 -07002850bool SurfaceFlinger::startDdmConnection()
2851{
2852 void* libddmconnection_dso =
2853 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2854 if (!libddmconnection_dso) {
2855 return false;
2856 }
2857 void (*DdmConnection_start)(const char* name);
2858 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002859 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002860 if (!DdmConnection_start) {
2861 dlclose(libddmconnection_dso);
2862 return false;
2863 }
2864 (*DdmConnection_start)(getServiceName());
2865 return true;
2866}
2867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868status_t SurfaceFlinger::onTransact(
2869 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2870{
2871 switch (code) {
2872 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002873 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002874 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002876 case CLEAR_ANIMATION_FRAME_STATS:
2877 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002878 case SET_POWER_MODE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 {
2880 // codes that require permission check
2881 IPCThreadState* ipc = IPCThreadState::self();
2882 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002883 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002884 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002885 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002886 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002887 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2888 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002890 break;
2891 }
2892 case CAPTURE_SCREEN:
2893 {
2894 // codes that require permission check
2895 IPCThreadState* ipc = IPCThreadState::self();
2896 const int pid = ipc->getCallingPid();
2897 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002898 if ((uid != AID_GRAPHICS) &&
2899 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002900 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002901 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2902 return PERMISSION_DENIED;
2903 }
2904 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 }
2906 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002907
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2909 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002910 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002911 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002912 IPCThreadState* ipc = IPCThreadState::self();
2913 const int pid = ipc->getCallingPid();
2914 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002915 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002916 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 return PERMISSION_DENIED;
2918 }
2919 int n;
2920 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07002921 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07002922 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 return NO_ERROR;
2924 case 1002: // SHOW_UPDATES
2925 n = data.readInt32();
2926 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07002927 invalidateHwcGeometry();
2928 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07002931 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002932 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002934 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07002935 setTransactionFlags(
2936 eTransactionNeeded|
2937 eDisplayTransactionNeeded|
2938 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002939 return NO_ERROR;
2940 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002941 case 1006:{ // send empty update
2942 signalRefresh();
2943 return NO_ERROR;
2944 }
Mathias Agopian53331da2011-08-22 21:44:41 -07002945 case 1008: // toggle use of hw composer
2946 n = data.readInt32();
2947 mDebugDisableHWC = n ? 1 : 0;
2948 invalidateHwcGeometry();
2949 repaintEverything();
2950 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07002951 case 1009: // toggle use of transform hint
2952 n = data.readInt32();
2953 mDebugDisableTransformHint = n ? 1 : 0;
2954 invalidateHwcGeometry();
2955 repaintEverything();
2956 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07002958 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 reply->writeInt32(0);
2960 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002961 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08002962 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 return NO_ERROR;
2964 case 1013: {
2965 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07002966 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2967 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07002968 return NO_ERROR;
2969 }
2970 case 1014: {
2971 // daltonize
2972 n = data.readInt32();
2973 switch (n % 10) {
2974 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2975 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2976 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2977 }
2978 if (n >= 10) {
2979 mDaltonizer.setMode(Daltonizer::correction);
2980 } else {
2981 mDaltonizer.setMode(Daltonizer::simulation);
2982 }
2983 mDaltonize = n > 0;
2984 invalidateHwcGeometry();
2985 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07002986 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07002988 case 1015: {
2989 // apply a color matrix
2990 n = data.readInt32();
2991 mHasColorMatrix = n ? 1 : 0;
2992 if (n) {
2993 // color matrix is sent as mat3 matrix followed by vec3
2994 // offset, then packed into a mat4 where the last row is
2995 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07002996 for (size_t i = 0 ; i < 4; i++) {
2997 for (size_t j = 0; j < 4; j++) {
2998 mColorMatrix[i][j] = data.readFloat();
2999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003000 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003001 } else {
3002 mColorMatrix = mat4();
3003 }
3004 invalidateHwcGeometry();
3005 repaintEverything();
3006 return NO_ERROR;
3007 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003008 // This is an experimental interface
3009 // Needs to be shifted to proper binder interface when we productize
3010 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003011 n = data.readInt32();
3012 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003013 return NO_ERROR;
3014 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003015 case 1017: {
3016 n = data.readInt32();
3017 mForceFullDamage = static_cast<bool>(n);
3018 return NO_ERROR;
3019 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003020 case 1018: { // Modify Choreographer's phase offset
3021 n = data.readInt32();
3022 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3023 return NO_ERROR;
3024 }
3025 case 1019: { // Modify SurfaceFlinger's phase offset
3026 n = data.readInt32();
3027 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3028 return NO_ERROR;
3029 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030 }
3031 }
3032 return err;
3033}
3034
Mathias Agopian53331da2011-08-22 21:44:41 -07003035void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003037 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003038}
3039
Mathias Agopian59119e62010-10-11 12:37:43 -07003040// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003041// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003042// ---------------------------------------------------------------------------
3043
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003044/* The code below is here to handle b/8734824
3045 *
3046 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003047 * from the surfaceflinger thread to the calling binder thread, where they
3048 * are executed. This allows the calling thread in the calling process to be
3049 * reused and not depend on having "enough" binder threads to handle the
3050 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003051 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003052class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003053 /* Parts of GraphicProducerWrapper are run on two different threads,
3054 * communicating by sending messages via Looper but also by shared member
3055 * data. Coherence maintenance is subtle and in places implicit (ugh).
3056 *
3057 * Don't rely on Looper's sendMessage/handleMessage providing
3058 * release/acquire semantics for any data not actually in the Message.
3059 * Data going from surfaceflinger to binder threads needs to be
3060 * synchronized explicitly.
3061 *
3062 * Barrier open/wait do provide release/acquire semantics. This provides
3063 * implicit synchronization for data coming back from binder to
3064 * surfaceflinger threads.
3065 */
3066
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003067 sp<IGraphicBufferProducer> impl;
3068 sp<Looper> looper;
3069 status_t result;
3070 bool exitPending;
3071 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003072 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003073 uint32_t code;
3074 Parcel const* data;
3075 Parcel* reply;
3076
3077 enum {
3078 MSG_API_CALL,
3079 MSG_EXIT
3080 };
3081
3082 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003083 * Called on surfaceflinger thread. This is called by our "fake"
3084 * BpGraphicBufferProducer. We package the data and reply Parcel and
3085 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003086 */
3087 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003088 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003089 this->code = code;
3090 this->data = &data;
3091 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003092 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003093 // if we've exited, we run the message synchronously right here.
3094 // note (JH): as far as I can tell from looking at the code, this
3095 // never actually happens. if it does, i'm not sure if it happens
3096 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003097 handleMessage(Message(MSG_API_CALL));
3098 } else {
3099 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003100 // Prevent stores to this->{code, data, reply} from being
3101 // reordered later than the construction of Message.
3102 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003103 looper->sendMessage(this, Message(MSG_API_CALL));
3104 barrier.wait();
3105 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003106 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003107 }
3108
3109 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003110 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003111 * call the real BpGraphicBufferProducer.
3112 */
3113 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003114 int what = message.what;
3115 // Prevent reads below from happening before the read from Message
3116 atomic_thread_fence(memory_order_acquire);
3117 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003118 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003119 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003120 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003121 exitRequested = true;
3122 }
3123 }
3124
3125public:
Jesse Hallb154c422014-07-13 12:47:02 -07003126 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3127 : impl(impl),
3128 looper(new Looper(true)),
3129 exitPending(false),
3130 exitRequested(false)
3131 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003132
Jesse Hallb154c422014-07-13 12:47:02 -07003133 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003134 status_t waitForResponse() {
3135 do {
3136 looper->pollOnce(-1);
3137 } while (!exitRequested);
3138 return result;
3139 }
3140
Jesse Hallb154c422014-07-13 12:47:02 -07003141 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003142 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003143 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003144 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003145 // Ensure this->result is visible to the binder thread before it
3146 // handles the message.
3147 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003148 looper->sendMessage(this, Message(MSG_EXIT));
3149 }
3150};
3151
3152
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003153status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3154 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003155 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003156 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003157 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003158
3159 if (CC_UNLIKELY(display == 0))
3160 return BAD_VALUE;
3161
3162 if (CC_UNLIKELY(producer == 0))
3163 return BAD_VALUE;
3164
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003165 // if we have secure windows on this display, never allow the screen capture
3166 // unless the producer interface is local (i.e.: we can take a screenshot for
3167 // ourselves).
Marco Nelissen097ca272014-11-14 08:01:01 -08003168 if (!IInterface::asBinder(producer)->localBinder()) {
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003169 Mutex::Autolock _l(mStateLock);
3170 sp<const DisplayDevice> hw(getDisplayDevice(display));
3171 if (hw->getSecureLayerVisible()) {
3172 ALOGW("FB is protected: PERMISSION_DENIED");
3173 return PERMISSION_DENIED;
3174 }
3175 }
3176
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003177 // Convert to surfaceflinger's internal rotation type.
3178 Transform::orientation_flags rotationFlags;
3179 switch (rotation) {
3180 case ISurfaceComposer::eRotateNone:
3181 rotationFlags = Transform::ROT_0;
3182 break;
3183 case ISurfaceComposer::eRotate90:
3184 rotationFlags = Transform::ROT_90;
3185 break;
3186 case ISurfaceComposer::eRotate180:
3187 rotationFlags = Transform::ROT_180;
3188 break;
3189 case ISurfaceComposer::eRotate270:
3190 rotationFlags = Transform::ROT_270;
3191 break;
3192 default:
3193 rotationFlags = Transform::ROT_0;
3194 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3195 break;
3196 }
3197
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003198 class MessageCaptureScreen : public MessageBase {
3199 SurfaceFlinger* flinger;
3200 sp<IBinder> display;
3201 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003202 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003203 uint32_t reqWidth, reqHeight;
3204 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003205 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003206 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003207 status_t result;
3208 public:
3209 MessageCaptureScreen(SurfaceFlinger* flinger,
3210 const sp<IBinder>& display,
3211 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003212 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003213 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003214 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003215 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003216 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003217 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003218 useIdentityTransform(useIdentityTransform),
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003219 rotation(rotation),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003220 result(PERMISSION_DENIED)
3221 {
3222 }
3223 status_t getResult() const {
3224 return result;
3225 }
3226 virtual bool handler() {
3227 Mutex::Autolock _l(flinger->mStateLock);
3228 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003229 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003230 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003231 useIdentityTransform, rotation);
Marco Nelissen097ca272014-11-14 08:01:01 -08003232 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003233 return true;
3234 }
3235 };
3236
Mathias Agopian9eb1f052013-04-10 16:27:17 -07003237 // make sure to process transactions before screenshots -- a transaction
3238 // might already be pending but scheduled for VSYNC; this guarantees we
3239 // will handle it before the screenshot. When VSYNC finally arrives
3240 // the scheduled transaction will be a no-op. If no transactions are
3241 // scheduled at this time, this will end-up being a no-op as well.
3242 mEventQueue.invalidateTransactionNow();
3243
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003244 // this creates a "fake" BBinder which will serve as a "fake" remote
3245 // binder to receive the marshaled calls and forward them to the
3246 // real remote (a BpGraphicBufferProducer)
3247 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3248
3249 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3250 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003251 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003252 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003253 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003254 useIdentityTransform, rotationFlags);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003255
3256 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003257 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003258 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003259 }
3260 return res;
3261}
3262
Mathias Agopian180f10d2013-04-10 22:55:41 -07003263
3264void SurfaceFlinger::renderScreenImplLocked(
3265 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003266 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003267 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003268 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003269{
3270 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003271 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003272
3273 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003274 const int32_t hw_w = hw->getWidth();
3275 const int32_t hw_h = hw->getHeight();
3276 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003277 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003278
Dan Stozac1879002014-05-22 15:59:05 -07003279 // if a default or invalid sourceCrop is passed in, set reasonable values
3280 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3281 !sourceCrop.isValid()) {
3282 sourceCrop.setLeftTop(Point(0, 0));
3283 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3284 }
3285
3286 // ensure that sourceCrop is inside screen
3287 if (sourceCrop.left < 0) {
3288 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3289 }
Dan Stozabe31f442014-06-11 11:20:54 -07003290 if (sourceCrop.right > hw_w) {
3291 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003292 }
3293 if (sourceCrop.top < 0) {
3294 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3295 }
Dan Stozabe31f442014-06-11 11:20:54 -07003296 if (sourceCrop.bottom > hw_h) {
3297 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003298 }
3299
Mathias Agopian180f10d2013-04-10 22:55:41 -07003300 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003301 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003302
3303 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003304 engine.setViewportAndProjection(
3305 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003306 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003307
3308 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003309 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003310
3311 const LayerVector& layers( mDrawingState.layersSortedByZ );
3312 const size_t count = layers.size();
3313 for (size_t i=0 ; i<count ; ++i) {
3314 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003315 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003316 if (state.layerStack == hw->getLayerStack()) {
3317 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3318 if (layer->isVisible()) {
3319 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003320 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003321 if (filtering) layer->setFiltering(false);
3322 }
3323 }
3324 }
3325 }
3326
3327 // compositionComplete is needed for older driver
3328 hw->compositionComplete();
Mathias Agopian931bda12013-08-28 18:11:46 -07003329 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003330}
3331
3332
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003333status_t SurfaceFlinger::captureScreenImplLocked(
3334 const sp<const DisplayDevice>& hw,
3335 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003336 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003337 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003338 bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003339{
3340 ATRACE_CALL();
3341
Mathias Agopian180f10d2013-04-10 22:55:41 -07003342 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003343 uint32_t hw_w = hw->getWidth();
3344 uint32_t hw_h = hw->getHeight();
3345
3346 if (rotation & Transform::ROT_90) {
3347 std::swap(hw_w, hw_h);
3348 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003349
Mathias Agopian180f10d2013-04-10 22:55:41 -07003350 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3351 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3352 reqWidth, reqHeight, hw_w, hw_h);
3353 return BAD_VALUE;
3354 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003355
Mathias Agopian180f10d2013-04-10 22:55:41 -07003356 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3357 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3358
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003359 // create a surface (because we're a producer, and we need to
3360 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003361 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003362 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003363
Michael Lentine5a16a622015-05-21 13:48:24 -07003364 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3365 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003366 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3367 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003368
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003369 int err = 0;
3370 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003371 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003372 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3373 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003374
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003375 if (err == NO_ERROR) {
3376 ANativeWindowBuffer* buffer;
3377 /* TODO: Once we have the sync framework everywhere this can use
3378 * server-side waits on the fence that dequeueBuffer returns.
3379 */
3380 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3381 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003382 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003383 // create an EGLImage from the buffer so we can later
3384 // turn it into a texture
3385 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3386 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3387 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003388 // this binds the given EGLImage as a framebuffer for the
3389 // duration of this scope.
3390 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3391 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003392 // this will in fact render into our dequeued buffer
3393 // via an FBO, which means we didn't have to create
3394 // an EGLSurface and therefore we're not
3395 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003396 renderScreenImplLocked(
3397 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3398 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003399
Riley Andrews86639902014-08-15 12:27:24 -07003400 // Attempt to create a sync khr object that can produce a sync point. If that
3401 // isn't available, create a non-dupable sync object in the fallback path and
3402 // wait on it directly.
3403 EGLSyncKHR sync;
3404 if (!DEBUG_SCREENSHOTS) {
3405 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003406 // native fence fd will not be populated until flush() is done.
3407 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003408 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003409 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003410 }
Riley Andrews86639902014-08-15 12:27:24 -07003411 if (sync != EGL_NO_SYNC_KHR) {
3412 // get the sync fd
3413 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3414 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3415 ALOGW("captureScreen: failed to dup sync khr object");
3416 syncFd = -1;
3417 }
3418 eglDestroySyncKHR(mEGLDisplay, sync);
3419 } else {
3420 // fallback path
3421 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3422 if (sync != EGL_NO_SYNC_KHR) {
3423 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3424 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3425 EGLint eglErr = eglGetError();
3426 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3427 ALOGW("captureScreen: fence wait timed out");
3428 } else {
3429 ALOGW_IF(eglErr != EGL_SUCCESS,
3430 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3431 }
3432 eglDestroySyncKHR(mEGLDisplay, sync);
3433 } else {
3434 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3435 }
3436 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003437 if (DEBUG_SCREENSHOTS) {
3438 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3439 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3440 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3441 hw, minLayerZ, maxLayerZ);
3442 delete [] pixels;
3443 }
3444
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003445 } else {
3446 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3447 result = INVALID_OPERATION;
3448 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003449 // destroy our image
3450 eglDestroyImageKHR(mEGLDisplay, image);
3451 } else {
3452 result = BAD_VALUE;
3453 }
Jesse Hallafe2b1f2014-10-21 11:09:17 -07003454 // queueBuffer takes ownership of syncFd
Michael Lentine5a16a622015-05-21 13:48:24 -07003455 result = window->queueBuffer(window, buffer, syncFd);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003456 }
3457 } else {
3458 result = BAD_VALUE;
3459 }
3460 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3461 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003462
Mathias Agopian74c40c02010-09-29 13:02:36 -07003463 return result;
3464}
3465
Mathias Agopiand5556842013-09-19 17:08:37 -07003466void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3467 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003468 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003469 for (size_t y=0 ; y<h ; y++) {
3470 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3471 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003472 if (p[x] != 0xFF000000) return;
3473 }
3474 }
3475 ALOGE("*** we just took a black screenshot ***\n"
3476 "requested minz=%d, maxz=%d, layerStack=%d",
3477 minLayerZ, maxLayerZ, hw->getLayerStack());
3478 const LayerVector& layers( mDrawingState.layersSortedByZ );
3479 const size_t count = layers.size();
3480 for (size_t i=0 ; i<count ; ++i) {
3481 const sp<Layer>& layer(layers[i]);
3482 const Layer::State& state(layer->getDrawingState());
3483 const bool visible = (state.layerStack == hw->getLayerStack())
3484 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3485 && (layer->isVisible());
Greg Hackmann86efcc02014-03-07 12:44:02 -08003486 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003487 visible ? '+' : '-',
3488 i, layer->getName().string(), state.layerStack, state.z,
3489 layer->isVisible(), state.flags, state.alpha);
3490 }
3491 }
3492}
3493
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003494// ---------------------------------------------------------------------------
3495
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003496SurfaceFlinger::LayerVector::LayerVector() {
3497}
3498
3499SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003500 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003501}
3502
3503int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3504 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003505{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003506 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003507 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3508 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003509
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003510 uint32_t ls = l->getCurrentState().layerStack;
3511 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003512 if (ls != rs)
3513 return ls - rs;
3514
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003515 uint32_t lz = l->getCurrentState().z;
3516 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003517 if (lz != rz)
3518 return lz - rz;
3519
3520 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003521}
3522
3523// ---------------------------------------------------------------------------
3524
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003525SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Michael Lentine47e45402014-07-18 15:34:25 -07003526 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003527}
3528
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003529SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
Michael Lentine47e45402014-07-18 15:34:25 -07003530 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003531 viewport.makeInvalid();
3532 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003533}
3534
3535// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003538
3539
3540#if defined(__gl_h_)
3541#error "don't include gl/gl.h in this file"
3542#endif
3543
3544#if defined(__gl2_h_)
3545#error "don't include gl2/gl2.h in this file"
3546#endif