1 /*
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
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19 #include <stdint.h>
20 #include <sys/types.h>
21 #include <errno.h>
22 #include <math.h>
23 #include <dlfcn.h>
24
25 #include <EGL/egl.h>
26 #include <GLES/gl.h>
27
28 #include <cutils/log.h>
29 #include <cutils/properties.h>
30
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/MemoryHeapBase.h>
34 #include <binder/PermissionCache.h>
35
36 #include <ui/DisplayInfo.h>
37
38 #include <gui/BitTube.h>
39 #include <gui/BufferQueue.h>
40 #include <gui/GuiConfig.h>
41 #include <gui/IDisplayEventConnection.h>
42 #include <gui/SurfaceTextureClient.h>
43
44 #include <ui/GraphicBufferAllocator.h>
45 #include <ui/PixelFormat.h>
46 #include <ui/UiConfig.h>
47
48 #include <utils/misc.h>
49 #include <utils/String8.h>
50 #include <utils/String16.h>
51 #include <utils/StopWatch.h>
52 #include <utils/Trace.h>
53
54 #include <private/android_filesystem_config.h>
55
56 #include "clz.h"
57 #include "DdmConnection.h"
58 #include "DisplayDevice.h"
59 #include "Client.h"
60 #include "EventThread.h"
61 #include "GLExtensions.h"
62 #include "Layer.h"
63 #include "LayerDim.h"
64 #include "LayerScreenshot.h"
65 #include "SurfaceFlinger.h"
66
67 #include "DisplayHardware/FramebufferSurface.h"
68 #include "DisplayHardware/GraphicBufferAlloc.h"
69 #include "DisplayHardware/HWComposer.h"
70
71
72 #define EGL_VERSION_HW_ANDROID 0x3143
73
74 #define DISPLAY_COUNT 1
75
76 namespace android {
77 // ---------------------------------------------------------------------------
78
79 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
80 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
81 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
82 const String16 sDump("android.permission.DUMP");
83
84 // ---------------------------------------------------------------------------
85
SurfaceFlinger()86 SurfaceFlinger::SurfaceFlinger()
87 : BnSurfaceComposer(), Thread(false),
88 mTransactionFlags(0),
89 mTransactionPending(false),
90 mAnimTransactionPending(false),
91 mLayersRemoved(false),
92 mRepaintEverything(0),
93 mBootTime(systemTime()),
94 mVisibleRegionsDirty(false),
95 mHwWorkListDirty(false),
96 mDebugRegion(0),
97 mDebugDDMS(0),
98 mDebugDisableHWC(0),
99 mDebugDisableTransformHint(0),
100 mDebugInSwapBuffers(0),
101 mLastSwapBufferTime(0),
102 mDebugInTransaction(0),
103 mLastTransactionTime(0),
104 mBootFinished(false)
105 {
106 ALOGI("SurfaceFlinger is starting");
107
108 // debugging stuff...
109 char value[PROPERTY_VALUE_MAX];
110
111 property_get("debug.sf.showupdates", value, "0");
112 mDebugRegion = atoi(value);
113
114 property_get("debug.sf.ddms", value, "0");
115 mDebugDDMS = atoi(value);
116 if (mDebugDDMS) {
117 if (!startDdmConnection()) {
118 // start failed, and DDMS debugging not enabled
119 mDebugDDMS = 0;
120 }
121 }
122 ALOGI_IF(mDebugRegion, "showupdates enabled");
123 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
124 }
125
onFirstRef()126 void SurfaceFlinger::onFirstRef()
127 {
128 mEventQueue.init(this);
129
130 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
131
132 // Wait for the main thread to be done with its initialization
133 mReadyToRunBarrier.wait();
134 }
135
136
~SurfaceFlinger()137 SurfaceFlinger::~SurfaceFlinger()
138 {
139 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
140 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
141 eglTerminate(display);
142 }
143
binderDied(const wp<IBinder> & who)144 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
145 {
146 // the window manager died on us. prepare its eulogy.
147
148 // restore initial conditions (default device unblank, etc)
149 initializeDisplays();
150
151 // restart the boot-animation
152 startBootAnim();
153 }
154
createConnection()155 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
156 {
157 sp<ISurfaceComposerClient> bclient;
158 sp<Client> client(new Client(this));
159 status_t err = client->initCheck();
160 if (err == NO_ERROR) {
161 bclient = client;
162 }
163 return bclient;
164 }
165
createDisplay(const String8 & displayName,bool secure)166 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
167 bool secure)
168 {
169 class DisplayToken : public BBinder {
170 sp<SurfaceFlinger> flinger;
171 virtual ~DisplayToken() {
172 // no more references, this display must be terminated
173 Mutex::Autolock _l(flinger->mStateLock);
174 flinger->mCurrentState.displays.removeItem(this);
175 flinger->setTransactionFlags(eDisplayTransactionNeeded);
176 }
177 public:
178 DisplayToken(const sp<SurfaceFlinger>& flinger)
179 : flinger(flinger) {
180 }
181 };
182
183 sp<BBinder> token = new DisplayToken(this);
184
185 Mutex::Autolock _l(mStateLock);
186 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
187 info.displayName = displayName;
188 info.isSecure = secure;
189 mCurrentState.displays.add(token, info);
190
191 return token;
192 }
193
getBuiltInDisplay(int32_t id)194 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
195 if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
196 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
197 return NULL;
198 }
199 return mDefaultDisplays[id];
200 }
201
createGraphicBufferAlloc()202 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
203 {
204 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
205 return gba;
206 }
207
bootFinished()208 void SurfaceFlinger::bootFinished()
209 {
210 const nsecs_t now = systemTime();
211 const nsecs_t duration = now - mBootTime;
212 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
213 mBootFinished = true;
214
215 // wait patiently for the window manager death
216 const String16 name("window");
217 sp<IBinder> window(defaultServiceManager()->getService(name));
218 if (window != 0) {
219 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
220 }
221
222 // stop boot animation
223 // formerly we would just kill the process, but we now ask it to exit so it
224 // can choose where to stop the animation.
225 property_set("service.bootanim.exit", "1");
226 }
227
deleteTextureAsync(GLuint texture)228 void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
229 class MessageDestroyGLTexture : public MessageBase {
230 GLuint texture;
231 public:
232 MessageDestroyGLTexture(GLuint texture)
233 : texture(texture) {
234 }
235 virtual bool handler() {
236 glDeleteTextures(1, &texture);
237 return true;
238 }
239 };
240 postMessageAsync(new MessageDestroyGLTexture(texture));
241 }
242
selectConfigForAttribute(EGLDisplay dpy,EGLint const * attrs,EGLint attribute,EGLint wanted,EGLConfig * outConfig)243 status_t SurfaceFlinger::selectConfigForAttribute(
244 EGLDisplay dpy,
245 EGLint const* attrs,
246 EGLint attribute, EGLint wanted,
247 EGLConfig* outConfig)
248 {
249 EGLConfig config = NULL;
250 EGLint numConfigs = -1, n=0;
251 eglGetConfigs(dpy, NULL, 0, &numConfigs);
252 EGLConfig* const configs = new EGLConfig[numConfigs];
253 eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
254
255 if (n) {
256 if (attribute != EGL_NONE) {
257 for (int i=0 ; i<n ; i++) {
258 EGLint value = 0;
259 eglGetConfigAttrib(dpy, configs[i], attribute, &value);
260 if (wanted == value) {
261 *outConfig = configs[i];
262 delete [] configs;
263 return NO_ERROR;
264 }
265 }
266 } else {
267 // just pick the first one
268 *outConfig = configs[0];
269 delete [] configs;
270 return NO_ERROR;
271 }
272 }
273 delete [] configs;
274 return NAME_NOT_FOUND;
275 }
276
277 class EGLAttributeVector {
278 struct Attribute;
279 class Adder;
280 friend class Adder;
281 KeyedVector<Attribute, EGLint> mList;
282 struct Attribute {
Attributeandroid::EGLAttributeVector::Attribute283 Attribute() {};
Attributeandroid::EGLAttributeVector::Attribute284 Attribute(EGLint v) : v(v) { }
285 EGLint v;
operator <android::EGLAttributeVector::Attribute286 bool operator < (const Attribute& other) const {
287 // this places EGL_NONE at the end
288 EGLint lhs(v);
289 EGLint rhs(other.v);
290 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
291 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
292 return lhs < rhs;
293 }
294 };
295 class Adder {
296 friend class EGLAttributeVector;
297 EGLAttributeVector& v;
298 EGLint attribute;
Adder(EGLAttributeVector & v,EGLint attribute)299 Adder(EGLAttributeVector& v, EGLint attribute)
300 : v(v), attribute(attribute) {
301 }
302 public:
operator =(EGLint value)303 void operator = (EGLint value) {
304 if (attribute != EGL_NONE) {
305 v.mList.add(attribute, value);
306 }
307 }
operator EGLint() const308 operator EGLint () const { return v.mList[attribute]; }
309 };
310 public:
EGLAttributeVector()311 EGLAttributeVector() {
312 mList.add(EGL_NONE, EGL_NONE);
313 }
remove(EGLint attribute)314 void remove(EGLint attribute) {
315 if (attribute != EGL_NONE) {
316 mList.removeItem(attribute);
317 }
318 }
operator [](EGLint attribute)319 Adder operator [] (EGLint attribute) {
320 return Adder(*this, attribute);
321 }
operator [](EGLint attribute) const322 EGLint operator [] (EGLint attribute) const {
323 return mList[attribute];
324 }
325 // cast-operator to (EGLint const*)
operator EGLint const*() const326 operator EGLint const* () const { return &mList.keyAt(0).v; }
327 };
328
selectEGLConfig(EGLDisplay display,EGLint nativeVisualId)329 EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
330 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
331 // it is to be used with WIFI displays
332 EGLConfig config;
333 EGLint dummy;
334 status_t err;
335
336 EGLAttributeVector attribs;
337 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT;
338 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE;
339 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
340 attribs[EGL_RED_SIZE] = 8;
341 attribs[EGL_GREEN_SIZE] = 8;
342 attribs[EGL_BLUE_SIZE] = 8;
343
344 err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config);
345 if (!err)
346 goto success;
347
348 // maybe we failed because of EGL_FRAMEBUFFER_TARGET_ANDROID
349 ALOGW("no suitable EGLConfig found, trying without EGL_FRAMEBUFFER_TARGET_ANDROID");
350 attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID);
351 err = selectConfigForAttribute(display, attribs,
352 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
353 if (!err)
354 goto success;
355
356 // maybe we failed because of EGL_RECORDABLE_ANDROID
357 ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID");
358 attribs.remove(EGL_RECORDABLE_ANDROID);
359 err = selectConfigForAttribute(display, attribs,
360 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
361 if (!err)
362 goto success;
363
364 // allow less than 24-bit color; the non-gpu-accelerated emulator only
365 // supports 16-bit color
366 ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed");
367 attribs.remove(EGL_RED_SIZE);
368 attribs.remove(EGL_GREEN_SIZE);
369 attribs.remove(EGL_BLUE_SIZE);
370 err = selectConfigForAttribute(display, attribs,
371 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
372 if (!err)
373 goto success;
374
375 // this EGL is too lame for Android
376 ALOGE("no suitable EGLConfig found, giving up");
377
378 return 0;
379
380 success:
381 if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
382 ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
383 return config;
384 }
385
createGLContext(EGLDisplay display,EGLConfig config)386 EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
387 // Also create our EGLContext
388 EGLint contextAttributes[] = {
389 #ifdef EGL_IMG_context_priority
390 #ifdef HAS_CONTEXT_PRIORITY
391 #warning "using EGL_IMG_context_priority"
392 EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
393 #endif
394 #endif
395 EGL_NONE, EGL_NONE
396 };
397 EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
398 ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
399 return ctxt;
400 }
401
initializeGL(EGLDisplay display)402 void SurfaceFlinger::initializeGL(EGLDisplay display) {
403 GLExtensions& extensions(GLExtensions::getInstance());
404 extensions.initWithGLStrings(
405 glGetString(GL_VENDOR),
406 glGetString(GL_RENDERER),
407 glGetString(GL_VERSION),
408 glGetString(GL_EXTENSIONS),
409 eglQueryString(display, EGL_VENDOR),
410 eglQueryString(display, EGL_VERSION),
411 eglQueryString(display, EGL_EXTENSIONS));
412
413 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
414 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
415
416 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
417 glPixelStorei(GL_PACK_ALIGNMENT, 4);
418 glEnableClientState(GL_VERTEX_ARRAY);
419 glShadeModel(GL_FLAT);
420 glDisable(GL_DITHER);
421 glDisable(GL_CULL_FACE);
422
423 struct pack565 {
424 inline uint16_t operator() (int r, int g, int b) const {
425 return (r<<11)|(g<<5)|b;
426 }
427 } pack565;
428
429 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
430 glGenTextures(1, &mProtectedTexName);
431 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
432 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
433 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
434 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
435 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
436 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
437 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
438
439 // print some debugging info
440 EGLint r,g,b,a;
441 eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE, &r);
442 eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
443 eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE, &b);
444 eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
445 ALOGI("EGL informations:");
446 ALOGI("vendor : %s", extensions.getEglVendor());
447 ALOGI("version : %s", extensions.getEglVersion());
448 ALOGI("extensions: %s", extensions.getEglExtension());
449 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
450 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
451 ALOGI("OpenGL ES informations:");
452 ALOGI("vendor : %s", extensions.getVendor());
453 ALOGI("renderer : %s", extensions.getRenderer());
454 ALOGI("version : %s", extensions.getVersion());
455 ALOGI("extensions: %s", extensions.getExtension());
456 ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
457 ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
458 }
459
readyToRun()460 status_t SurfaceFlinger::readyToRun()
461 {
462 ALOGI( "SurfaceFlinger's main thread ready to run. "
463 "Initializing graphics H/W...");
464
465 // initialize EGL for the default display
466 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
467 eglInitialize(mEGLDisplay, NULL, NULL);
468
469 // Initialize the H/W composer object. There may or may not be an
470 // actual hardware composer underneath.
471 mHwc = new HWComposer(this,
472 *static_cast<HWComposer::EventHandler *>(this));
473
474 // initialize the config and context
475 EGLint format = mHwc->getVisualID();
476 mEGLConfig = selectEGLConfig(mEGLDisplay, format);
477 mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
478
479 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
480 "couldn't create EGLContext");
481
482 // initialize our non-virtual displays
483 for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
484 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
485 mDefaultDisplays[i] = new BBinder();
486 wp<IBinder> token = mDefaultDisplays[i];
487
488 // set-up the displays that are already connected
489 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
490 // All non-virtual displays are currently considered secure.
491 bool isSecure = true;
492 mCurrentState.displays.add(token, DisplayDeviceState(type));
493 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i);
494 sp<SurfaceTextureClient> stc = new SurfaceTextureClient(
495 static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
496 sp<DisplayDevice> hw = new DisplayDevice(this,
497 type, isSecure, token, stc, fbs, mEGLConfig);
498 if (i > DisplayDevice::DISPLAY_PRIMARY) {
499 // FIXME: currently we don't get blank/unblank requests
500 // for displays other than the main display, so we always
501 // assume a connected display is unblanked.
502 ALOGD("marking display %d as acquired/unblanked", i);
503 hw->acquireScreen();
504 }
505 mDisplays.add(token, hw);
506 }
507 }
508
509 // we need a GL context current in a few places, when initializing
510 // OpenGL ES (see below), or creating a layer,
511 // or when a texture is (asynchronously) destroyed, and for that
512 // we need a valid surface, so it's convenient to use the main display
513 // for that.
514 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
515
516 // initialize OpenGL ES
517 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
518 initializeGL(mEGLDisplay);
519
520 // start the EventThread
521 mEventThread = new EventThread(this);
522 mEventQueue.setEventThread(mEventThread);
523
524 // initialize our drawing state
525 mDrawingState = mCurrentState;
526
527
528 // We're now ready to accept clients...
529 mReadyToRunBarrier.open();
530
531 // set initial conditions (e.g. unblank default device)
532 initializeDisplays();
533
534 // start boot animation
535 startBootAnim();
536
537 return NO_ERROR;
538 }
539
allocateHwcDisplayId(DisplayDevice::DisplayType type)540 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
541 return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
542 type : mHwc->allocateDisplayId();
543 }
544
startBootAnim()545 void SurfaceFlinger::startBootAnim() {
546 // start boot animation
547 property_set("service.bootanim.exit", "0");
548 property_set("ctl.start", "bootanim");
549 }
550
getMaxTextureSize() const551 uint32_t SurfaceFlinger::getMaxTextureSize() const {
552 return mMaxTextureSize;
553 }
554
getMaxViewportDims() const555 uint32_t SurfaceFlinger::getMaxViewportDims() const {
556 return mMaxViewportDims[0] < mMaxViewportDims[1] ?
557 mMaxViewportDims[0] : mMaxViewportDims[1];
558 }
559
560 // ----------------------------------------------------------------------------
561
authenticateSurfaceTexture(const sp<ISurfaceTexture> & surfaceTexture) const562 bool SurfaceFlinger::authenticateSurfaceTexture(
563 const sp<ISurfaceTexture>& surfaceTexture) const {
564 Mutex::Autolock _l(mStateLock);
565 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
566
567 // Check the visible layer list for the ISurface
568 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
569 size_t count = currentLayers.size();
570 for (size_t i=0 ; i<count ; i++) {
571 const sp<LayerBase>& layer(currentLayers[i]);
572 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
573 if (lbc != NULL) {
574 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
575 if (lbcBinder == surfaceTextureBinder) {
576 return true;
577 }
578 }
579 }
580
581 // Check the layers in the purgatory. This check is here so that if a
582 // SurfaceTexture gets destroyed before all the clients are done using it,
583 // the error will not be reported as "surface XYZ is not authenticated", but
584 // will instead fail later on when the client tries to use the surface,
585 // which should be reported as "surface XYZ returned an -ENODEV". The
586 // purgatorized layers are no less authentic than the visible ones, so this
587 // should not cause any harm.
588 size_t purgatorySize = mLayerPurgatory.size();
589 for (size_t i=0 ; i<purgatorySize ; i++) {
590 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
591 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
592 if (lbc != NULL) {
593 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
594 if (lbcBinder == surfaceTextureBinder) {
595 return true;
596 }
597 }
598 }
599
600 return false;
601 }
602
getDisplayInfo(const sp<IBinder> & display,DisplayInfo * info)603 status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
604 int32_t type = BAD_VALUE;
605 for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
606 if (display == mDefaultDisplays[i]) {
607 type = i;
608 break;
609 }
610 }
611
612 if (type < 0) {
613 return type;
614 }
615
616 const HWComposer& hwc(getHwComposer());
617 if (!hwc.isConnected(type)) {
618 return NAME_NOT_FOUND;
619 }
620
621 float xdpi = hwc.getDpiX(type);
622 float ydpi = hwc.getDpiY(type);
623
624 // TODO: Not sure if display density should handled by SF any longer
625 class Density {
626 static int getDensityFromProperty(char const* propName) {
627 char property[PROPERTY_VALUE_MAX];
628 int density = 0;
629 if (property_get(propName, property, NULL) > 0) {
630 density = atoi(property);
631 }
632 return density;
633 }
634 public:
635 static int getEmuDensity() {
636 return getDensityFromProperty("qemu.sf.lcd_density"); }
637 static int getBuildDensity() {
638 return getDensityFromProperty("ro.sf.lcd_density"); }
639 };
640
641 if (type == DisplayDevice::DISPLAY_PRIMARY) {
642 // The density of the device is provided by a build property
643 float density = Density::getBuildDensity() / 160.0f;
644 if (density == 0) {
645 // the build doesn't provide a density -- this is wrong!
646 // use xdpi instead
647 ALOGE("ro.sf.lcd_density must be defined as a build property");
648 density = xdpi / 160.0f;
649 }
650 if (Density::getEmuDensity()) {
651 // if "qemu.sf.lcd_density" is specified, it overrides everything
652 xdpi = ydpi = density = Density::getEmuDensity();
653 density /= 160.0f;
654 }
655 info->density = density;
656
657 // TODO: this needs to go away (currently needed only by webkit)
658 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
659 info->orientation = hw->getOrientation();
660 getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
661 } else {
662 // TODO: where should this value come from?
663 static const int TV_DENSITY = 213;
664 info->density = TV_DENSITY / 160.0f;
665 info->orientation = 0;
666 }
667
668 info->w = hwc.getWidth(type);
669 info->h = hwc.getHeight(type);
670 info->xdpi = xdpi;
671 info->ydpi = ydpi;
672 info->fps = float(1e9 / hwc.getRefreshPeriod(type));
673
674 // All non-virtual displays are currently considered secure.
675 info->secure = true;
676
677 return NO_ERROR;
678 }
679
680 // ----------------------------------------------------------------------------
681
createDisplayEventConnection()682 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
683 return mEventThread->createEventConnection();
684 }
685
686 // ----------------------------------------------------------------------------
687
waitForEvent()688 void SurfaceFlinger::waitForEvent() {
689 mEventQueue.waitMessage();
690 }
691
signalTransaction()692 void SurfaceFlinger::signalTransaction() {
693 mEventQueue.invalidate();
694 }
695
signalLayerUpdate()696 void SurfaceFlinger::signalLayerUpdate() {
697 mEventQueue.invalidate();
698 }
699
signalRefresh()700 void SurfaceFlinger::signalRefresh() {
701 mEventQueue.refresh();
702 }
703
postMessageAsync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t flags)704 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
705 nsecs_t reltime, uint32_t flags) {
706 return mEventQueue.postMessage(msg, reltime);
707 }
708
postMessageSync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t flags)709 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
710 nsecs_t reltime, uint32_t flags) {
711 status_t res = mEventQueue.postMessage(msg, reltime);
712 if (res == NO_ERROR) {
713 msg->wait();
714 }
715 return res;
716 }
717
threadLoop()718 bool SurfaceFlinger::threadLoop() {
719 waitForEvent();
720 return true;
721 }
722
onVSyncReceived(int type,nsecs_t timestamp)723 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
724 if (mEventThread == NULL) {
725 // This is a temporary workaround for b/7145521. A non-null pointer
726 // does not mean EventThread has finished initializing, so this
727 // is not a correct fix.
728 ALOGW("WARNING: EventThread not started, ignoring vsync");
729 return;
730 }
731 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
732 // we should only receive DisplayDevice::DisplayType from the vsync callback
733 mEventThread->onVSyncReceived(type, timestamp);
734 }
735 }
736
onHotplugReceived(int type,bool connected)737 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
738 if (mEventThread == NULL) {
739 // This is a temporary workaround for b/7145521. A non-null pointer
740 // does not mean EventThread has finished initializing, so this
741 // is not a correct fix.
742 ALOGW("WARNING: EventThread not started, ignoring hotplug");
743 return;
744 }
745
746 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
747 Mutex::Autolock _l(mStateLock);
748 if (connected == false) {
749 mCurrentState.displays.removeItem(mDefaultDisplays[type]);
750 } else {
751 DisplayDeviceState info((DisplayDevice::DisplayType)type);
752 mCurrentState.displays.add(mDefaultDisplays[type], info);
753 }
754 setTransactionFlags(eDisplayTransactionNeeded);
755
756 // Defer EventThread notification until SF has updated mDisplays.
757 }
758 }
759
eventControl(int disp,int event,int enabled)760 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
761 getHwComposer().eventControl(disp, event, enabled);
762 }
763
onMessageReceived(int32_t what)764 void SurfaceFlinger::onMessageReceived(int32_t what) {
765 ATRACE_CALL();
766 switch (what) {
767 case MessageQueue::INVALIDATE:
768 handleMessageTransaction();
769 handleMessageInvalidate();
770 signalRefresh();
771 break;
772 case MessageQueue::REFRESH:
773 handleMessageRefresh();
774 break;
775 }
776 }
777
handleMessageTransaction()778 void SurfaceFlinger::handleMessageTransaction() {
779 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
780 if (transactionFlags) {
781 handleTransaction(transactionFlags);
782 }
783 }
784
handleMessageInvalidate()785 void SurfaceFlinger::handleMessageInvalidate() {
786 ATRACE_CALL();
787 handlePageFlip();
788 }
789
handleMessageRefresh()790 void SurfaceFlinger::handleMessageRefresh() {
791 ATRACE_CALL();
792 preComposition();
793 rebuildLayerStacks();
794 setUpHWComposer();
795 doDebugFlashRegions();
796 doComposition();
797 postComposition();
798 }
799
doDebugFlashRegions()800 void SurfaceFlinger::doDebugFlashRegions()
801 {
802 // is debugging enabled
803 if (CC_LIKELY(!mDebugRegion))
804 return;
805
806 const bool repaintEverything = mRepaintEverything;
807 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
808 const sp<DisplayDevice>& hw(mDisplays[dpy]);
809 if (hw->canDraw()) {
810 // transform the dirty region into this screen's coordinate space
811 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
812 if (!dirtyRegion.isEmpty()) {
813 // redraw the whole screen
814 doComposeSurfaces(hw, Region(hw->bounds()));
815
816 // and draw the dirty region
817 glDisable(GL_TEXTURE_EXTERNAL_OES);
818 glDisable(GL_TEXTURE_2D);
819 glDisable(GL_BLEND);
820 glColor4f(1, 0, 1, 1);
821 const int32_t height = hw->getHeight();
822 Region::const_iterator it = dirtyRegion.begin();
823 Region::const_iterator const end = dirtyRegion.end();
824 while (it != end) {
825 const Rect& r = *it++;
826 GLfloat vertices[][2] = {
827 { r.left, height - r.top },
828 { r.left, height - r.bottom },
829 { r.right, height - r.bottom },
830 { r.right, height - r.top }
831 };
832 glVertexPointer(2, GL_FLOAT, 0, vertices);
833 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
834 }
835 hw->compositionComplete();
836 hw->swapBuffers(getHwComposer());
837 }
838 }
839 }
840
841 postFramebuffer();
842
843 if (mDebugRegion > 1) {
844 usleep(mDebugRegion * 1000);
845 }
846
847 HWComposer& hwc(getHwComposer());
848 if (hwc.initCheck() == NO_ERROR) {
849 status_t err = hwc.prepare();
850 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
851 }
852 }
853
preComposition()854 void SurfaceFlinger::preComposition()
855 {
856 bool needExtraInvalidate = false;
857 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
858 const size_t count = currentLayers.size();
859 for (size_t i=0 ; i<count ; i++) {
860 if (currentLayers[i]->onPreComposition()) {
861 needExtraInvalidate = true;
862 }
863 }
864 if (needExtraInvalidate) {
865 signalLayerUpdate();
866 }
867 }
868
postComposition()869 void SurfaceFlinger::postComposition()
870 {
871 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
872 const size_t count = currentLayers.size();
873 for (size_t i=0 ; i<count ; i++) {
874 currentLayers[i]->onPostComposition();
875 }
876 }
877
rebuildLayerStacks()878 void SurfaceFlinger::rebuildLayerStacks() {
879 // rebuild the visible layer list per screen
880 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
881 ATRACE_CALL();
882 mVisibleRegionsDirty = false;
883 invalidateHwcGeometry();
884
885 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
886 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
887 Region opaqueRegion;
888 Region dirtyRegion;
889 Vector< sp<LayerBase> > layersSortedByZ;
890 const sp<DisplayDevice>& hw(mDisplays[dpy]);
891 const Transform& tr(hw->getTransform());
892 const Rect bounds(hw->getBounds());
893 if (hw->canDraw()) {
894 SurfaceFlinger::computeVisibleRegions(currentLayers,
895 hw->getLayerStack(), dirtyRegion, opaqueRegion);
896
897 const size_t count = currentLayers.size();
898 for (size_t i=0 ; i<count ; i++) {
899 const sp<LayerBase>& layer(currentLayers[i]);
900 const Layer::State& s(layer->drawingState());
901 if (s.layerStack == hw->getLayerStack()) {
902 Region drawRegion(tr.transform(
903 layer->visibleNonTransparentRegion));
904 drawRegion.andSelf(bounds);
905 if (!drawRegion.isEmpty()) {
906 layersSortedByZ.add(layer);
907 }
908 }
909 }
910 }
911 hw->setVisibleLayersSortedByZ(layersSortedByZ);
912 hw->undefinedRegion.set(bounds);
913 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
914 hw->dirtyRegion.orSelf(dirtyRegion);
915 }
916 }
917 }
918
setUpHWComposer()919 void SurfaceFlinger::setUpHWComposer() {
920 HWComposer& hwc(getHwComposer());
921 if (hwc.initCheck() == NO_ERROR) {
922 // build the h/w work list
923 if (CC_UNLIKELY(mHwWorkListDirty)) {
924 mHwWorkListDirty = false;
925 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
926 sp<const DisplayDevice> hw(mDisplays[dpy]);
927 const int32_t id = hw->getHwcDisplayId();
928 if (id >= 0) {
929 const Vector< sp<LayerBase> >& currentLayers(
930 hw->getVisibleLayersSortedByZ());
931 const size_t count = currentLayers.size();
932 if (hwc.createWorkList(id, count) == NO_ERROR) {
933 HWComposer::LayerListIterator cur = hwc.begin(id);
934 const HWComposer::LayerListIterator end = hwc.end(id);
935 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
936 const sp<LayerBase>& layer(currentLayers[i]);
937 layer->setGeometry(hw, *cur);
938 if (mDebugDisableHWC || mDebugRegion) {
939 cur->setSkip(true);
940 }
941 }
942 }
943 }
944 }
945 }
946
947 // set the per-frame data
948 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
949 sp<const DisplayDevice> hw(mDisplays[dpy]);
950 const int32_t id = hw->getHwcDisplayId();
951 if (id >= 0) {
952 const Vector< sp<LayerBase> >& currentLayers(
953 hw->getVisibleLayersSortedByZ());
954 const size_t count = currentLayers.size();
955 HWComposer::LayerListIterator cur = hwc.begin(id);
956 const HWComposer::LayerListIterator end = hwc.end(id);
957 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
958 /*
959 * update the per-frame h/w composer data for each layer
960 * and build the transparent region of the FB
961 */
962 const sp<LayerBase>& layer(currentLayers[i]);
963 layer->setPerFrameData(hw, *cur);
964 }
965 }
966 }
967
968 status_t err = hwc.prepare();
969 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
970 }
971 }
972
doComposition()973 void SurfaceFlinger::doComposition() {
974 ATRACE_CALL();
975 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
976 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
977 const sp<DisplayDevice>& hw(mDisplays[dpy]);
978 if (hw->canDraw()) {
979 // transform the dirty region into this screen's coordinate space
980 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
981
982 // repaint the framebuffer (if needed)
983 doDisplayComposition(hw, dirtyRegion);
984
985 hw->dirtyRegion.clear();
986 hw->flip(hw->swapRegion);
987 hw->swapRegion.clear();
988 }
989 // inform the h/w that we're done compositing
990 hw->compositionComplete();
991 }
992 postFramebuffer();
993 }
994
postFramebuffer()995 void SurfaceFlinger::postFramebuffer()
996 {
997 ATRACE_CALL();
998
999 const nsecs_t now = systemTime();
1000 mDebugInSwapBuffers = now;
1001
1002 HWComposer& hwc(getHwComposer());
1003 if (hwc.initCheck() == NO_ERROR) {
1004 if (!hwc.supportsFramebufferTarget()) {
1005 // EGL spec says:
1006 // "surface must be bound to the calling thread's current context,
1007 // for the current rendering API."
1008 DisplayDevice::makeCurrent(mEGLDisplay,
1009 getDefaultDisplayDevice(), mEGLContext);
1010 }
1011 hwc.commit();
1012 }
1013
1014 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1015 sp<const DisplayDevice> hw(mDisplays[dpy]);
1016 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
1017 hw->onSwapBuffersCompleted(hwc);
1018 const size_t count = currentLayers.size();
1019 int32_t id = hw->getHwcDisplayId();
1020 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1021 HWComposer::LayerListIterator cur = hwc.begin(id);
1022 const HWComposer::LayerListIterator end = hwc.end(id);
1023 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1024 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1025 }
1026 } else {
1027 for (size_t i = 0; i < count; i++) {
1028 currentLayers[i]->onLayerDisplayed(hw, NULL);
1029 }
1030 }
1031 }
1032
1033 mLastSwapBufferTime = systemTime() - now;
1034 mDebugInSwapBuffers = 0;
1035 }
1036
handleTransaction(uint32_t transactionFlags)1037 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1038 {
1039 ATRACE_CALL();
1040
1041 Mutex::Autolock _l(mStateLock);
1042 const nsecs_t now = systemTime();
1043 mDebugInTransaction = now;
1044
1045 // Here we're guaranteed that some transaction flags are set
1046 // so we can call handleTransactionLocked() unconditionally.
1047 // We call getTransactionFlags(), which will also clear the flags,
1048 // with mStateLock held to guarantee that mCurrentState won't change
1049 // until the transaction is committed.
1050
1051 transactionFlags = getTransactionFlags(eTransactionMask);
1052 handleTransactionLocked(transactionFlags);
1053
1054 mLastTransactionTime = systemTime() - now;
1055 mDebugInTransaction = 0;
1056 invalidateHwcGeometry();
1057 // here the transaction has been committed
1058 }
1059
handleTransactionLocked(uint32_t transactionFlags)1060 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1061 {
1062 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1063 const size_t count = currentLayers.size();
1064
1065 /*
1066 * Traversal of the children
1067 * (perform the transaction for each of them if needed)
1068 */
1069
1070 if (transactionFlags & eTraversalNeeded) {
1071 for (size_t i=0 ; i<count ; i++) {
1072 const sp<LayerBase>& layer(currentLayers[i]);
1073 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1074 if (!trFlags) continue;
1075
1076 const uint32_t flags = layer->doTransaction(0);
1077 if (flags & Layer::eVisibleRegion)
1078 mVisibleRegionsDirty = true;
1079 }
1080 }
1081
1082 /*
1083 * Perform display own transactions if needed
1084 */
1085
1086 if (transactionFlags & eDisplayTransactionNeeded) {
1087 // here we take advantage of Vector's copy-on-write semantics to
1088 // improve performance by skipping the transaction entirely when
1089 // know that the lists are identical
1090 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1091 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1092 if (!curr.isIdenticalTo(draw)) {
1093 mVisibleRegionsDirty = true;
1094 const size_t cc = curr.size();
1095 size_t dc = draw.size();
1096
1097 // find the displays that were removed
1098 // (ie: in drawing state but not in current state)
1099 // also handle displays that changed
1100 // (ie: displays that are in both lists)
1101 for (size_t i=0 ; i<dc ; i++) {
1102 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1103 if (j < 0) {
1104 // in drawing state but not in current state
1105 if (!draw[i].isMainDisplay()) {
1106 // Call makeCurrent() on the primary display so we can
1107 // be sure that nothing associated with this display
1108 // is current.
1109 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1110 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1111 mDisplays.removeItem(draw.keyAt(i));
1112 getHwComposer().disconnectDisplay(draw[i].type);
1113 mEventThread->onHotplugReceived(draw[i].type, false);
1114 } else {
1115 ALOGW("trying to remove the main display");
1116 }
1117 } else {
1118 // this display is in both lists. see if something changed.
1119 const DisplayDeviceState& state(curr[j]);
1120 const wp<IBinder>& display(curr.keyAt(j));
1121 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1122 // changing the surface is like destroying and
1123 // recreating the DisplayDevice, so we just remove it
1124 // from the drawing state, so that it get re-added
1125 // below.
1126 mDisplays.removeItem(display);
1127 mDrawingState.displays.removeItemsAt(i);
1128 dc--; i--;
1129 // at this point we must loop to the next item
1130 continue;
1131 }
1132
1133 const sp<DisplayDevice> disp(getDisplayDevice(display));
1134 if (disp != NULL) {
1135 if (state.layerStack != draw[i].layerStack) {
1136 disp->setLayerStack(state.layerStack);
1137 }
1138 if ((state.orientation != draw[i].orientation)
1139 || (state.viewport != draw[i].viewport)
1140 || (state.frame != draw[i].frame))
1141 {
1142 disp->setProjection(state.orientation,
1143 state.viewport, state.frame);
1144 }
1145 }
1146 }
1147 }
1148
1149 // find displays that were added
1150 // (ie: in current state but not in drawing state)
1151 for (size_t i=0 ; i<cc ; i++) {
1152 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1153 const DisplayDeviceState& state(curr[i]);
1154 bool isSecure = false;
1155
1156 sp<FramebufferSurface> fbs;
1157 sp<SurfaceTextureClient> stc;
1158 if (!state.isVirtualDisplay()) {
1159
1160 ALOGE_IF(state.surface!=NULL,
1161 "adding a supported display, but rendering "
1162 "surface is provided (%p), ignoring it",
1163 state.surface.get());
1164
1165 // All non-virtual displays are currently considered
1166 // secure.
1167 isSecure = true;
1168
1169 // for supported (by hwc) displays we provide our
1170 // own rendering surface
1171 fbs = new FramebufferSurface(*mHwc, state.type);
1172 stc = new SurfaceTextureClient(
1173 static_cast< sp<ISurfaceTexture> >(
1174 fbs->getBufferQueue()));
1175 } else {
1176 if (state.surface != NULL) {
1177 stc = new SurfaceTextureClient(state.surface);
1178 }
1179 isSecure = state.isSecure;
1180 }
1181
1182 const wp<IBinder>& display(curr.keyAt(i));
1183 if (stc != NULL) {
1184 sp<DisplayDevice> hw = new DisplayDevice(this,
1185 state.type, isSecure, display, stc, fbs,
1186 mEGLConfig);
1187 hw->setLayerStack(state.layerStack);
1188 hw->setProjection(state.orientation,
1189 state.viewport, state.frame);
1190 hw->setDisplayName(state.displayName);
1191 mDisplays.add(display, hw);
1192 mEventThread->onHotplugReceived(state.type, true);
1193 }
1194 }
1195 }
1196 }
1197 }
1198
1199 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1200 // The transform hint might have changed for some layers
1201 // (either because a display has changed, or because a layer
1202 // as changed).
1203 //
1204 // Walk through all the layers in currentLayers,
1205 // and update their transform hint.
1206 //
1207 // If a layer is visible only on a single display, then that
1208 // display is used to calculate the hint, otherwise we use the
1209 // default display.
1210 //
1211 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1212 // the hint is set before we acquire a buffer from the surface texture.
1213 //
1214 // NOTE: layer transactions have taken place already, so we use their
1215 // drawing state. However, SurfaceFlinger's own transaction has not
1216 // happened yet, so we must use the current state layer list
1217 // (soon to become the drawing state list).
1218 //
1219 sp<const DisplayDevice> disp;
1220 uint32_t currentlayerStack = 0;
1221 for (size_t i=0; i<count; i++) {
1222 // NOTE: we rely on the fact that layers are sorted by
1223 // layerStack first (so we don't have to traverse the list
1224 // of displays for every layer).
1225 const sp<LayerBase>& layerBase(currentLayers[i]);
1226 uint32_t layerStack = layerBase->drawingState().layerStack;
1227 if (i==0 || currentlayerStack != layerStack) {
1228 currentlayerStack = layerStack;
1229 // figure out if this layerstack is mirrored
1230 // (more than one display) if so, pick the default display,
1231 // if not, pick the only display it's on.
1232 disp.clear();
1233 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1234 sp<const DisplayDevice> hw(mDisplays[dpy]);
1235 if (hw->getLayerStack() == currentlayerStack) {
1236 if (disp == NULL) {
1237 disp = hw;
1238 } else {
1239 disp = getDefaultDisplayDevice();
1240 break;
1241 }
1242 }
1243 }
1244 }
1245 if (disp != NULL) {
1246 // presumably this means this layer is using a layerStack
1247 // that is not visible on any display
1248 layerBase->updateTransformHint(disp);
1249 }
1250 }
1251 }
1252
1253
1254 /*
1255 * Perform our own transaction if needed
1256 */
1257
1258 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1259 if (currentLayers.size() > previousLayers.size()) {
1260 // layers have been added
1261 mVisibleRegionsDirty = true;
1262 }
1263
1264 // some layers might have been removed, so
1265 // we need to update the regions they're exposing.
1266 if (mLayersRemoved) {
1267 mLayersRemoved = false;
1268 mVisibleRegionsDirty = true;
1269 const size_t count = previousLayers.size();
1270 for (size_t i=0 ; i<count ; i++) {
1271 const sp<LayerBase>& layer(previousLayers[i]);
1272 if (currentLayers.indexOf(layer) < 0) {
1273 // this layer is not visible anymore
1274 // TODO: we could traverse the tree from front to back and
1275 // compute the actual visible region
1276 // TODO: we could cache the transformed region
1277 const Layer::State& s(layer->drawingState());
1278 Region visibleReg = s.transform.transform(
1279 Region(Rect(s.active.w, s.active.h)));
1280 invalidateLayerStack(s.layerStack, visibleReg);
1281 }
1282 }
1283 }
1284
1285 commitTransaction();
1286 }
1287
commitTransaction()1288 void SurfaceFlinger::commitTransaction()
1289 {
1290 if (!mLayersPendingRemoval.isEmpty()) {
1291 // Notify removed layers now that they can't be drawn from
1292 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1293 mLayersPendingRemoval[i]->onRemoved();
1294 }
1295 mLayersPendingRemoval.clear();
1296 }
1297
1298 mDrawingState = mCurrentState;
1299 mTransactionPending = false;
1300 mAnimTransactionPending = false;
1301 mTransactionCV.broadcast();
1302 }
1303
computeVisibleRegions(const LayerVector & currentLayers,uint32_t layerStack,Region & outDirtyRegion,Region & outOpaqueRegion)1304 void SurfaceFlinger::computeVisibleRegions(
1305 const LayerVector& currentLayers, uint32_t layerStack,
1306 Region& outDirtyRegion, Region& outOpaqueRegion)
1307 {
1308 ATRACE_CALL();
1309
1310 Region aboveOpaqueLayers;
1311 Region aboveCoveredLayers;
1312 Region dirty;
1313
1314 outDirtyRegion.clear();
1315
1316 size_t i = currentLayers.size();
1317 while (i--) {
1318 const sp<LayerBase>& layer = currentLayers[i];
1319
1320 // start with the whole surface at its current location
1321 const Layer::State& s(layer->drawingState());
1322
1323 // only consider the layers on the given later stack
1324 if (s.layerStack != layerStack)
1325 continue;
1326
1327 /*
1328 * opaqueRegion: area of a surface that is fully opaque.
1329 */
1330 Region opaqueRegion;
1331
1332 /*
1333 * visibleRegion: area of a surface that is visible on screen
1334 * and not fully transparent. This is essentially the layer's
1335 * footprint minus the opaque regions above it.
1336 * Areas covered by a translucent surface are considered visible.
1337 */
1338 Region visibleRegion;
1339
1340 /*
1341 * coveredRegion: area of a surface that is covered by all
1342 * visible regions above it (which includes the translucent areas).
1343 */
1344 Region coveredRegion;
1345
1346 /*
1347 * transparentRegion: area of a surface that is hinted to be completely
1348 * transparent. This is only used to tell when the layer has no visible
1349 * non-transparent regions and can be removed from the layer list. It
1350 * does not affect the visibleRegion of this layer or any layers
1351 * beneath it. The hint may not be correct if apps don't respect the
1352 * SurfaceView restrictions (which, sadly, some don't).
1353 */
1354 Region transparentRegion;
1355
1356
1357 // handle hidden surfaces by setting the visible region to empty
1358 if (CC_LIKELY(layer->isVisible())) {
1359 const bool translucent = !layer->isOpaque();
1360 Rect bounds(layer->computeBounds());
1361 visibleRegion.set(bounds);
1362 if (!visibleRegion.isEmpty()) {
1363 // Remove the transparent area from the visible region
1364 if (translucent) {
1365 const Transform tr(s.transform);
1366 if (tr.transformed()) {
1367 if (tr.preserveRects()) {
1368 // transform the transparent region
1369 transparentRegion = tr.transform(s.transparentRegion);
1370 } else {
1371 // transformation too complex, can't do the
1372 // transparent region optimization.
1373 transparentRegion.clear();
1374 }
1375 } else {
1376 transparentRegion = s.transparentRegion;
1377 }
1378 }
1379
1380 // compute the opaque region
1381 const int32_t layerOrientation = s.transform.getOrientation();
1382 if (s.alpha==255 && !translucent &&
1383 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1384 // the opaque region is the layer's footprint
1385 opaqueRegion = visibleRegion;
1386 }
1387 }
1388 }
1389
1390 // Clip the covered region to the visible region
1391 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1392
1393 // Update aboveCoveredLayers for next (lower) layer
1394 aboveCoveredLayers.orSelf(visibleRegion);
1395
1396 // subtract the opaque region covered by the layers above us
1397 visibleRegion.subtractSelf(aboveOpaqueLayers);
1398
1399 // compute this layer's dirty region
1400 if (layer->contentDirty) {
1401 // we need to invalidate the whole region
1402 dirty = visibleRegion;
1403 // as well, as the old visible region
1404 dirty.orSelf(layer->visibleRegion);
1405 layer->contentDirty = false;
1406 } else {
1407 /* compute the exposed region:
1408 * the exposed region consists of two components:
1409 * 1) what's VISIBLE now and was COVERED before
1410 * 2) what's EXPOSED now less what was EXPOSED before
1411 *
1412 * note that (1) is conservative, we start with the whole
1413 * visible region but only keep what used to be covered by
1414 * something -- which mean it may have been exposed.
1415 *
1416 * (2) handles areas that were not covered by anything but got
1417 * exposed because of a resize.
1418 */
1419 const Region newExposed = visibleRegion - coveredRegion;
1420 const Region oldVisibleRegion = layer->visibleRegion;
1421 const Region oldCoveredRegion = layer->coveredRegion;
1422 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1423 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1424 }
1425 dirty.subtractSelf(aboveOpaqueLayers);
1426
1427 // accumulate to the screen dirty region
1428 outDirtyRegion.orSelf(dirty);
1429
1430 // Update aboveOpaqueLayers for next (lower) layer
1431 aboveOpaqueLayers.orSelf(opaqueRegion);
1432
1433 // Store the visible region in screen space
1434 layer->setVisibleRegion(visibleRegion);
1435 layer->setCoveredRegion(coveredRegion);
1436 layer->setVisibleNonTransparentRegion(
1437 visibleRegion.subtract(transparentRegion));
1438 }
1439
1440 outOpaqueRegion = aboveOpaqueLayers;
1441 }
1442
invalidateLayerStack(uint32_t layerStack,const Region & dirty)1443 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1444 const Region& dirty) {
1445 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1446 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1447 if (hw->getLayerStack() == layerStack) {
1448 hw->dirtyRegion.orSelf(dirty);
1449 }
1450 }
1451 }
1452
handlePageFlip()1453 void SurfaceFlinger::handlePageFlip()
1454 {
1455 Region dirtyRegion;
1456
1457 bool visibleRegions = false;
1458 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1459 const size_t count = currentLayers.size();
1460 for (size_t i=0 ; i<count ; i++) {
1461 const sp<LayerBase>& layer(currentLayers[i]);
1462 const Region dirty(layer->latchBuffer(visibleRegions));
1463 const Layer::State& s(layer->drawingState());
1464 invalidateLayerStack(s.layerStack, dirty);
1465 }
1466
1467 mVisibleRegionsDirty |= visibleRegions;
1468 }
1469
invalidateHwcGeometry()1470 void SurfaceFlinger::invalidateHwcGeometry()
1471 {
1472 mHwWorkListDirty = true;
1473 }
1474
1475
doDisplayComposition(const sp<const DisplayDevice> & hw,const Region & inDirtyRegion)1476 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1477 const Region& inDirtyRegion)
1478 {
1479 Region dirtyRegion(inDirtyRegion);
1480
1481 // compute the invalid region
1482 hw->swapRegion.orSelf(dirtyRegion);
1483
1484 uint32_t flags = hw->getFlags();
1485 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1486 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1487 // takes a rectangle, we must make sure to update that whole
1488 // rectangle in that case
1489 dirtyRegion.set(hw->swapRegion.bounds());
1490 } else {
1491 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1492 // We need to redraw the rectangle that will be updated
1493 // (pushed to the framebuffer).
1494 // This is needed because PARTIAL_UPDATES only takes one
1495 // rectangle instead of a region (see DisplayDevice::flip())
1496 dirtyRegion.set(hw->swapRegion.bounds());
1497 } else {
1498 // we need to redraw everything (the whole screen)
1499 dirtyRegion.set(hw->bounds());
1500 hw->swapRegion = dirtyRegion;
1501 }
1502 }
1503
1504 doComposeSurfaces(hw, dirtyRegion);
1505
1506 // update the swap region and clear the dirty region
1507 hw->swapRegion.orSelf(dirtyRegion);
1508
1509 // swap buffers (presentation)
1510 hw->swapBuffers(getHwComposer());
1511 }
1512
doComposeSurfaces(const sp<const DisplayDevice> & hw,const Region & dirty)1513 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1514 {
1515 const int32_t id = hw->getHwcDisplayId();
1516 HWComposer& hwc(getHwComposer());
1517 HWComposer::LayerListIterator cur = hwc.begin(id);
1518 const HWComposer::LayerListIterator end = hwc.end(id);
1519
1520 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1521 if (hasGlesComposition) {
1522 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1523
1524 // set the frame buffer
1525 glMatrixMode(GL_MODELVIEW);
1526 glLoadIdentity();
1527
1528 // Never touch the framebuffer if we don't have any framebuffer layers
1529 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1530 if (hasHwcComposition) {
1531 // when using overlays, we assume a fully transparent framebuffer
1532 // NOTE: we could reduce how much we need to clear, for instance
1533 // remove where there are opaque FB layers. however, on some
1534 // GPUs doing a "clean slate" glClear might be more efficient.
1535 // We'll revisit later if needed.
1536 glClearColor(0, 0, 0, 0);
1537 glClear(GL_COLOR_BUFFER_BIT);
1538 } else {
1539 const Region region(hw->undefinedRegion.intersect(dirty));
1540 // screen is already cleared here
1541 if (!region.isEmpty()) {
1542 // can happen with SurfaceView
1543 drawWormhole(hw, region);
1544 }
1545 }
1546
1547 if (hw->getDisplayType() >= DisplayDevice::DISPLAY_EXTERNAL) {
1548 // TODO: just to be on the safe side, we don't set the
1549 // scissor on the main display. It should never be needed
1550 // anyways (though in theory it could since the API allows it).
1551 const Rect& bounds(hw->getBounds());
1552 const Transform& tr(hw->getTransform());
1553 const Rect scissor(tr.transform(hw->getViewport()));
1554 if (scissor != bounds) {
1555 // scissor doesn't match the screen's dimensions, so we
1556 // need to clear everything outside of it and enable
1557 // the GL scissor so we don't draw anything where we shouldn't
1558 const GLint height = hw->getHeight();
1559 glScissor(scissor.left, height - scissor.bottom,
1560 scissor.getWidth(), scissor.getHeight());
1561 // clear everything unscissored
1562 glClearColor(0, 0, 0, 0);
1563 glClear(GL_COLOR_BUFFER_BIT);
1564 // enable scissor for this frame
1565 glEnable(GL_SCISSOR_TEST);
1566 }
1567 }
1568 }
1569
1570 /*
1571 * and then, render the layers targeted at the framebuffer
1572 */
1573
1574 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1575 const size_t count = layers.size();
1576 const Transform& tr = hw->getTransform();
1577 if (cur != end) {
1578 // we're using h/w composer
1579 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1580 const sp<LayerBase>& layer(layers[i]);
1581 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1582 if (!clip.isEmpty()) {
1583 switch (cur->getCompositionType()) {
1584 case HWC_OVERLAY: {
1585 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1586 && i
1587 && layer->isOpaque()
1588 && hasGlesComposition) {
1589 // never clear the very first layer since we're
1590 // guaranteed the FB is already cleared
1591 layer->clearWithOpenGL(hw, clip);
1592 }
1593 break;
1594 }
1595 case HWC_FRAMEBUFFER: {
1596 layer->draw(hw, clip);
1597 break;
1598 }
1599 case HWC_FRAMEBUFFER_TARGET: {
1600 // this should not happen as the iterator shouldn't
1601 // let us get there.
1602 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1603 break;
1604 }
1605 }
1606 }
1607 layer->setAcquireFence(hw, *cur);
1608 }
1609 } else {
1610 // we're not using h/w composer
1611 for (size_t i=0 ; i<count ; ++i) {
1612 const sp<LayerBase>& layer(layers[i]);
1613 const Region clip(dirty.intersect(
1614 tr.transform(layer->visibleRegion)));
1615 if (!clip.isEmpty()) {
1616 layer->draw(hw, clip);
1617 }
1618 }
1619 }
1620
1621 // disable scissor at the end of the frame
1622 glDisable(GL_SCISSOR_TEST);
1623 }
1624
drawWormhole(const sp<const DisplayDevice> & hw,const Region & region) const1625 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1626 const Region& region) const
1627 {
1628 glDisable(GL_TEXTURE_EXTERNAL_OES);
1629 glDisable(GL_TEXTURE_2D);
1630 glDisable(GL_BLEND);
1631 glColor4f(0,0,0,0);
1632
1633 const int32_t height = hw->getHeight();
1634 Region::const_iterator it = region.begin();
1635 Region::const_iterator const end = region.end();
1636 while (it != end) {
1637 const Rect& r = *it++;
1638 GLfloat vertices[][2] = {
1639 { r.left, height - r.top },
1640 { r.left, height - r.bottom },
1641 { r.right, height - r.bottom },
1642 { r.right, height - r.top }
1643 };
1644 glVertexPointer(2, GL_FLOAT, 0, vertices);
1645 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1646 }
1647 }
1648
addClientLayer(const sp<Client> & client,const sp<LayerBaseClient> & lbc)1649 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1650 const sp<LayerBaseClient>& lbc)
1651 {
1652 // attach this layer to the client
1653 size_t name = client->attachLayer(lbc);
1654
1655 // add this layer to the current state list
1656 Mutex::Autolock _l(mStateLock);
1657 mCurrentState.layersSortedByZ.add(lbc);
1658
1659 return ssize_t(name);
1660 }
1661
removeLayer(const sp<LayerBase> & layer)1662 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1663 {
1664 Mutex::Autolock _l(mStateLock);
1665 status_t err = purgatorizeLayer_l(layer);
1666 if (err == NO_ERROR)
1667 setTransactionFlags(eTransactionNeeded);
1668 return err;
1669 }
1670
removeLayer_l(const sp<LayerBase> & layerBase)1671 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1672 {
1673 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1674 if (index >= 0) {
1675 mLayersRemoved = true;
1676 return NO_ERROR;
1677 }
1678 return status_t(index);
1679 }
1680
purgatorizeLayer_l(const sp<LayerBase> & layerBase)1681 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1682 {
1683 // First add the layer to the purgatory list, which makes sure it won't
1684 // go away, then remove it from the main list (through a transaction).
1685 ssize_t err = removeLayer_l(layerBase);
1686 if (err >= 0) {
1687 mLayerPurgatory.add(layerBase);
1688 }
1689
1690 mLayersPendingRemoval.push(layerBase);
1691
1692 // it's possible that we don't find a layer, because it might
1693 // have been destroyed already -- this is not technically an error
1694 // from the user because there is a race between Client::destroySurface(),
1695 // ~Client() and ~ISurface().
1696 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1697 }
1698
peekTransactionFlags(uint32_t flags)1699 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1700 {
1701 return android_atomic_release_load(&mTransactionFlags);
1702 }
1703
getTransactionFlags(uint32_t flags)1704 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1705 {
1706 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1707 }
1708
setTransactionFlags(uint32_t flags)1709 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1710 {
1711 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1712 if ((old & flags)==0) { // wake the server up
1713 signalTransaction();
1714 }
1715 return old;
1716 }
1717
setTransactionState(const Vector<ComposerState> & state,const Vector<DisplayState> & displays,uint32_t flags)1718 void SurfaceFlinger::setTransactionState(
1719 const Vector<ComposerState>& state,
1720 const Vector<DisplayState>& displays,
1721 uint32_t flags)
1722 {
1723 ATRACE_CALL();
1724 Mutex::Autolock _l(mStateLock);
1725 uint32_t transactionFlags = 0;
1726
1727 if (flags & eAnimation) {
1728 // For window updates that are part of an animation we must wait for
1729 // previous animation "frames" to be handled.
1730 while (mAnimTransactionPending) {
1731 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1732 if (CC_UNLIKELY(err != NO_ERROR)) {
1733 // just in case something goes wrong in SF, return to the
1734 // caller after a few seconds.
1735 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1736 "waiting for previous animation frame");
1737 mAnimTransactionPending = false;
1738 break;
1739 }
1740 }
1741 }
1742
1743 size_t count = displays.size();
1744 for (size_t i=0 ; i<count ; i++) {
1745 const DisplayState& s(displays[i]);
1746 transactionFlags |= setDisplayStateLocked(s);
1747 }
1748
1749 count = state.size();
1750 for (size_t i=0 ; i<count ; i++) {
1751 const ComposerState& s(state[i]);
1752 // Here we need to check that the interface we're given is indeed
1753 // one of our own. A malicious client could give us a NULL
1754 // IInterface, or one of its own or even one of our own but a
1755 // different type. All these situations would cause us to crash.
1756 //
1757 // NOTE: it would be better to use RTTI as we could directly check
1758 // that we have a Client*. however, RTTI is disabled in Android.
1759 if (s.client != NULL) {
1760 sp<IBinder> binder = s.client->asBinder();
1761 if (binder != NULL) {
1762 String16 desc(binder->getInterfaceDescriptor());
1763 if (desc == ISurfaceComposerClient::descriptor) {
1764 sp<Client> client( static_cast<Client *>(s.client.get()) );
1765 transactionFlags |= setClientStateLocked(client, s.state);
1766 }
1767 }
1768 }
1769 }
1770
1771 if (transactionFlags) {
1772 // this triggers the transaction
1773 setTransactionFlags(transactionFlags);
1774
1775 // if this is a synchronous transaction, wait for it to take effect
1776 // before returning.
1777 if (flags & eSynchronous) {
1778 mTransactionPending = true;
1779 }
1780 if (flags & eAnimation) {
1781 mAnimTransactionPending = true;
1782 }
1783 while (mTransactionPending) {
1784 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1785 if (CC_UNLIKELY(err != NO_ERROR)) {
1786 // just in case something goes wrong in SF, return to the
1787 // called after a few seconds.
1788 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1789 mTransactionPending = false;
1790 break;
1791 }
1792 }
1793 }
1794 }
1795
setDisplayStateLocked(const DisplayState & s)1796 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1797 {
1798 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1799 if (dpyIdx < 0)
1800 return 0;
1801
1802 uint32_t flags = 0;
1803 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1804 if (disp.isValid()) {
1805 const uint32_t what = s.what;
1806 if (what & DisplayState::eSurfaceChanged) {
1807 if (disp.surface->asBinder() != s.surface->asBinder()) {
1808 disp.surface = s.surface;
1809 flags |= eDisplayTransactionNeeded;
1810 }
1811 }
1812 if (what & DisplayState::eLayerStackChanged) {
1813 if (disp.layerStack != s.layerStack) {
1814 disp.layerStack = s.layerStack;
1815 flags |= eDisplayTransactionNeeded;
1816 }
1817 }
1818 if (what & DisplayState::eDisplayProjectionChanged) {
1819 if (disp.orientation != s.orientation) {
1820 disp.orientation = s.orientation;
1821 flags |= eDisplayTransactionNeeded;
1822 }
1823 if (disp.frame != s.frame) {
1824 disp.frame = s.frame;
1825 flags |= eDisplayTransactionNeeded;
1826 }
1827 if (disp.viewport != s.viewport) {
1828 disp.viewport = s.viewport;
1829 flags |= eDisplayTransactionNeeded;
1830 }
1831 }
1832 }
1833 return flags;
1834 }
1835
setClientStateLocked(const sp<Client> & client,const layer_state_t & s)1836 uint32_t SurfaceFlinger::setClientStateLocked(
1837 const sp<Client>& client,
1838 const layer_state_t& s)
1839 {
1840 uint32_t flags = 0;
1841 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1842 if (layer != 0) {
1843 const uint32_t what = s.what;
1844 if (what & layer_state_t::ePositionChanged) {
1845 if (layer->setPosition(s.x, s.y))
1846 flags |= eTraversalNeeded;
1847 }
1848 if (what & layer_state_t::eLayerChanged) {
1849 // NOTE: index needs to be calculated before we update the state
1850 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1851 if (layer->setLayer(s.z)) {
1852 mCurrentState.layersSortedByZ.removeAt(idx);
1853 mCurrentState.layersSortedByZ.add(layer);
1854 // we need traversal (state changed)
1855 // AND transaction (list changed)
1856 flags |= eTransactionNeeded|eTraversalNeeded;
1857 }
1858 }
1859 if (what & layer_state_t::eSizeChanged) {
1860 if (layer->setSize(s.w, s.h)) {
1861 flags |= eTraversalNeeded;
1862 }
1863 }
1864 if (what & layer_state_t::eAlphaChanged) {
1865 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1866 flags |= eTraversalNeeded;
1867 }
1868 if (what & layer_state_t::eMatrixChanged) {
1869 if (layer->setMatrix(s.matrix))
1870 flags |= eTraversalNeeded;
1871 }
1872 if (what & layer_state_t::eTransparentRegionChanged) {
1873 if (layer->setTransparentRegionHint(s.transparentRegion))
1874 flags |= eTraversalNeeded;
1875 }
1876 if (what & layer_state_t::eVisibilityChanged) {
1877 if (layer->setFlags(s.flags, s.mask))
1878 flags |= eTraversalNeeded;
1879 }
1880 if (what & layer_state_t::eCropChanged) {
1881 if (layer->setCrop(s.crop))
1882 flags |= eTraversalNeeded;
1883 }
1884 if (what & layer_state_t::eLayerStackChanged) {
1885 // NOTE: index needs to be calculated before we update the state
1886 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1887 if (layer->setLayerStack(s.layerStack)) {
1888 mCurrentState.layersSortedByZ.removeAt(idx);
1889 mCurrentState.layersSortedByZ.add(layer);
1890 // we need traversal (state changed)
1891 // AND transaction (list changed)
1892 flags |= eTransactionNeeded|eTraversalNeeded;
1893 }
1894 }
1895 }
1896 return flags;
1897 }
1898
createLayer(ISurfaceComposerClient::surface_data_t * params,const String8 & name,const sp<Client> & client,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags)1899 sp<ISurface> SurfaceFlinger::createLayer(
1900 ISurfaceComposerClient::surface_data_t* params,
1901 const String8& name,
1902 const sp<Client>& client,
1903 uint32_t w, uint32_t h, PixelFormat format,
1904 uint32_t flags)
1905 {
1906 sp<LayerBaseClient> layer;
1907 sp<ISurface> surfaceHandle;
1908
1909 if (int32_t(w|h) < 0) {
1910 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1911 int(w), int(h));
1912 return surfaceHandle;
1913 }
1914
1915 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1916 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1917 case ISurfaceComposerClient::eFXSurfaceNormal:
1918 layer = createNormalLayer(client, w, h, flags, format);
1919 break;
1920 case ISurfaceComposerClient::eFXSurfaceBlur:
1921 case ISurfaceComposerClient::eFXSurfaceDim:
1922 layer = createDimLayer(client, w, h, flags);
1923 break;
1924 case ISurfaceComposerClient::eFXSurfaceScreenshot:
1925 layer = createScreenshotLayer(client, w, h, flags);
1926 break;
1927 }
1928
1929 if (layer != 0) {
1930 layer->initStates(w, h, flags);
1931 layer->setName(name);
1932 ssize_t token = addClientLayer(client, layer);
1933 surfaceHandle = layer->getSurface();
1934 if (surfaceHandle != 0) {
1935 params->token = token;
1936 params->identity = layer->getIdentity();
1937 }
1938 setTransactionFlags(eTransactionNeeded);
1939 }
1940
1941 return surfaceHandle;
1942 }
1943
createNormalLayer(const sp<Client> & client,uint32_t w,uint32_t h,uint32_t flags,PixelFormat & format)1944 sp<Layer> SurfaceFlinger::createNormalLayer(
1945 const sp<Client>& client,
1946 uint32_t w, uint32_t h, uint32_t flags,
1947 PixelFormat& format)
1948 {
1949 // initialize the surfaces
1950 switch (format) {
1951 case PIXEL_FORMAT_TRANSPARENT:
1952 case PIXEL_FORMAT_TRANSLUCENT:
1953 format = PIXEL_FORMAT_RGBA_8888;
1954 break;
1955 case PIXEL_FORMAT_OPAQUE:
1956 #ifdef NO_RGBX_8888
1957 format = PIXEL_FORMAT_RGB_565;
1958 #else
1959 format = PIXEL_FORMAT_RGBX_8888;
1960 #endif
1961 break;
1962 }
1963
1964 #ifdef NO_RGBX_8888
1965 if (format == PIXEL_FORMAT_RGBX_8888)
1966 format = PIXEL_FORMAT_RGBA_8888;
1967 #endif
1968
1969 sp<Layer> layer = new Layer(this, client);
1970 status_t err = layer->setBuffers(w, h, format, flags);
1971 if (CC_LIKELY(err != NO_ERROR)) {
1972 ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1973 layer.clear();
1974 }
1975 return layer;
1976 }
1977
createDimLayer(const sp<Client> & client,uint32_t w,uint32_t h,uint32_t flags)1978 sp<LayerDim> SurfaceFlinger::createDimLayer(
1979 const sp<Client>& client,
1980 uint32_t w, uint32_t h, uint32_t flags)
1981 {
1982 sp<LayerDim> layer = new LayerDim(this, client);
1983 return layer;
1984 }
1985
createScreenshotLayer(const sp<Client> & client,uint32_t w,uint32_t h,uint32_t flags)1986 sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1987 const sp<Client>& client,
1988 uint32_t w, uint32_t h, uint32_t flags)
1989 {
1990 sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1991 return layer;
1992 }
1993
onLayerRemoved(const sp<Client> & client,SurfaceID sid)1994 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1995 {
1996 /*
1997 * called by the window manager, when a surface should be marked for
1998 * destruction.
1999 *
2000 * The surface is removed from the current and drawing lists, but placed
2001 * in the purgatory queue, so it's not destroyed right-away (we need
2002 * to wait for all client's references to go away first).
2003 */
2004
2005 status_t err = NAME_NOT_FOUND;
2006 Mutex::Autolock _l(mStateLock);
2007 sp<LayerBaseClient> layer = client->getLayerUser(sid);
2008
2009 if (layer != 0) {
2010 err = purgatorizeLayer_l(layer);
2011 if (err == NO_ERROR) {
2012 setTransactionFlags(eTransactionNeeded);
2013 }
2014 }
2015 return err;
2016 }
2017
onLayerDestroyed(const wp<LayerBaseClient> & layer)2018 status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
2019 {
2020 // called by ~ISurface() when all references are gone
2021 status_t err = NO_ERROR;
2022 sp<LayerBaseClient> l(layer.promote());
2023 if (l != NULL) {
2024 Mutex::Autolock _l(mStateLock);
2025 err = removeLayer_l(l);
2026 if (err == NAME_NOT_FOUND) {
2027 // The surface wasn't in the current list, which means it was
2028 // removed already, which means it is in the purgatory,
2029 // and need to be removed from there.
2030 ssize_t idx = mLayerPurgatory.remove(l);
2031 ALOGE_IF(idx < 0,
2032 "layer=%p is not in the purgatory list", l.get());
2033 }
2034 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2035 "error removing layer=%p (%s)", l.get(), strerror(-err));
2036 }
2037 return err;
2038 }
2039
2040 // ---------------------------------------------------------------------------
2041
onInitializeDisplays()2042 void SurfaceFlinger::onInitializeDisplays() {
2043 // reset screen orientation
2044 Vector<ComposerState> state;
2045 Vector<DisplayState> displays;
2046 DisplayState d;
2047 d.what = DisplayState::eDisplayProjectionChanged;
2048 d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
2049 d.orientation = DisplayState::eOrientationDefault;
2050 d.frame.makeInvalid();
2051 d.viewport.makeInvalid();
2052 displays.add(d);
2053 setTransactionState(state, displays, 0);
2054 onScreenAcquired(getDefaultDisplayDevice());
2055 }
2056
initializeDisplays()2057 void SurfaceFlinger::initializeDisplays() {
2058 class MessageScreenInitialized : public MessageBase {
2059 SurfaceFlinger* flinger;
2060 public:
2061 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2062 virtual bool handler() {
2063 flinger->onInitializeDisplays();
2064 return true;
2065 }
2066 };
2067 sp<MessageBase> msg = new MessageScreenInitialized(this);
2068 postMessageAsync(msg); // we may be called from main thread, use async message
2069 }
2070
2071
onScreenAcquired(const sp<const DisplayDevice> & hw)2072 void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2073 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2074 if (hw->isScreenAcquired()) {
2075 // this is expected, e.g. when power manager wakes up during boot
2076 ALOGD(" screen was previously acquired");
2077 return;
2078 }
2079
2080 hw->acquireScreen();
2081 int32_t type = hw->getDisplayType();
2082 if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2083 // built-in display, tell the HWC
2084 getHwComposer().acquire(type);
2085
2086 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2087 // FIXME: eventthread only knows about the main display right now
2088 mEventThread->onScreenAcquired();
2089 }
2090 }
2091 mVisibleRegionsDirty = true;
2092 repaintEverything();
2093 }
2094
onScreenReleased(const sp<const DisplayDevice> & hw)2095 void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2096 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2097 if (!hw->isScreenAcquired()) {
2098 ALOGD(" screen was previously released");
2099 return;
2100 }
2101
2102 hw->releaseScreen();
2103 int32_t type = hw->getDisplayType();
2104 if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2105 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2106 // FIXME: eventthread only knows about the main display right now
2107 mEventThread->onScreenReleased();
2108 }
2109
2110 // built-in display, tell the HWC
2111 getHwComposer().release(type);
2112 }
2113 mVisibleRegionsDirty = true;
2114 // from this point on, SF will stop drawing on this display
2115 }
2116
unblank(const sp<IBinder> & display)2117 void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2118 class MessageScreenAcquired : public MessageBase {
2119 SurfaceFlinger& mFlinger;
2120 sp<IBinder> mDisplay;
2121 public:
2122 MessageScreenAcquired(SurfaceFlinger& flinger,
2123 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2124 virtual bool handler() {
2125 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2126 if (hw == NULL) {
2127 ALOGE("Attempt to unblank null display %p", mDisplay.get());
2128 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2129 ALOGW("Attempt to unblank virtual display");
2130 } else {
2131 mFlinger.onScreenAcquired(hw);
2132 }
2133 return true;
2134 }
2135 };
2136 sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2137 postMessageSync(msg);
2138 }
2139
blank(const sp<IBinder> & display)2140 void SurfaceFlinger::blank(const sp<IBinder>& display) {
2141 class MessageScreenReleased : public MessageBase {
2142 SurfaceFlinger& mFlinger;
2143 sp<IBinder> mDisplay;
2144 public:
2145 MessageScreenReleased(SurfaceFlinger& flinger,
2146 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2147 virtual bool handler() {
2148 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2149 if (hw == NULL) {
2150 ALOGE("Attempt to blank null display %p", mDisplay.get());
2151 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2152 ALOGW("Attempt to blank virtual display");
2153 } else {
2154 mFlinger.onScreenReleased(hw);
2155 }
2156 return true;
2157 }
2158 };
2159 sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2160 postMessageSync(msg);
2161 }
2162
2163 // ---------------------------------------------------------------------------
2164
dump(int fd,const Vector<String16> & args)2165 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2166 {
2167 const size_t SIZE = 4096;
2168 char buffer[SIZE];
2169 String8 result;
2170
2171 if (!PermissionCache::checkCallingPermission(sDump)) {
2172 snprintf(buffer, SIZE, "Permission Denial: "
2173 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
2174 IPCThreadState::self()->getCallingPid(),
2175 IPCThreadState::self()->getCallingUid());
2176 result.append(buffer);
2177 } else {
2178 // Try to get the main lock, but don't insist if we can't
2179 // (this would indicate SF is stuck, but we want to be able to
2180 // print something in dumpsys).
2181 int retry = 3;
2182 while (mStateLock.tryLock()<0 && --retry>=0) {
2183 usleep(1000000);
2184 }
2185 const bool locked(retry >= 0);
2186 if (!locked) {
2187 snprintf(buffer, SIZE,
2188 "SurfaceFlinger appears to be unresponsive, "
2189 "dumping anyways (no locks held)\n");
2190 result.append(buffer);
2191 }
2192
2193 bool dumpAll = true;
2194 size_t index = 0;
2195 size_t numArgs = args.size();
2196 if (numArgs) {
2197 if ((index < numArgs) &&
2198 (args[index] == String16("--list"))) {
2199 index++;
2200 listLayersLocked(args, index, result, buffer, SIZE);
2201 dumpAll = false;
2202 }
2203
2204 if ((index < numArgs) &&
2205 (args[index] == String16("--latency"))) {
2206 index++;
2207 dumpStatsLocked(args, index, result, buffer, SIZE);
2208 dumpAll = false;
2209 }
2210
2211 if ((index < numArgs) &&
2212 (args[index] == String16("--latency-clear"))) {
2213 index++;
2214 clearStatsLocked(args, index, result, buffer, SIZE);
2215 dumpAll = false;
2216 }
2217 }
2218
2219 if (dumpAll) {
2220 dumpAllLocked(result, buffer, SIZE);
2221 }
2222
2223 if (locked) {
2224 mStateLock.unlock();
2225 }
2226 }
2227 write(fd, result.string(), result.size());
2228 return NO_ERROR;
2229 }
2230
listLayersLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const2231 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2232 String8& result, char* buffer, size_t SIZE) const
2233 {
2234 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2235 const size_t count = currentLayers.size();
2236 for (size_t i=0 ; i<count ; i++) {
2237 const sp<LayerBase>& layer(currentLayers[i]);
2238 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2239 result.append(buffer);
2240 }
2241 }
2242
dumpStatsLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const2243 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2244 String8& result, char* buffer, size_t SIZE) const
2245 {
2246 String8 name;
2247 if (index < args.size()) {
2248 name = String8(args[index]);
2249 index++;
2250 }
2251
2252 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2253 const size_t count = currentLayers.size();
2254 for (size_t i=0 ; i<count ; i++) {
2255 const sp<LayerBase>& layer(currentLayers[i]);
2256 if (name.isEmpty()) {
2257 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2258 result.append(buffer);
2259 }
2260 if (name.isEmpty() || (name == layer->getName())) {
2261 layer->dumpStats(result, buffer, SIZE);
2262 }
2263 }
2264 }
2265
clearStatsLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const2266 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2267 String8& result, char* buffer, size_t SIZE) const
2268 {
2269 String8 name;
2270 if (index < args.size()) {
2271 name = String8(args[index]);
2272 index++;
2273 }
2274
2275 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2276 const size_t count = currentLayers.size();
2277 for (size_t i=0 ; i<count ; i++) {
2278 const sp<LayerBase>& layer(currentLayers[i]);
2279 if (name.isEmpty() || (name == layer->getName())) {
2280 layer->clearStats();
2281 }
2282 }
2283 }
2284
appendSfConfigString(String8 & result)2285 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2286 {
2287 static const char* config =
2288 " [sf"
2289 #ifdef NO_RGBX_8888
2290 " NO_RGBX_8888"
2291 #endif
2292 #ifdef HAS_CONTEXT_PRIORITY
2293 " HAS_CONTEXT_PRIORITY"
2294 #endif
2295 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2296 " NEVER_DEFAULT_TO_ASYNC_MODE"
2297 #endif
2298 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2299 " TARGET_DISABLE_TRIPLE_BUFFERING"
2300 #endif
2301 "]";
2302 result.append(config);
2303 }
2304
dumpAllLocked(String8 & result,char * buffer,size_t SIZE) const2305 void SurfaceFlinger::dumpAllLocked(
2306 String8& result, char* buffer, size_t SIZE) const
2307 {
2308 // figure out if we're stuck somewhere
2309 const nsecs_t now = systemTime();
2310 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2311 const nsecs_t inTransaction(mDebugInTransaction);
2312 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2313 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2314
2315 /*
2316 * Dump library configuration.
2317 */
2318 result.append("Build configuration:");
2319 appendSfConfigString(result);
2320 appendUiConfigString(result);
2321 appendGuiConfigString(result);
2322 result.append("\n");
2323
2324 /*
2325 * Dump the visible layer list
2326 */
2327 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2328 const size_t count = currentLayers.size();
2329 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
2330 result.append(buffer);
2331 for (size_t i=0 ; i<count ; i++) {
2332 const sp<LayerBase>& layer(currentLayers[i]);
2333 layer->dump(result, buffer, SIZE);
2334 }
2335
2336 /*
2337 * Dump the layers in the purgatory
2338 */
2339
2340 const size_t purgatorySize = mLayerPurgatory.size();
2341 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
2342 result.append(buffer);
2343 for (size_t i=0 ; i<purgatorySize ; i++) {
2344 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
2345 layer->shortDump(result, buffer, SIZE);
2346 }
2347
2348 /*
2349 * Dump Display state
2350 */
2351
2352 snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size());
2353 result.append(buffer);
2354 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2355 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2356 hw->dump(result, buffer, SIZE);
2357 }
2358
2359 /*
2360 * Dump SurfaceFlinger global state
2361 */
2362
2363 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
2364 result.append(buffer);
2365
2366 HWComposer& hwc(getHwComposer());
2367 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2368 const GLExtensions& extensions(GLExtensions::getInstance());
2369 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2370 extensions.getVendor(),
2371 extensions.getRenderer(),
2372 extensions.getVersion());
2373 result.append(buffer);
2374
2375 snprintf(buffer, SIZE, "EGL : %s\n",
2376 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2377 result.append(buffer);
2378
2379 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2380 result.append(buffer);
2381
2382 hw->undefinedRegion.dump(result, "undefinedRegion");
2383 snprintf(buffer, SIZE,
2384 " orientation=%d, canDraw=%d\n",
2385 hw->getOrientation(), hw->canDraw());
2386 result.append(buffer);
2387 snprintf(buffer, SIZE,
2388 " last eglSwapBuffers() time: %f us\n"
2389 " last transaction time : %f us\n"
2390 " transaction-flags : %08x\n"
2391 " refresh-rate : %f fps\n"
2392 " x-dpi : %f\n"
2393 " y-dpi : %f\n",
2394 mLastSwapBufferTime/1000.0,
2395 mLastTransactionTime/1000.0,
2396 mTransactionFlags,
2397 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2398 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2399 hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2400 result.append(buffer);
2401
2402 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
2403 inSwapBuffersDuration/1000.0);
2404 result.append(buffer);
2405
2406 snprintf(buffer, SIZE, " transaction time: %f us\n",
2407 inTransactionDuration/1000.0);
2408 result.append(buffer);
2409
2410 /*
2411 * VSYNC state
2412 */
2413 mEventThread->dump(result, buffer, SIZE);
2414
2415 /*
2416 * Dump HWComposer state
2417 */
2418 snprintf(buffer, SIZE, "h/w composer state:\n");
2419 result.append(buffer);
2420 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
2421 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2422 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2423 result.append(buffer);
2424 hwc.dump(result, buffer, SIZE);
2425
2426 /*
2427 * Dump gralloc state
2428 */
2429 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2430 alloc.dump(result);
2431 }
2432
2433 const Vector< sp<LayerBase> >&
getLayerSortedByZForHwcDisplay(int disp)2434 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int disp) {
2435 // Note: mStateLock is held here
2436 return getDisplayDevice( getBuiltInDisplay(disp) )->getVisibleLayersSortedByZ();
2437 }
2438
startDdmConnection()2439 bool SurfaceFlinger::startDdmConnection()
2440 {
2441 void* libddmconnection_dso =
2442 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2443 if (!libddmconnection_dso) {
2444 return false;
2445 }
2446 void (*DdmConnection_start)(const char* name);
2447 DdmConnection_start =
2448 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2449 if (!DdmConnection_start) {
2450 dlclose(libddmconnection_dso);
2451 return false;
2452 }
2453 (*DdmConnection_start)(getServiceName());
2454 return true;
2455 }
2456
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2457 status_t SurfaceFlinger::onTransact(
2458 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2459 {
2460 switch (code) {
2461 case CREATE_CONNECTION:
2462 case SET_TRANSACTION_STATE:
2463 case BOOT_FINISHED:
2464 case BLANK:
2465 case UNBLANK:
2466 {
2467 // codes that require permission check
2468 IPCThreadState* ipc = IPCThreadState::self();
2469 const int pid = ipc->getCallingPid();
2470 const int uid = ipc->getCallingUid();
2471 if ((uid != AID_GRAPHICS) &&
2472 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2473 ALOGE("Permission Denial: "
2474 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2475 return PERMISSION_DENIED;
2476 }
2477 break;
2478 }
2479 case CAPTURE_SCREEN:
2480 {
2481 // codes that require permission check
2482 IPCThreadState* ipc = IPCThreadState::self();
2483 const int pid = ipc->getCallingPid();
2484 const int uid = ipc->getCallingUid();
2485 if ((uid != AID_GRAPHICS) &&
2486 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2487 ALOGE("Permission Denial: "
2488 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2489 return PERMISSION_DENIED;
2490 }
2491 break;
2492 }
2493 }
2494
2495 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2496 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2497 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2498 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2499 IPCThreadState* ipc = IPCThreadState::self();
2500 const int pid = ipc->getCallingPid();
2501 const int uid = ipc->getCallingUid();
2502 ALOGE("Permission Denial: "
2503 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2504 return PERMISSION_DENIED;
2505 }
2506 int n;
2507 switch (code) {
2508 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2509 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2510 return NO_ERROR;
2511 case 1002: // SHOW_UPDATES
2512 n = data.readInt32();
2513 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2514 invalidateHwcGeometry();
2515 repaintEverything();
2516 return NO_ERROR;
2517 case 1004:{ // repaint everything
2518 repaintEverything();
2519 return NO_ERROR;
2520 }
2521 case 1005:{ // force transaction
2522 setTransactionFlags(
2523 eTransactionNeeded|
2524 eDisplayTransactionNeeded|
2525 eTraversalNeeded);
2526 return NO_ERROR;
2527 }
2528 case 1006:{ // send empty update
2529 signalRefresh();
2530 return NO_ERROR;
2531 }
2532 case 1008: // toggle use of hw composer
2533 n = data.readInt32();
2534 mDebugDisableHWC = n ? 1 : 0;
2535 invalidateHwcGeometry();
2536 repaintEverything();
2537 return NO_ERROR;
2538 case 1009: // toggle use of transform hint
2539 n = data.readInt32();
2540 mDebugDisableTransformHint = n ? 1 : 0;
2541 invalidateHwcGeometry();
2542 repaintEverything();
2543 return NO_ERROR;
2544 case 1010: // interrogate.
2545 reply->writeInt32(0);
2546 reply->writeInt32(0);
2547 reply->writeInt32(mDebugRegion);
2548 reply->writeInt32(0);
2549 reply->writeInt32(mDebugDisableHWC);
2550 return NO_ERROR;
2551 case 1013: {
2552 Mutex::Autolock _l(mStateLock);
2553 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2554 reply->writeInt32(hw->getPageFlipCount());
2555 }
2556 return NO_ERROR;
2557 }
2558 }
2559 return err;
2560 }
2561
repaintEverything()2562 void SurfaceFlinger::repaintEverything() {
2563 android_atomic_or(1, &mRepaintEverything);
2564 signalTransaction();
2565 }
2566
2567 // ---------------------------------------------------------------------------
2568
renderScreenToTexture(uint32_t layerStack,GLuint * textureName,GLfloat * uOut,GLfloat * vOut)2569 status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2570 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2571 {
2572 Mutex::Autolock _l(mStateLock);
2573 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2574 }
2575
renderScreenToTextureLocked(uint32_t layerStack,GLuint * textureName,GLfloat * uOut,GLfloat * vOut)2576 status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2577 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2578 {
2579 ATRACE_CALL();
2580
2581 if (!GLExtensions::getInstance().haveFramebufferObject())
2582 return INVALID_OPERATION;
2583
2584 // get screen geometry
2585 // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2586 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2587 const uint32_t hw_w = hw->getWidth();
2588 const uint32_t hw_h = hw->getHeight();
2589 GLfloat u = 1;
2590 GLfloat v = 1;
2591
2592 // make sure to clear all GL error flags
2593 while ( glGetError() != GL_NO_ERROR ) ;
2594
2595 // create a FBO
2596 GLuint name, tname;
2597 glGenTextures(1, &tname);
2598 glBindTexture(GL_TEXTURE_2D, tname);
2599 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2600 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2601 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2602 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2603 if (glGetError() != GL_NO_ERROR) {
2604 while ( glGetError() != GL_NO_ERROR ) ;
2605 GLint tw = (2 << (31 - clz(hw_w)));
2606 GLint th = (2 << (31 - clz(hw_h)));
2607 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2608 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2609 u = GLfloat(hw_w) / tw;
2610 v = GLfloat(hw_h) / th;
2611 }
2612 glGenFramebuffersOES(1, &name);
2613 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2614 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2615 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2616
2617 DisplayDevice::setViewportAndProjection(hw);
2618
2619 // redraw the screen entirely...
2620 glDisable(GL_TEXTURE_EXTERNAL_OES);
2621 glDisable(GL_TEXTURE_2D);
2622 glClearColor(0,0,0,1);
2623 glClear(GL_COLOR_BUFFER_BIT);
2624 glMatrixMode(GL_MODELVIEW);
2625 glLoadIdentity();
2626 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2627 const size_t count = layers.size();
2628 for (size_t i=0 ; i<count ; ++i) {
2629 const sp<LayerBase>& layer(layers[i]);
2630 layer->draw(hw);
2631 }
2632
2633 hw->compositionComplete();
2634
2635 // back to main framebuffer
2636 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2637 glDeleteFramebuffersOES(1, &name);
2638
2639 *textureName = tname;
2640 *uOut = u;
2641 *vOut = v;
2642 return NO_ERROR;
2643 }
2644
2645 // ---------------------------------------------------------------------------
2646
captureScreenImplLocked(const sp<IBinder> & display,sp<IMemoryHeap> * heap,uint32_t * w,uint32_t * h,PixelFormat * f,uint32_t sw,uint32_t sh,uint32_t minLayerZ,uint32_t maxLayerZ)2647 status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2648 sp<IMemoryHeap>* heap,
2649 uint32_t* w, uint32_t* h, PixelFormat* f,
2650 uint32_t sw, uint32_t sh,
2651 uint32_t minLayerZ, uint32_t maxLayerZ)
2652 {
2653 ATRACE_CALL();
2654
2655 status_t result = PERMISSION_DENIED;
2656
2657 if (!GLExtensions::getInstance().haveFramebufferObject()) {
2658 return INVALID_OPERATION;
2659 }
2660
2661 // get screen geometry
2662 sp<const DisplayDevice> hw(getDisplayDevice(display));
2663 const uint32_t hw_w = hw->getWidth();
2664 const uint32_t hw_h = hw->getHeight();
2665
2666 // if we have secure windows on this display, never allow the screen capture
2667 if (hw->getSecureLayerVisible()) {
2668 ALOGW("FB is protected: PERMISSION_DENIED");
2669 return PERMISSION_DENIED;
2670 }
2671
2672 if ((sw > hw_w) || (sh > hw_h)) {
2673 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2674 return BAD_VALUE;
2675 }
2676
2677 sw = (!sw) ? hw_w : sw;
2678 sh = (!sh) ? hw_h : sh;
2679 const size_t size = sw * sh * 4;
2680 const bool filtering = sw != hw_w || sh != hw_h;
2681
2682 // ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2683 // sw, sh, minLayerZ, maxLayerZ);
2684
2685 // make sure to clear all GL error flags
2686 while ( glGetError() != GL_NO_ERROR ) ;
2687
2688 // create a FBO
2689 GLuint name, tname;
2690 glGenRenderbuffersOES(1, &tname);
2691 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2692 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2693
2694 glGenFramebuffersOES(1, &name);
2695 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2696 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2697 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2698
2699 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2700
2701 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2702
2703 // invert everything, b/c glReadPixel() below will invert the FB
2704 GLint viewport[4];
2705 glGetIntegerv(GL_VIEWPORT, viewport);
2706 glViewport(0, 0, sw, sh);
2707 glMatrixMode(GL_PROJECTION);
2708 glPushMatrix();
2709 glLoadIdentity();
2710 glOrthof(0, hw_w, hw_h, 0, 0, 1);
2711 glMatrixMode(GL_MODELVIEW);
2712
2713 // redraw the screen entirely...
2714 glClearColor(0,0,0,1);
2715 glClear(GL_COLOR_BUFFER_BIT);
2716
2717 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2718 const size_t count = layers.size();
2719 for (size_t i=0 ; i<count ; ++i) {
2720 const sp<LayerBase>& layer(layers[i]);
2721 const uint32_t z = layer->drawingState().z;
2722 if (z >= minLayerZ && z <= maxLayerZ) {
2723 if (filtering) layer->setFiltering(true);
2724 layer->draw(hw);
2725 if (filtering) layer->setFiltering(false);
2726 }
2727 }
2728
2729 // check for errors and return screen capture
2730 if (glGetError() != GL_NO_ERROR) {
2731 // error while rendering
2732 result = INVALID_OPERATION;
2733 } else {
2734 // allocate shared memory large enough to hold the
2735 // screen capture
2736 sp<MemoryHeapBase> base(
2737 new MemoryHeapBase(size, 0, "screen-capture") );
2738 void* const ptr = base->getBase();
2739 if (ptr != MAP_FAILED) {
2740 // capture the screen with glReadPixels()
2741 ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2742 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2743 if (glGetError() == GL_NO_ERROR) {
2744 *heap = base;
2745 *w = sw;
2746 *h = sh;
2747 *f = PIXEL_FORMAT_RGBA_8888;
2748 result = NO_ERROR;
2749 }
2750 } else {
2751 result = NO_MEMORY;
2752 }
2753 }
2754 glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
2755 glMatrixMode(GL_PROJECTION);
2756 glPopMatrix();
2757 glMatrixMode(GL_MODELVIEW);
2758 } else {
2759 result = BAD_VALUE;
2760 }
2761
2762 // release FBO resources
2763 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2764 glDeleteRenderbuffersOES(1, &tname);
2765 glDeleteFramebuffersOES(1, &name);
2766
2767 hw->compositionComplete();
2768
2769 // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2770
2771 return result;
2772 }
2773
2774
captureScreen(const sp<IBinder> & display,sp<IMemoryHeap> * heap,uint32_t * width,uint32_t * height,PixelFormat * format,uint32_t sw,uint32_t sh,uint32_t minLayerZ,uint32_t maxLayerZ)2775 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2776 sp<IMemoryHeap>* heap,
2777 uint32_t* width, uint32_t* height, PixelFormat* format,
2778 uint32_t sw, uint32_t sh,
2779 uint32_t minLayerZ, uint32_t maxLayerZ)
2780 {
2781 if (CC_UNLIKELY(display == 0))
2782 return BAD_VALUE;
2783
2784 if (!GLExtensions::getInstance().haveFramebufferObject())
2785 return INVALID_OPERATION;
2786
2787 class MessageCaptureScreen : public MessageBase {
2788 SurfaceFlinger* flinger;
2789 sp<IBinder> display;
2790 sp<IMemoryHeap>* heap;
2791 uint32_t* w;
2792 uint32_t* h;
2793 PixelFormat* f;
2794 uint32_t sw;
2795 uint32_t sh;
2796 uint32_t minLayerZ;
2797 uint32_t maxLayerZ;
2798 status_t result;
2799 public:
2800 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2801 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2802 uint32_t sw, uint32_t sh,
2803 uint32_t minLayerZ, uint32_t maxLayerZ)
2804 : flinger(flinger), display(display),
2805 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2806 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2807 result(PERMISSION_DENIED)
2808 {
2809 }
2810 status_t getResult() const {
2811 return result;
2812 }
2813 virtual bool handler() {
2814 Mutex::Autolock _l(flinger->mStateLock);
2815 result = flinger->captureScreenImplLocked(display,
2816 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2817 return true;
2818 }
2819 };
2820
2821 sp<MessageBase> msg = new MessageCaptureScreen(this,
2822 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2823 status_t res = postMessageSync(msg);
2824 if (res == NO_ERROR) {
2825 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2826 }
2827 return res;
2828 }
2829
2830 // ---------------------------------------------------------------------------
2831
LayerVector()2832 SurfaceFlinger::LayerVector::LayerVector() {
2833 }
2834
LayerVector(const LayerVector & rhs)2835 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2836 : SortedVector<sp<LayerBase> >(rhs) {
2837 }
2838
do_compare(const void * lhs,const void * rhs) const2839 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2840 const void* rhs) const
2841 {
2842 // sort layers per layer-stack, then by z-order and finally by sequence
2843 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2844 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2845
2846 uint32_t ls = l->currentState().layerStack;
2847 uint32_t rs = r->currentState().layerStack;
2848 if (ls != rs)
2849 return ls - rs;
2850
2851 uint32_t lz = l->currentState().z;
2852 uint32_t rz = r->currentState().z;
2853 if (lz != rz)
2854 return lz - rz;
2855
2856 return l->sequence - r->sequence;
2857 }
2858
2859 // ---------------------------------------------------------------------------
2860
DisplayDeviceState()2861 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2862 : type(DisplayDevice::DISPLAY_ID_INVALID) {
2863 }
2864
DisplayDeviceState(DisplayDevice::DisplayType type)2865 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2866 : type(type), layerStack(0), orientation(0) {
2867 viewport.makeInvalid();
2868 frame.makeInvalid();
2869 }
2870
2871 // ---------------------------------------------------------------------------
2872
2873 }; // namespace android
2874