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 <stdlib.h>
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <math.h>
26 #include <limits.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/ioctl.h>
30
31 #include <cutils/log.h>
32 #include <cutils/properties.h>
33
34 #include <binder/IPCThreadState.h>
35 #include <binder/IServiceManager.h>
36 #include <binder/MemoryHeapBase.h>
37 #include <binder/PermissionCache.h>
38
39 #include <gui/IDisplayEventConnection.h>
40
41 #include <utils/String8.h>
42 #include <utils/String16.h>
43 #include <utils/StopWatch.h>
44 #include <utils/Trace.h>
45
46 #include <ui/GraphicBufferAllocator.h>
47 #include <ui/PixelFormat.h>
48
49 #include <GLES/gl.h>
50
51 #include "clz.h"
52 #include "DdmConnection.h"
53 #include "EventThread.h"
54 #include "GLExtensions.h"
55 #include "Layer.h"
56 #include "LayerDim.h"
57 #include "LayerScreenshot.h"
58 #include "SurfaceFlinger.h"
59
60 #include "DisplayHardware/DisplayHardware.h"
61 #include "DisplayHardware/HWComposer.h"
62
63 #include <private/android_filesystem_config.h>
64 #include <private/gui/SharedBufferStack.h>
65 #include <gui/BitTube.h>
66
67 #define EGL_VERSION_HW_ANDROID 0x3143
68
69 #define DISPLAY_COUNT 1
70
71 namespace android {
72 // ---------------------------------------------------------------------------
73
74 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
75 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
76 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
77 const String16 sDump("android.permission.DUMP");
78
79 // ---------------------------------------------------------------------------
80
SurfaceFlinger()81 SurfaceFlinger::SurfaceFlinger()
82 : BnSurfaceComposer(), Thread(false),
83 mTransactionFlags(0),
84 mTransationPending(false),
85 mLayersRemoved(false),
86 mBootTime(systemTime()),
87 mVisibleRegionsDirty(false),
88 mHwWorkListDirty(false),
89 mElectronBeamAnimationMode(0),
90 mDebugRegion(0),
91 mDebugDDMS(0),
92 mDebugDisableHWC(0),
93 mDebugDisableTransformHint(0),
94 mDebugInSwapBuffers(0),
95 mLastSwapBufferTime(0),
96 mDebugInTransaction(0),
97 mLastTransactionTime(0),
98 mBootFinished(false),
99 mSecureFrameBuffer(0)
100 {
101 init();
102 }
103
init()104 void SurfaceFlinger::init()
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 #ifdef DDMS_DEBUGGING
115 property_get("debug.sf.ddms", value, "0");
116 mDebugDDMS = atoi(value);
117 if (mDebugDDMS) {
118 DdmConnection::start(getServiceName());
119 }
120 #endif
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 glDeleteTextures(1, &mWormholeTexName);
140 }
141
binderDied(const wp<IBinder> & who)142 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
143 {
144 // the window manager died on us. prepare its eulogy.
145
146 // reset screen orientation
147 Vector<ComposerState> state;
148 setTransactionState(state, eOrientationDefault, 0);
149
150 // restart the boot-animation
151 startBootAnim();
152 }
153
getCblk() const154 sp<IMemoryHeap> SurfaceFlinger::getCblk() const
155 {
156 return mServerHeap;
157 }
158
createConnection()159 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
160 {
161 sp<ISurfaceComposerClient> bclient;
162 sp<Client> client(new Client(this));
163 status_t err = client->initCheck();
164 if (err == NO_ERROR) {
165 bclient = client;
166 }
167 return bclient;
168 }
169
createGraphicBufferAlloc()170 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
171 {
172 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
173 return gba;
174 }
175
graphicPlane(int dpy) const176 const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
177 {
178 ALOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
179 const GraphicPlane& plane(mGraphicPlanes[dpy]);
180 return plane;
181 }
182
graphicPlane(int dpy)183 GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
184 {
185 return const_cast<GraphicPlane&>(
186 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
187 }
188
bootFinished()189 void SurfaceFlinger::bootFinished()
190 {
191 const nsecs_t now = systemTime();
192 const nsecs_t duration = now - mBootTime;
193 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
194 mBootFinished = true;
195
196 // wait patiently for the window manager death
197 const String16 name("window");
198 sp<IBinder> window(defaultServiceManager()->getService(name));
199 if (window != 0) {
200 window->linkToDeath(this);
201 }
202
203 // stop boot animation
204 // formerly we would just kill the process, but we now ask it to exit so it
205 // can choose where to stop the animation.
206 property_set("service.bootanim.exit", "1");
207 }
208
pack565(int r,int g,int b)209 static inline uint16_t pack565(int r, int g, int b) {
210 return (r<<11)|(g<<5)|b;
211 }
212
readyToRun()213 status_t SurfaceFlinger::readyToRun()
214 {
215 ALOGI( "SurfaceFlinger's main thread ready to run. "
216 "Initializing graphics H/W...");
217
218 // we only support one display currently
219 int dpy = 0;
220
221 {
222 // initialize the main display
223 GraphicPlane& plane(graphicPlane(dpy));
224 DisplayHardware* const hw = new DisplayHardware(this, dpy);
225 plane.setDisplayHardware(hw);
226 }
227
228 // create the shared control-block
229 mServerHeap = new MemoryHeapBase(4096,
230 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
231 ALOGE_IF(mServerHeap==0, "can't create shared memory dealer");
232
233 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
234 ALOGE_IF(mServerCblk==0, "can't get to shared control block's address");
235
236 new(mServerCblk) surface_flinger_cblk_t;
237
238 // initialize primary screen
239 // (other display should be initialized in the same manner, but
240 // asynchronously, as they could come and go. None of this is supported
241 // yet).
242 const GraphicPlane& plane(graphicPlane(dpy));
243 const DisplayHardware& hw = plane.displayHardware();
244 const uint32_t w = hw.getWidth();
245 const uint32_t h = hw.getHeight();
246 const uint32_t f = hw.getFormat();
247 hw.makeCurrent();
248
249 // initialize the shared control block
250 mServerCblk->connected |= 1<<dpy;
251 display_cblk_t* dcblk = mServerCblk->displays + dpy;
252 memset(dcblk, 0, sizeof(display_cblk_t));
253 dcblk->w = plane.getWidth();
254 dcblk->h = plane.getHeight();
255 dcblk->format = f;
256 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
257 dcblk->xdpi = hw.getDpiX();
258 dcblk->ydpi = hw.getDpiY();
259 dcblk->fps = hw.getRefreshRate();
260 dcblk->density = hw.getDensity();
261
262 // Initialize OpenGL|ES
263 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
264 glPixelStorei(GL_PACK_ALIGNMENT, 4);
265 glEnableClientState(GL_VERTEX_ARRAY);
266 glShadeModel(GL_FLAT);
267 glDisable(GL_DITHER);
268 glDisable(GL_CULL_FACE);
269
270 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
271 const uint16_t g1 = pack565(0x17,0x2f,0x17);
272 const uint16_t wormholeTexData[4] = { g0, g1, g1, g0 };
273 glGenTextures(1, &mWormholeTexName);
274 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
275 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
276 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
277 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
278 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
279 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
280 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, wormholeTexData);
281
282 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
283 glGenTextures(1, &mProtectedTexName);
284 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
285 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
286 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
287 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
288 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
289 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
290 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
291
292 glViewport(0, 0, w, h);
293 glMatrixMode(GL_PROJECTION);
294 glLoadIdentity();
295 // put the origin in the left-bottom corner
296 glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
297
298
299 // start the EventThread
300 mEventThread = new EventThread(this);
301 mEventQueue.setEventThread(mEventThread);
302 hw.startSleepManagement();
303
304 /*
305 * We're now ready to accept clients...
306 */
307
308 mReadyToRunBarrier.open();
309
310 // start boot animation
311 startBootAnim();
312
313 return NO_ERROR;
314 }
315
startBootAnim()316 void SurfaceFlinger::startBootAnim() {
317 // start boot animation
318 property_set("service.bootanim.exit", "0");
319 property_set("ctl.start", "bootanim");
320 }
321
322 // ----------------------------------------------------------------------------
323
authenticateSurfaceTexture(const sp<ISurfaceTexture> & surfaceTexture) const324 bool SurfaceFlinger::authenticateSurfaceTexture(
325 const sp<ISurfaceTexture>& surfaceTexture) const {
326 Mutex::Autolock _l(mStateLock);
327 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
328
329 // Check the visible layer list for the ISurface
330 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
331 size_t count = currentLayers.size();
332 for (size_t i=0 ; i<count ; i++) {
333 const sp<LayerBase>& layer(currentLayers[i]);
334 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
335 if (lbc != NULL) {
336 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
337 if (lbcBinder == surfaceTextureBinder) {
338 return true;
339 }
340 }
341 }
342
343 // Check the layers in the purgatory. This check is here so that if a
344 // SurfaceTexture gets destroyed before all the clients are done using it,
345 // the error will not be reported as "surface XYZ is not authenticated", but
346 // will instead fail later on when the client tries to use the surface,
347 // which should be reported as "surface XYZ returned an -ENODEV". The
348 // purgatorized layers are no less authentic than the visible ones, so this
349 // should not cause any harm.
350 size_t purgatorySize = mLayerPurgatory.size();
351 for (size_t i=0 ; i<purgatorySize ; i++) {
352 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
353 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
354 if (lbc != NULL) {
355 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
356 if (lbcBinder == surfaceTextureBinder) {
357 return true;
358 }
359 }
360 }
361
362 return false;
363 }
364
365 // ----------------------------------------------------------------------------
366
createDisplayEventConnection()367 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
368 return mEventThread->createEventConnection();
369 }
370
371 // ----------------------------------------------------------------------------
372
waitForEvent()373 void SurfaceFlinger::waitForEvent() {
374 mEventQueue.waitMessage();
375 }
376
signalTransaction()377 void SurfaceFlinger::signalTransaction() {
378 mEventQueue.invalidate();
379 }
380
signalLayerUpdate()381 void SurfaceFlinger::signalLayerUpdate() {
382 mEventQueue.invalidate();
383 }
384
signalRefresh()385 void SurfaceFlinger::signalRefresh() {
386 mEventQueue.refresh();
387 }
388
postMessageAsync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t flags)389 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
390 nsecs_t reltime, uint32_t flags) {
391 return mEventQueue.postMessage(msg, reltime);
392 }
393
postMessageSync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t flags)394 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
395 nsecs_t reltime, uint32_t flags) {
396 status_t res = mEventQueue.postMessage(msg, reltime);
397 if (res == NO_ERROR) {
398 msg->wait();
399 }
400 return res;
401 }
402
threadLoop()403 bool SurfaceFlinger::threadLoop()
404 {
405 waitForEvent();
406 return true;
407 }
408
onMessageReceived(int32_t what)409 void SurfaceFlinger::onMessageReceived(int32_t what)
410 {
411 ATRACE_CALL();
412 switch (what) {
413 case MessageQueue::REFRESH: {
414 // case MessageQueue::INVALIDATE: {
415 // if we're in a global transaction, don't do anything.
416 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
417 uint32_t transactionFlags = peekTransactionFlags(mask);
418 if (CC_UNLIKELY(transactionFlags)) {
419 handleTransaction(transactionFlags);
420 }
421
422 // post surfaces (if needed)
423 handlePageFlip();
424
425 // signalRefresh();
426 //
427 // } break;
428 //
429 // case MessageQueue::REFRESH: {
430
431 handleRefresh();
432
433 const DisplayHardware& hw(graphicPlane(0).displayHardware());
434
435 // if (mDirtyRegion.isEmpty()) {
436 // return;
437 // }
438
439 if (CC_UNLIKELY(mHwWorkListDirty)) {
440 // build the h/w work list
441 handleWorkList();
442 }
443
444 if (CC_LIKELY(hw.canDraw())) {
445 // repaint the framebuffer (if needed)
446 handleRepaint();
447 // inform the h/w that we're done compositing
448 hw.compositionComplete();
449 postFramebuffer();
450 } else {
451 // pretend we did the post
452 hw.compositionComplete();
453 }
454
455 } break;
456 }
457 }
458
postFramebuffer()459 void SurfaceFlinger::postFramebuffer()
460 {
461 ATRACE_CALL();
462 // mSwapRegion can be empty here is some cases, for instance if a hidden
463 // or fully transparent window is updating.
464 // in that case, we need to flip anyways to not risk a deadlock with
465 // h/w composer.
466
467 const DisplayHardware& hw(graphicPlane(0).displayHardware());
468 const nsecs_t now = systemTime();
469 mDebugInSwapBuffers = now;
470 hw.flip(mSwapRegion);
471
472 size_t numLayers = mVisibleLayersSortedByZ.size();
473 for (size_t i = 0; i < numLayers; i++) {
474 mVisibleLayersSortedByZ[i]->onLayerDisplayed();
475 }
476
477 mLastSwapBufferTime = systemTime() - now;
478 mDebugInSwapBuffers = 0;
479 mSwapRegion.clear();
480 }
481
handleTransaction(uint32_t transactionFlags)482 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
483 {
484 ATRACE_CALL();
485
486 Mutex::Autolock _l(mStateLock);
487 const nsecs_t now = systemTime();
488 mDebugInTransaction = now;
489
490 // Here we're guaranteed that some transaction flags are set
491 // so we can call handleTransactionLocked() unconditionally.
492 // We call getTransactionFlags(), which will also clear the flags,
493 // with mStateLock held to guarantee that mCurrentState won't change
494 // until the transaction is committed.
495
496 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
497 transactionFlags = getTransactionFlags(mask);
498 handleTransactionLocked(transactionFlags);
499
500 mLastTransactionTime = systemTime() - now;
501 mDebugInTransaction = 0;
502 invalidateHwcGeometry();
503 // here the transaction has been committed
504 }
505
handleTransactionLocked(uint32_t transactionFlags)506 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
507 {
508 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
509 const size_t count = currentLayers.size();
510
511 /*
512 * Traversal of the children
513 * (perform the transaction for each of them if needed)
514 */
515
516 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
517 if (layersNeedTransaction) {
518 for (size_t i=0 ; i<count ; i++) {
519 const sp<LayerBase>& layer = currentLayers[i];
520 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
521 if (!trFlags) continue;
522
523 const uint32_t flags = layer->doTransaction(0);
524 if (flags & Layer::eVisibleRegion)
525 mVisibleRegionsDirty = true;
526 }
527 }
528
529 /*
530 * Perform our own transaction if needed
531 */
532
533 if (transactionFlags & eTransactionNeeded) {
534 if (mCurrentState.orientation != mDrawingState.orientation) {
535 // the orientation has changed, recompute all visible regions
536 // and invalidate everything.
537
538 const int dpy = 0;
539 const int orientation = mCurrentState.orientation;
540 // Currently unused: const uint32_t flags = mCurrentState.orientationFlags;
541 GraphicPlane& plane(graphicPlane(dpy));
542 plane.setOrientation(orientation);
543
544 // update the shared control block
545 const DisplayHardware& hw(plane.displayHardware());
546 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
547 dcblk->orientation = orientation;
548 dcblk->w = plane.getWidth();
549 dcblk->h = plane.getHeight();
550
551 mVisibleRegionsDirty = true;
552 mDirtyRegion.set(hw.bounds());
553 }
554
555 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
556 // layers have been added
557 mVisibleRegionsDirty = true;
558 }
559
560 // some layers might have been removed, so
561 // we need to update the regions they're exposing.
562 if (mLayersRemoved) {
563 mLayersRemoved = false;
564 mVisibleRegionsDirty = true;
565 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
566 const size_t count = previousLayers.size();
567 for (size_t i=0 ; i<count ; i++) {
568 const sp<LayerBase>& layer(previousLayers[i]);
569 if (currentLayers.indexOf( layer ) < 0) {
570 // this layer is not visible anymore
571 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
572 }
573 }
574 }
575 }
576
577 commitTransaction();
578 }
579
computeVisibleRegions(const LayerVector & currentLayers,Region & dirtyRegion,Region & opaqueRegion)580 void SurfaceFlinger::computeVisibleRegions(
581 const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
582 {
583 ATRACE_CALL();
584
585 const GraphicPlane& plane(graphicPlane(0));
586 const Transform& planeTransform(plane.transform());
587 const DisplayHardware& hw(plane.displayHardware());
588 const Region screenRegion(hw.bounds());
589
590 Region aboveOpaqueLayers;
591 Region aboveCoveredLayers;
592 Region dirty;
593
594 bool secureFrameBuffer = false;
595
596 size_t i = currentLayers.size();
597 while (i--) {
598 const sp<LayerBase>& layer = currentLayers[i];
599 layer->validateVisibility(planeTransform);
600
601 // start with the whole surface at its current location
602 const Layer::State& s(layer->drawingState());
603
604 /*
605 * opaqueRegion: area of a surface that is fully opaque.
606 */
607 Region opaqueRegion;
608
609 /*
610 * visibleRegion: area of a surface that is visible on screen
611 * and not fully transparent. This is essentially the layer's
612 * footprint minus the opaque regions above it.
613 * Areas covered by a translucent surface are considered visible.
614 */
615 Region visibleRegion;
616
617 /*
618 * coveredRegion: area of a surface that is covered by all
619 * visible regions above it (which includes the translucent areas).
620 */
621 Region coveredRegion;
622
623
624 // handle hidden surfaces by setting the visible region to empty
625 if (CC_LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
626 const bool translucent = !layer->isOpaque();
627 const Rect bounds(layer->visibleBounds());
628 visibleRegion.set(bounds);
629 visibleRegion.andSelf(screenRegion);
630 if (!visibleRegion.isEmpty()) {
631 // Remove the transparent area from the visible region
632 if (translucent) {
633 visibleRegion.subtractSelf(layer->transparentRegionScreen);
634 }
635
636 // compute the opaque region
637 const int32_t layerOrientation = layer->getOrientation();
638 if (s.alpha==255 && !translucent &&
639 ((layerOrientation & Transform::ROT_INVALID) == false)) {
640 // the opaque region is the layer's footprint
641 opaqueRegion = visibleRegion;
642 }
643 }
644 }
645
646 // Clip the covered region to the visible region
647 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
648
649 // Update aboveCoveredLayers for next (lower) layer
650 aboveCoveredLayers.orSelf(visibleRegion);
651
652 // subtract the opaque region covered by the layers above us
653 visibleRegion.subtractSelf(aboveOpaqueLayers);
654
655 // compute this layer's dirty region
656 if (layer->contentDirty) {
657 // we need to invalidate the whole region
658 dirty = visibleRegion;
659 // as well, as the old visible region
660 dirty.orSelf(layer->visibleRegionScreen);
661 layer->contentDirty = false;
662 } else {
663 /* compute the exposed region:
664 * the exposed region consists of two components:
665 * 1) what's VISIBLE now and was COVERED before
666 * 2) what's EXPOSED now less what was EXPOSED before
667 *
668 * note that (1) is conservative, we start with the whole
669 * visible region but only keep what used to be covered by
670 * something -- which mean it may have been exposed.
671 *
672 * (2) handles areas that were not covered by anything but got
673 * exposed because of a resize.
674 */
675 const Region newExposed = visibleRegion - coveredRegion;
676 const Region oldVisibleRegion = layer->visibleRegionScreen;
677 const Region oldCoveredRegion = layer->coveredRegionScreen;
678 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
679 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
680 }
681 dirty.subtractSelf(aboveOpaqueLayers);
682
683 // accumulate to the screen dirty region
684 dirtyRegion.orSelf(dirty);
685
686 // Update aboveOpaqueLayers for next (lower) layer
687 aboveOpaqueLayers.orSelf(opaqueRegion);
688
689 // Store the visible region is screen space
690 layer->setVisibleRegion(visibleRegion);
691 layer->setCoveredRegion(coveredRegion);
692
693 // If a secure layer is partially visible, lock-down the screen!
694 if (layer->isSecure() && !visibleRegion.isEmpty()) {
695 secureFrameBuffer = true;
696 }
697 }
698
699 // invalidate the areas where a layer was removed
700 dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
701 mDirtyRegionRemovedLayer.clear();
702
703 mSecureFrameBuffer = secureFrameBuffer;
704 opaqueRegion = aboveOpaqueLayers;
705 }
706
707
commitTransaction()708 void SurfaceFlinger::commitTransaction()
709 {
710 if (!mLayersPendingRemoval.isEmpty()) {
711 // Notify removed layers now that they can't be drawn from
712 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
713 mLayersPendingRemoval[i]->onRemoved();
714 }
715 mLayersPendingRemoval.clear();
716 }
717
718 mDrawingState = mCurrentState;
719 mTransationPending = false;
720 mTransactionCV.broadcast();
721 }
722
handlePageFlip()723 void SurfaceFlinger::handlePageFlip()
724 {
725 ATRACE_CALL();
726 const DisplayHardware& hw = graphicPlane(0).displayHardware();
727 const Region screenRegion(hw.bounds());
728
729 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
730 const bool visibleRegions = lockPageFlip(currentLayers);
731
732 if (visibleRegions || mVisibleRegionsDirty) {
733 Region opaqueRegion;
734 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
735
736 /*
737 * rebuild the visible layer list
738 */
739 const size_t count = currentLayers.size();
740 mVisibleLayersSortedByZ.clear();
741 mVisibleLayersSortedByZ.setCapacity(count);
742 for (size_t i=0 ; i<count ; i++) {
743 if (!currentLayers[i]->visibleRegionScreen.isEmpty())
744 mVisibleLayersSortedByZ.add(currentLayers[i]);
745 }
746
747 mWormholeRegion = screenRegion.subtract(opaqueRegion);
748 mVisibleRegionsDirty = false;
749 invalidateHwcGeometry();
750 }
751
752 unlockPageFlip(currentLayers);
753
754 mDirtyRegion.orSelf(getAndClearInvalidateRegion());
755 mDirtyRegion.andSelf(screenRegion);
756 }
757
invalidateHwcGeometry()758 void SurfaceFlinger::invalidateHwcGeometry()
759 {
760 mHwWorkListDirty = true;
761 }
762
lockPageFlip(const LayerVector & currentLayers)763 bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
764 {
765 bool recomputeVisibleRegions = false;
766 size_t count = currentLayers.size();
767 sp<LayerBase> const* layers = currentLayers.array();
768 for (size_t i=0 ; i<count ; i++) {
769 const sp<LayerBase>& layer(layers[i]);
770 layer->lockPageFlip(recomputeVisibleRegions);
771 }
772 return recomputeVisibleRegions;
773 }
774
unlockPageFlip(const LayerVector & currentLayers)775 void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
776 {
777 const GraphicPlane& plane(graphicPlane(0));
778 const Transform& planeTransform(plane.transform());
779 const size_t count = currentLayers.size();
780 sp<LayerBase> const* layers = currentLayers.array();
781 for (size_t i=0 ; i<count ; i++) {
782 const sp<LayerBase>& layer(layers[i]);
783 layer->unlockPageFlip(planeTransform, mDirtyRegion);
784 }
785 }
786
handleRefresh()787 void SurfaceFlinger::handleRefresh()
788 {
789 bool needInvalidate = false;
790 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
791 const size_t count = currentLayers.size();
792 for (size_t i=0 ; i<count ; i++) {
793 const sp<LayerBase>& layer(currentLayers[i]);
794 if (layer->onPreComposition()) {
795 needInvalidate = true;
796 }
797 }
798 if (needInvalidate) {
799 signalLayerUpdate();
800 }
801 }
802
803
handleWorkList()804 void SurfaceFlinger::handleWorkList()
805 {
806 mHwWorkListDirty = false;
807 HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer());
808 if (hwc.initCheck() == NO_ERROR) {
809 const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ);
810 const size_t count = currentLayers.size();
811 hwc.createWorkList(count);
812 hwc_layer_t* const cur(hwc.getLayers());
813 for (size_t i=0 ; cur && i<count ; i++) {
814 currentLayers[i]->setGeometry(&cur[i]);
815 if (mDebugDisableHWC || mDebugRegion) {
816 cur[i].compositionType = HWC_FRAMEBUFFER;
817 cur[i].flags |= HWC_SKIP_LAYER;
818 }
819 }
820 }
821 }
822
handleRepaint()823 void SurfaceFlinger::handleRepaint()
824 {
825 ATRACE_CALL();
826
827 // compute the invalid region
828 mSwapRegion.orSelf(mDirtyRegion);
829
830 if (CC_UNLIKELY(mDebugRegion)) {
831 debugFlashRegions();
832 }
833
834 // set the frame buffer
835 const DisplayHardware& hw(graphicPlane(0).displayHardware());
836 glMatrixMode(GL_MODELVIEW);
837 glLoadIdentity();
838
839 uint32_t flags = hw.getFlags();
840 if (flags & DisplayHardware::SWAP_RECTANGLE) {
841 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
842 // takes a rectangle, we must make sure to update that whole
843 // rectangle in that case
844 mDirtyRegion.set(mSwapRegion.bounds());
845 } else {
846 if (flags & DisplayHardware::PARTIAL_UPDATES) {
847 // We need to redraw the rectangle that will be updated
848 // (pushed to the framebuffer).
849 // This is needed because PARTIAL_UPDATES only takes one
850 // rectangle instead of a region (see DisplayHardware::flip())
851 mDirtyRegion.set(mSwapRegion.bounds());
852 } else {
853 // we need to redraw everything (the whole screen)
854 mDirtyRegion.set(hw.bounds());
855 mSwapRegion = mDirtyRegion;
856 }
857 }
858
859 setupHardwareComposer();
860 composeSurfaces(mDirtyRegion);
861
862 // update the swap region and clear the dirty region
863 mSwapRegion.orSelf(mDirtyRegion);
864 mDirtyRegion.clear();
865 }
866
setupHardwareComposer()867 void SurfaceFlinger::setupHardwareComposer()
868 {
869 const DisplayHardware& hw(graphicPlane(0).displayHardware());
870 HWComposer& hwc(hw.getHwComposer());
871 hwc_layer_t* const cur(hwc.getLayers());
872 if (!cur) {
873 return;
874 }
875
876 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
877 size_t count = layers.size();
878
879 ALOGE_IF(hwc.getNumLayers() != count,
880 "HAL number of layers (%d) doesn't match surfaceflinger (%d)",
881 hwc.getNumLayers(), count);
882
883 // just to be extra-safe, use the smallest count
884 if (hwc.initCheck() == NO_ERROR) {
885 count = count < hwc.getNumLayers() ? count : hwc.getNumLayers();
886 }
887
888 /*
889 * update the per-frame h/w composer data for each layer
890 * and build the transparent region of the FB
891 */
892 for (size_t i=0 ; i<count ; i++) {
893 const sp<LayerBase>& layer(layers[i]);
894 layer->setPerFrameData(&cur[i]);
895 }
896 status_t err = hwc.prepare();
897 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
898 }
899
composeSurfaces(const Region & dirty)900 void SurfaceFlinger::composeSurfaces(const Region& dirty)
901 {
902 const DisplayHardware& hw(graphicPlane(0).displayHardware());
903 HWComposer& hwc(hw.getHwComposer());
904 hwc_layer_t* const cur(hwc.getLayers());
905
906 const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);
907 if (!cur || fbLayerCount) {
908 // Never touch the framebuffer if we don't have any framebuffer layers
909
910 if (hwc.getLayerCount(HWC_OVERLAY)) {
911 // when using overlays, we assume a fully transparent framebuffer
912 // NOTE: we could reduce how much we need to clear, for instance
913 // remove where there are opaque FB layers. however, on some
914 // GPUs doing a "clean slate" glClear might be more efficient.
915 // We'll revisit later if needed.
916 glClearColor(0, 0, 0, 0);
917 glClear(GL_COLOR_BUFFER_BIT);
918 } else {
919 // screen is already cleared here
920 if (!mWormholeRegion.isEmpty()) {
921 // can happen with SurfaceView
922 drawWormhole();
923 }
924 }
925
926 /*
927 * and then, render the layers targeted at the framebuffer
928 */
929
930 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
931 const size_t count = layers.size();
932
933 for (size_t i=0 ; i<count ; i++) {
934 const sp<LayerBase>& layer(layers[i]);
935 const Region clip(dirty.intersect(layer->visibleRegionScreen));
936 if (!clip.isEmpty()) {
937 if (cur && (cur[i].compositionType == HWC_OVERLAY)) {
938 if (i && (cur[i].hints & HWC_HINT_CLEAR_FB)
939 && layer->isOpaque()) {
940 // never clear the very first layer since we're
941 // guaranteed the FB is already cleared
942 layer->clearWithOpenGL(clip);
943 }
944 continue;
945 }
946 // render the layer
947 layer->draw(clip);
948 }
949 }
950 }
951 }
952
debugFlashRegions()953 void SurfaceFlinger::debugFlashRegions()
954 {
955 const DisplayHardware& hw(graphicPlane(0).displayHardware());
956 const uint32_t flags = hw.getFlags();
957 const int32_t height = hw.getHeight();
958 if (mSwapRegion.isEmpty()) {
959 return;
960 }
961
962 if (!(flags & DisplayHardware::SWAP_RECTANGLE)) {
963 const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
964 mDirtyRegion.bounds() : hw.bounds());
965 composeSurfaces(repaint);
966 }
967
968 glDisable(GL_TEXTURE_EXTERNAL_OES);
969 glDisable(GL_TEXTURE_2D);
970 glDisable(GL_BLEND);
971
972 static int toggle = 0;
973 toggle = 1 - toggle;
974 if (toggle) {
975 glColor4f(1, 0, 1, 1);
976 } else {
977 glColor4f(1, 1, 0, 1);
978 }
979
980 Region::const_iterator it = mDirtyRegion.begin();
981 Region::const_iterator const end = mDirtyRegion.end();
982 while (it != end) {
983 const Rect& r = *it++;
984 GLfloat vertices[][2] = {
985 { r.left, height - r.top },
986 { r.left, height - r.bottom },
987 { r.right, height - r.bottom },
988 { r.right, height - r.top }
989 };
990 glVertexPointer(2, GL_FLOAT, 0, vertices);
991 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
992 }
993
994 hw.flip(mSwapRegion);
995
996 if (mDebugRegion > 1)
997 usleep(mDebugRegion * 1000);
998 }
999
drawWormhole() const1000 void SurfaceFlinger::drawWormhole() const
1001 {
1002 const Region region(mWormholeRegion.intersect(mDirtyRegion));
1003 if (region.isEmpty())
1004 return;
1005
1006 glDisable(GL_TEXTURE_EXTERNAL_OES);
1007 glDisable(GL_TEXTURE_2D);
1008 glDisable(GL_BLEND);
1009 glColor4f(0,0,0,0);
1010
1011 GLfloat vertices[4][2];
1012 glVertexPointer(2, GL_FLOAT, 0, vertices);
1013 Region::const_iterator it = region.begin();
1014 Region::const_iterator const end = region.end();
1015 while (it != end) {
1016 const Rect& r = *it++;
1017 vertices[0][0] = r.left;
1018 vertices[0][1] = r.top;
1019 vertices[1][0] = r.right;
1020 vertices[1][1] = r.top;
1021 vertices[2][0] = r.right;
1022 vertices[2][1] = r.bottom;
1023 vertices[3][0] = r.left;
1024 vertices[3][1] = r.bottom;
1025 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1026 }
1027 }
1028
addLayer(const sp<LayerBase> & layer)1029 status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1030 {
1031 Mutex::Autolock _l(mStateLock);
1032 addLayer_l(layer);
1033 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1034 return NO_ERROR;
1035 }
1036
addLayer_l(const sp<LayerBase> & layer)1037 status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1038 {
1039 ssize_t i = mCurrentState.layersSortedByZ.add(layer);
1040 return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1041 }
1042
addClientLayer(const sp<Client> & client,const sp<LayerBaseClient> & lbc)1043 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1044 const sp<LayerBaseClient>& lbc)
1045 {
1046 // attach this layer to the client
1047 size_t name = client->attachLayer(lbc);
1048
1049 Mutex::Autolock _l(mStateLock);
1050
1051 // add this layer to the current state list
1052 addLayer_l(lbc);
1053
1054 return ssize_t(name);
1055 }
1056
removeLayer(const sp<LayerBase> & layer)1057 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1058 {
1059 Mutex::Autolock _l(mStateLock);
1060 status_t err = purgatorizeLayer_l(layer);
1061 if (err == NO_ERROR)
1062 setTransactionFlags(eTransactionNeeded);
1063 return err;
1064 }
1065
removeLayer_l(const sp<LayerBase> & layerBase)1066 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1067 {
1068 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1069 if (lbc != 0) {
1070 mLayerMap.removeItem( lbc->getSurfaceBinder() );
1071 }
1072 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1073 if (index >= 0) {
1074 mLayersRemoved = true;
1075 return NO_ERROR;
1076 }
1077 return status_t(index);
1078 }
1079
purgatorizeLayer_l(const sp<LayerBase> & layerBase)1080 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1081 {
1082 // First add the layer to the purgatory list, which makes sure it won't
1083 // go away, then remove it from the main list (through a transaction).
1084 ssize_t err = removeLayer_l(layerBase);
1085 if (err >= 0) {
1086 mLayerPurgatory.add(layerBase);
1087 }
1088
1089 mLayersPendingRemoval.push(layerBase);
1090
1091 // it's possible that we don't find a layer, because it might
1092 // have been destroyed already -- this is not technically an error
1093 // from the user because there is a race between Client::destroySurface(),
1094 // ~Client() and ~ISurface().
1095 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1096 }
1097
invalidateLayerVisibility(const sp<LayerBase> & layer)1098 status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1099 {
1100 layer->forceVisibilityTransaction();
1101 setTransactionFlags(eTraversalNeeded);
1102 return NO_ERROR;
1103 }
1104
peekTransactionFlags(uint32_t flags)1105 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1106 {
1107 return android_atomic_release_load(&mTransactionFlags);
1108 }
1109
getTransactionFlags(uint32_t flags)1110 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1111 {
1112 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1113 }
1114
setTransactionFlags(uint32_t flags)1115 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1116 {
1117 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1118 if ((old & flags)==0) { // wake the server up
1119 signalTransaction();
1120 }
1121 return old;
1122 }
1123
1124
setTransactionState(const Vector<ComposerState> & state,int orientation,uint32_t flags)1125 void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state,
1126 int orientation, uint32_t flags) {
1127 Mutex::Autolock _l(mStateLock);
1128
1129 uint32_t transactionFlags = 0;
1130 if (mCurrentState.orientation != orientation) {
1131 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1132 mCurrentState.orientation = orientation;
1133 transactionFlags |= eTransactionNeeded;
1134 } else if (orientation != eOrientationUnchanged) {
1135 ALOGW("setTransactionState: ignoring unrecognized orientation: %d",
1136 orientation);
1137 }
1138 }
1139
1140 const size_t count = state.size();
1141 for (size_t i=0 ; i<count ; i++) {
1142 const ComposerState& s(state[i]);
1143 sp<Client> client( static_cast<Client *>(s.client.get()) );
1144 transactionFlags |= setClientStateLocked(client, s.state);
1145 }
1146
1147 if (transactionFlags) {
1148 // this triggers the transaction
1149 setTransactionFlags(transactionFlags);
1150
1151 // if this is a synchronous transaction, wait for it to take effect
1152 // before returning.
1153 if (flags & eSynchronous) {
1154 mTransationPending = true;
1155 }
1156 while (mTransationPending) {
1157 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1158 if (CC_UNLIKELY(err != NO_ERROR)) {
1159 // just in case something goes wrong in SF, return to the
1160 // called after a few seconds.
1161 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1162 mTransationPending = false;
1163 break;
1164 }
1165 }
1166 }
1167 }
1168
createSurface(ISurfaceComposerClient::surface_data_t * params,const String8 & name,const sp<Client> & client,DisplayID d,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags)1169 sp<ISurface> SurfaceFlinger::createSurface(
1170 ISurfaceComposerClient::surface_data_t* params,
1171 const String8& name,
1172 const sp<Client>& client,
1173 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1174 uint32_t flags)
1175 {
1176 sp<LayerBaseClient> layer;
1177 sp<ISurface> surfaceHandle;
1178
1179 if (int32_t(w|h) < 0) {
1180 ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1181 int(w), int(h));
1182 return surfaceHandle;
1183 }
1184
1185 //ALOGD("createSurface for (%d x %d), name=%s", w, h, name.string());
1186 sp<Layer> normalLayer;
1187 switch (flags & eFXSurfaceMask) {
1188 case eFXSurfaceNormal:
1189 normalLayer = createNormalSurface(client, d, w, h, flags, format);
1190 layer = normalLayer;
1191 break;
1192 case eFXSurfaceBlur:
1193 // for now we treat Blur as Dim, until we can implement it
1194 // efficiently.
1195 case eFXSurfaceDim:
1196 layer = createDimSurface(client, d, w, h, flags);
1197 break;
1198 case eFXSurfaceScreenshot:
1199 layer = createScreenshotSurface(client, d, w, h, flags);
1200 break;
1201 }
1202
1203 if (layer != 0) {
1204 layer->initStates(w, h, flags);
1205 layer->setName(name);
1206 ssize_t token = addClientLayer(client, layer);
1207
1208 surfaceHandle = layer->getSurface();
1209 if (surfaceHandle != 0) {
1210 params->token = token;
1211 params->identity = layer->getIdentity();
1212 if (normalLayer != 0) {
1213 Mutex::Autolock _l(mStateLock);
1214 mLayerMap.add(layer->getSurfaceBinder(), normalLayer);
1215 }
1216 }
1217
1218 setTransactionFlags(eTransactionNeeded);
1219 }
1220
1221 return surfaceHandle;
1222 }
1223
createNormalSurface(const sp<Client> & client,DisplayID display,uint32_t w,uint32_t h,uint32_t flags,PixelFormat & format)1224 sp<Layer> SurfaceFlinger::createNormalSurface(
1225 const sp<Client>& client, DisplayID display,
1226 uint32_t w, uint32_t h, uint32_t flags,
1227 PixelFormat& format)
1228 {
1229 // initialize the surfaces
1230 switch (format) { // TODO: take h/w into account
1231 case PIXEL_FORMAT_TRANSPARENT:
1232 case PIXEL_FORMAT_TRANSLUCENT:
1233 format = PIXEL_FORMAT_RGBA_8888;
1234 break;
1235 case PIXEL_FORMAT_OPAQUE:
1236 #ifdef NO_RGBX_8888
1237 format = PIXEL_FORMAT_RGB_565;
1238 #else
1239 format = PIXEL_FORMAT_RGBX_8888;
1240 #endif
1241 break;
1242 }
1243
1244 #ifdef NO_RGBX_8888
1245 if (format == PIXEL_FORMAT_RGBX_8888)
1246 format = PIXEL_FORMAT_RGBA_8888;
1247 #endif
1248
1249 sp<Layer> layer = new Layer(this, display, client);
1250 status_t err = layer->setBuffers(w, h, format, flags);
1251 if (CC_LIKELY(err != NO_ERROR)) {
1252 ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1253 layer.clear();
1254 }
1255 return layer;
1256 }
1257
createDimSurface(const sp<Client> & client,DisplayID display,uint32_t w,uint32_t h,uint32_t flags)1258 sp<LayerDim> SurfaceFlinger::createDimSurface(
1259 const sp<Client>& client, DisplayID display,
1260 uint32_t w, uint32_t h, uint32_t flags)
1261 {
1262 sp<LayerDim> layer = new LayerDim(this, display, client);
1263 return layer;
1264 }
1265
createScreenshotSurface(const sp<Client> & client,DisplayID display,uint32_t w,uint32_t h,uint32_t flags)1266 sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface(
1267 const sp<Client>& client, DisplayID display,
1268 uint32_t w, uint32_t h, uint32_t flags)
1269 {
1270 sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client);
1271 return layer;
1272 }
1273
removeSurface(const sp<Client> & client,SurfaceID sid)1274 status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1275 {
1276 /*
1277 * called by the window manager, when a surface should be marked for
1278 * destruction.
1279 *
1280 * The surface is removed from the current and drawing lists, but placed
1281 * in the purgatory queue, so it's not destroyed right-away (we need
1282 * to wait for all client's references to go away first).
1283 */
1284
1285 status_t err = NAME_NOT_FOUND;
1286 Mutex::Autolock _l(mStateLock);
1287 sp<LayerBaseClient> layer = client->getLayerUser(sid);
1288
1289 if (layer != 0) {
1290 err = purgatorizeLayer_l(layer);
1291 if (err == NO_ERROR) {
1292 setTransactionFlags(eTransactionNeeded);
1293 }
1294 }
1295 return err;
1296 }
1297
destroySurface(const wp<LayerBaseClient> & layer)1298 status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer)
1299 {
1300 // called by ~ISurface() when all references are gone
1301 status_t err = NO_ERROR;
1302 sp<LayerBaseClient> l(layer.promote());
1303 if (l != NULL) {
1304 Mutex::Autolock _l(mStateLock);
1305 err = removeLayer_l(l);
1306 if (err == NAME_NOT_FOUND) {
1307 // The surface wasn't in the current list, which means it was
1308 // removed already, which means it is in the purgatory,
1309 // and need to be removed from there.
1310 ssize_t idx = mLayerPurgatory.remove(l);
1311 ALOGE_IF(idx < 0,
1312 "layer=%p is not in the purgatory list", l.get());
1313 }
1314 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1315 "error removing layer=%p (%s)", l.get(), strerror(-err));
1316 }
1317 return err;
1318 }
1319
setClientStateLocked(const sp<Client> & client,const layer_state_t & s)1320 uint32_t SurfaceFlinger::setClientStateLocked(
1321 const sp<Client>& client,
1322 const layer_state_t& s)
1323 {
1324 uint32_t flags = 0;
1325 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1326 if (layer != 0) {
1327 const uint32_t what = s.what;
1328 if (what & ePositionChanged) {
1329 if (layer->setPosition(s.x, s.y))
1330 flags |= eTraversalNeeded;
1331 }
1332 if (what & eLayerChanged) {
1333 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1334 if (layer->setLayer(s.z)) {
1335 mCurrentState.layersSortedByZ.removeAt(idx);
1336 mCurrentState.layersSortedByZ.add(layer);
1337 // we need traversal (state changed)
1338 // AND transaction (list changed)
1339 flags |= eTransactionNeeded|eTraversalNeeded;
1340 }
1341 }
1342 if (what & eSizeChanged) {
1343 if (layer->setSize(s.w, s.h)) {
1344 flags |= eTraversalNeeded;
1345 }
1346 }
1347 if (what & eAlphaChanged) {
1348 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1349 flags |= eTraversalNeeded;
1350 }
1351 if (what & eMatrixChanged) {
1352 if (layer->setMatrix(s.matrix))
1353 flags |= eTraversalNeeded;
1354 }
1355 if (what & eTransparentRegionChanged) {
1356 if (layer->setTransparentRegionHint(s.transparentRegion))
1357 flags |= eTraversalNeeded;
1358 }
1359 if (what & eVisibilityChanged) {
1360 if (layer->setFlags(s.flags, s.mask))
1361 flags |= eTraversalNeeded;
1362 }
1363 if (what & eCropChanged) {
1364 if (layer->setCrop(s.crop))
1365 flags |= eTraversalNeeded;
1366 }
1367 }
1368 return flags;
1369 }
1370
1371 // ---------------------------------------------------------------------------
1372
onScreenAcquired()1373 void SurfaceFlinger::onScreenAcquired() {
1374 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1375 hw.acquireScreen();
1376 mEventThread->onScreenAcquired();
1377 // this is a temporary work-around, eventually this should be called
1378 // by the power-manager
1379 SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode);
1380 // from this point on, SF will process updates again
1381 repaintEverything();
1382 }
1383
onScreenReleased()1384 void SurfaceFlinger::onScreenReleased() {
1385 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1386 if (hw.isScreenAcquired()) {
1387 mEventThread->onScreenReleased();
1388 hw.releaseScreen();
1389 // from this point on, SF will stop drawing
1390 }
1391 }
1392
screenAcquired()1393 void SurfaceFlinger::screenAcquired() {
1394 class MessageScreenAcquired : public MessageBase {
1395 SurfaceFlinger* flinger;
1396 public:
1397 MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1398 virtual bool handler() {
1399 flinger->onScreenAcquired();
1400 return true;
1401 }
1402 };
1403 sp<MessageBase> msg = new MessageScreenAcquired(this);
1404 postMessageSync(msg);
1405 }
1406
screenReleased()1407 void SurfaceFlinger::screenReleased() {
1408 class MessageScreenReleased : public MessageBase {
1409 SurfaceFlinger* flinger;
1410 public:
1411 MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1412 virtual bool handler() {
1413 flinger->onScreenReleased();
1414 return true;
1415 }
1416 };
1417 sp<MessageBase> msg = new MessageScreenReleased(this);
1418 postMessageSync(msg);
1419 }
1420
1421 // ---------------------------------------------------------------------------
1422
dump(int fd,const Vector<String16> & args)1423 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1424 {
1425 const size_t SIZE = 4096;
1426 char buffer[SIZE];
1427 String8 result;
1428
1429 if (!PermissionCache::checkCallingPermission(sDump)) {
1430 snprintf(buffer, SIZE, "Permission Denial: "
1431 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1432 IPCThreadState::self()->getCallingPid(),
1433 IPCThreadState::self()->getCallingUid());
1434 result.append(buffer);
1435 } else {
1436 // Try to get the main lock, but don't insist if we can't
1437 // (this would indicate SF is stuck, but we want to be able to
1438 // print something in dumpsys).
1439 int retry = 3;
1440 while (mStateLock.tryLock()<0 && --retry>=0) {
1441 usleep(1000000);
1442 }
1443 const bool locked(retry >= 0);
1444 if (!locked) {
1445 snprintf(buffer, SIZE,
1446 "SurfaceFlinger appears to be unresponsive, "
1447 "dumping anyways (no locks held)\n");
1448 result.append(buffer);
1449 }
1450
1451 bool dumpAll = true;
1452 size_t index = 0;
1453 size_t numArgs = args.size();
1454 if (numArgs) {
1455 if ((index < numArgs) &&
1456 (args[index] == String16("--list"))) {
1457 index++;
1458 listLayersLocked(args, index, result, buffer, SIZE);
1459 dumpAll = false;
1460 }
1461
1462 if ((index < numArgs) &&
1463 (args[index] == String16("--latency"))) {
1464 index++;
1465 dumpStatsLocked(args, index, result, buffer, SIZE);
1466 dumpAll = false;
1467 }
1468
1469 if ((index < numArgs) &&
1470 (args[index] == String16("--latency-clear"))) {
1471 index++;
1472 clearStatsLocked(args, index, result, buffer, SIZE);
1473 dumpAll = false;
1474 }
1475 }
1476
1477 if (dumpAll) {
1478 dumpAllLocked(result, buffer, SIZE);
1479 }
1480
1481 if (locked) {
1482 mStateLock.unlock();
1483 }
1484 }
1485 write(fd, result.string(), result.size());
1486 return NO_ERROR;
1487 }
1488
listLayersLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const1489 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1490 String8& result, char* buffer, size_t SIZE) const
1491 {
1492 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1493 const size_t count = currentLayers.size();
1494 for (size_t i=0 ; i<count ; i++) {
1495 const sp<LayerBase>& layer(currentLayers[i]);
1496 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1497 result.append(buffer);
1498 }
1499 }
1500
dumpStatsLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const1501 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1502 String8& result, char* buffer, size_t SIZE) const
1503 {
1504 String8 name;
1505 if (index < args.size()) {
1506 name = String8(args[index]);
1507 index++;
1508 }
1509
1510 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1511 const size_t count = currentLayers.size();
1512 for (size_t i=0 ; i<count ; i++) {
1513 const sp<LayerBase>& layer(currentLayers[i]);
1514 if (name.isEmpty()) {
1515 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1516 result.append(buffer);
1517 }
1518 if (name.isEmpty() || (name == layer->getName())) {
1519 layer->dumpStats(result, buffer, SIZE);
1520 }
1521 }
1522 }
1523
clearStatsLocked(const Vector<String16> & args,size_t & index,String8 & result,char * buffer,size_t SIZE) const1524 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1525 String8& result, char* buffer, size_t SIZE) const
1526 {
1527 String8 name;
1528 if (index < args.size()) {
1529 name = String8(args[index]);
1530 index++;
1531 }
1532
1533 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1534 const size_t count = currentLayers.size();
1535 for (size_t i=0 ; i<count ; i++) {
1536 const sp<LayerBase>& layer(currentLayers[i]);
1537 if (name.isEmpty() || (name == layer->getName())) {
1538 layer->clearStats();
1539 }
1540 }
1541 }
1542
dumpAllLocked(String8 & result,char * buffer,size_t SIZE) const1543 void SurfaceFlinger::dumpAllLocked(
1544 String8& result, char* buffer, size_t SIZE) const
1545 {
1546 // figure out if we're stuck somewhere
1547 const nsecs_t now = systemTime();
1548 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1549 const nsecs_t inTransaction(mDebugInTransaction);
1550 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1551 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1552
1553 /*
1554 * Dump the visible layer list
1555 */
1556 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1557 const size_t count = currentLayers.size();
1558 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1559 result.append(buffer);
1560 for (size_t i=0 ; i<count ; i++) {
1561 const sp<LayerBase>& layer(currentLayers[i]);
1562 layer->dump(result, buffer, SIZE);
1563 }
1564
1565 /*
1566 * Dump the layers in the purgatory
1567 */
1568
1569 const size_t purgatorySize = mLayerPurgatory.size();
1570 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1571 result.append(buffer);
1572 for (size_t i=0 ; i<purgatorySize ; i++) {
1573 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1574 layer->shortDump(result, buffer, SIZE);
1575 }
1576
1577 /*
1578 * Dump SurfaceFlinger global state
1579 */
1580
1581 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1582 result.append(buffer);
1583
1584 const GLExtensions& extensions(GLExtensions::getInstance());
1585 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1586 extensions.getVendor(),
1587 extensions.getRenderer(),
1588 extensions.getVersion());
1589 result.append(buffer);
1590
1591 snprintf(buffer, SIZE, "EGL : %s\n",
1592 eglQueryString(graphicPlane(0).getEGLDisplay(),
1593 EGL_VERSION_HW_ANDROID));
1594 result.append(buffer);
1595
1596 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1597 result.append(buffer);
1598
1599 mWormholeRegion.dump(result, "WormholeRegion");
1600 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1601 snprintf(buffer, SIZE,
1602 " orientation=%d, canDraw=%d\n",
1603 mCurrentState.orientation, hw.canDraw());
1604 result.append(buffer);
1605 snprintf(buffer, SIZE,
1606 " last eglSwapBuffers() time: %f us\n"
1607 " last transaction time : %f us\n"
1608 " transaction-flags : %08x\n"
1609 " refresh-rate : %f fps\n"
1610 " x-dpi : %f\n"
1611 " y-dpi : %f\n"
1612 " density : %f\n",
1613 mLastSwapBufferTime/1000.0,
1614 mLastTransactionTime/1000.0,
1615 mTransactionFlags,
1616 hw.getRefreshRate(),
1617 hw.getDpiX(),
1618 hw.getDpiY(),
1619 hw.getDensity());
1620 result.append(buffer);
1621
1622 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
1623 inSwapBuffersDuration/1000.0);
1624 result.append(buffer);
1625
1626 snprintf(buffer, SIZE, " transaction time: %f us\n",
1627 inTransactionDuration/1000.0);
1628 result.append(buffer);
1629
1630 /*
1631 * VSYNC state
1632 */
1633 mEventThread->dump(result, buffer, SIZE);
1634
1635 /*
1636 * Dump HWComposer state
1637 */
1638 HWComposer& hwc(hw.getHwComposer());
1639 snprintf(buffer, SIZE, "h/w composer state:\n");
1640 result.append(buffer);
1641 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
1642 hwc.initCheck()==NO_ERROR ? "present" : "not present",
1643 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
1644 result.append(buffer);
1645 hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ);
1646
1647 /*
1648 * Dump gralloc state
1649 */
1650 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1651 alloc.dump(result);
1652 hw.dump(result);
1653 }
1654
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)1655 status_t SurfaceFlinger::onTransact(
1656 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1657 {
1658 switch (code) {
1659 case CREATE_CONNECTION:
1660 case SET_TRANSACTION_STATE:
1661 case SET_ORIENTATION:
1662 case BOOT_FINISHED:
1663 case TURN_ELECTRON_BEAM_OFF:
1664 case TURN_ELECTRON_BEAM_ON:
1665 {
1666 // codes that require permission check
1667 IPCThreadState* ipc = IPCThreadState::self();
1668 const int pid = ipc->getCallingPid();
1669 const int uid = ipc->getCallingUid();
1670 if ((uid != AID_GRAPHICS) &&
1671 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
1672 ALOGE("Permission Denial: "
1673 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1674 return PERMISSION_DENIED;
1675 }
1676 break;
1677 }
1678 case CAPTURE_SCREEN:
1679 {
1680 // codes that require permission check
1681 IPCThreadState* ipc = IPCThreadState::self();
1682 const int pid = ipc->getCallingPid();
1683 const int uid = ipc->getCallingUid();
1684 if ((uid != AID_GRAPHICS) &&
1685 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
1686 ALOGE("Permission Denial: "
1687 "can't read framebuffer pid=%d, uid=%d", pid, uid);
1688 return PERMISSION_DENIED;
1689 }
1690 break;
1691 }
1692 }
1693
1694 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1695 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1696 CHECK_INTERFACE(ISurfaceComposer, data, reply);
1697 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
1698 IPCThreadState* ipc = IPCThreadState::self();
1699 const int pid = ipc->getCallingPid();
1700 const int uid = ipc->getCallingUid();
1701 ALOGE("Permission Denial: "
1702 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1703 return PERMISSION_DENIED;
1704 }
1705 int n;
1706 switch (code) {
1707 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1708 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1709 return NO_ERROR;
1710 case 1002: // SHOW_UPDATES
1711 n = data.readInt32();
1712 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1713 invalidateHwcGeometry();
1714 repaintEverything();
1715 return NO_ERROR;
1716 case 1004:{ // repaint everything
1717 repaintEverything();
1718 return NO_ERROR;
1719 }
1720 case 1005:{ // force transaction
1721 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1722 return NO_ERROR;
1723 }
1724 case 1006:{ // send empty update
1725 signalRefresh();
1726 return NO_ERROR;
1727 }
1728 case 1008: // toggle use of hw composer
1729 n = data.readInt32();
1730 mDebugDisableHWC = n ? 1 : 0;
1731 invalidateHwcGeometry();
1732 repaintEverything();
1733 return NO_ERROR;
1734 case 1009: // toggle use of transform hint
1735 n = data.readInt32();
1736 mDebugDisableTransformHint = n ? 1 : 0;
1737 invalidateHwcGeometry();
1738 repaintEverything();
1739 return NO_ERROR;
1740 case 1010: // interrogate.
1741 reply->writeInt32(0);
1742 reply->writeInt32(0);
1743 reply->writeInt32(mDebugRegion);
1744 reply->writeInt32(0);
1745 reply->writeInt32(mDebugDisableHWC);
1746 return NO_ERROR;
1747 case 1013: {
1748 Mutex::Autolock _l(mStateLock);
1749 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1750 reply->writeInt32(hw.getPageFlipCount());
1751 }
1752 return NO_ERROR;
1753 }
1754 }
1755 return err;
1756 }
1757
repaintEverything()1758 void SurfaceFlinger::repaintEverything() {
1759 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1760 const Rect bounds(hw.getBounds());
1761 setInvalidateRegion(Region(bounds));
1762 signalTransaction();
1763 }
1764
setInvalidateRegion(const Region & reg)1765 void SurfaceFlinger::setInvalidateRegion(const Region& reg) {
1766 Mutex::Autolock _l(mInvalidateLock);
1767 mInvalidateRegion = reg;
1768 }
1769
getAndClearInvalidateRegion()1770 Region SurfaceFlinger::getAndClearInvalidateRegion() {
1771 Mutex::Autolock _l(mInvalidateLock);
1772 Region reg(mInvalidateRegion);
1773 mInvalidateRegion.clear();
1774 return reg;
1775 }
1776
1777 // ---------------------------------------------------------------------------
1778
renderScreenToTexture(DisplayID dpy,GLuint * textureName,GLfloat * uOut,GLfloat * vOut)1779 status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
1780 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1781 {
1782 Mutex::Autolock _l(mStateLock);
1783 return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
1784 }
1785
renderScreenToTextureLocked(DisplayID dpy,GLuint * textureName,GLfloat * uOut,GLfloat * vOut)1786 status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
1787 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
1788 {
1789 ATRACE_CALL();
1790
1791 if (!GLExtensions::getInstance().haveFramebufferObject())
1792 return INVALID_OPERATION;
1793
1794 // get screen geometry
1795 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
1796 const uint32_t hw_w = hw.getWidth();
1797 const uint32_t hw_h = hw.getHeight();
1798 GLfloat u = 1;
1799 GLfloat v = 1;
1800
1801 // make sure to clear all GL error flags
1802 while ( glGetError() != GL_NO_ERROR ) ;
1803
1804 // create a FBO
1805 GLuint name, tname;
1806 glGenTextures(1, &tname);
1807 glBindTexture(GL_TEXTURE_2D, tname);
1808 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1809 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1810 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1811 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1812 if (glGetError() != GL_NO_ERROR) {
1813 while ( glGetError() != GL_NO_ERROR ) ;
1814 GLint tw = (2 << (31 - clz(hw_w)));
1815 GLint th = (2 << (31 - clz(hw_h)));
1816 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
1817 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
1818 u = GLfloat(hw_w) / tw;
1819 v = GLfloat(hw_h) / th;
1820 }
1821 glGenFramebuffersOES(1, &name);
1822 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
1823 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
1824 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
1825
1826 // redraw the screen entirely...
1827 glDisable(GL_TEXTURE_EXTERNAL_OES);
1828 glDisable(GL_TEXTURE_2D);
1829 glClearColor(0,0,0,1);
1830 glClear(GL_COLOR_BUFFER_BIT);
1831 glMatrixMode(GL_MODELVIEW);
1832 glLoadIdentity();
1833 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
1834 const size_t count = layers.size();
1835 for (size_t i=0 ; i<count ; ++i) {
1836 const sp<LayerBase>& layer(layers[i]);
1837 layer->drawForSreenShot();
1838 }
1839
1840 hw.compositionComplete();
1841
1842 // back to main framebuffer
1843 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
1844 glDeleteFramebuffersOES(1, &name);
1845
1846 *textureName = tname;
1847 *uOut = u;
1848 *vOut = v;
1849 return NO_ERROR;
1850 }
1851
1852 // ---------------------------------------------------------------------------
1853
1854 class VSyncWaiter {
1855 DisplayEventReceiver::Event buffer[4];
1856 sp<Looper> looper;
1857 sp<IDisplayEventConnection> events;
1858 sp<BitTube> eventTube;
1859 public:
VSyncWaiter(const sp<EventThread> & eventThread)1860 VSyncWaiter(const sp<EventThread>& eventThread) {
1861 looper = new Looper(true);
1862 events = eventThread->createEventConnection();
1863 eventTube = events->getDataChannel();
1864 looper->addFd(eventTube->getFd(), 0, ALOOPER_EVENT_INPUT, 0, 0);
1865 events->requestNextVsync();
1866 }
1867
wait()1868 void wait() {
1869 ssize_t n;
1870
1871 looper->pollOnce(-1);
1872 // we don't handle any errors here, it doesn't matter
1873 // and we don't want to take the risk to get stuck.
1874
1875 // drain the events...
1876 while ((n = DisplayEventReceiver::getEvents(
1877 eventTube, buffer, 4)) > 0) ;
1878
1879 events->requestNextVsync();
1880 }
1881 };
1882
electronBeamOffAnimationImplLocked()1883 status_t SurfaceFlinger::electronBeamOffAnimationImplLocked()
1884 {
1885 // get screen geometry
1886 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1887 const uint32_t hw_w = hw.getWidth();
1888 const uint32_t hw_h = hw.getHeight();
1889 const Region screenBounds(hw.getBounds());
1890
1891 GLfloat u, v;
1892 GLuint tname;
1893 status_t result = renderScreenToTextureLocked(0, &tname, &u, &v);
1894 if (result != NO_ERROR) {
1895 return result;
1896 }
1897
1898 GLfloat vtx[8];
1899 const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} };
1900 glBindTexture(GL_TEXTURE_2D, tname);
1901 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1902 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1903 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1904 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1905 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1906 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
1907 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1908 glVertexPointer(2, GL_FLOAT, 0, vtx);
1909
1910 /*
1911 * Texture coordinate mapping
1912 *
1913 * u
1914 * 1 +----------+---+
1915 * | | | | image is inverted
1916 * | V | | w.r.t. the texture
1917 * 1-v +----------+ | coordinates
1918 * | |
1919 * | |
1920 * | |
1921 * 0 +--------------+
1922 * 0 1
1923 *
1924 */
1925
1926 class s_curve_interpolator {
1927 const float nbFrames, s, v;
1928 public:
1929 s_curve_interpolator(int nbFrames, float s)
1930 : nbFrames(1.0f / (nbFrames-1)), s(s),
1931 v(1.0f + expf(-s + 0.5f*s)) {
1932 }
1933 float operator()(int f) {
1934 const float x = f * nbFrames;
1935 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
1936 }
1937 };
1938
1939 class v_stretch {
1940 const GLfloat hw_w, hw_h;
1941 public:
1942 v_stretch(uint32_t hw_w, uint32_t hw_h)
1943 : hw_w(hw_w), hw_h(hw_h) {
1944 }
1945 void operator()(GLfloat* vtx, float v) {
1946 const GLfloat w = hw_w + (hw_w * v);
1947 const GLfloat h = hw_h - (hw_h * v);
1948 const GLfloat x = (hw_w - w) * 0.5f;
1949 const GLfloat y = (hw_h - h) * 0.5f;
1950 vtx[0] = x; vtx[1] = y;
1951 vtx[2] = x; vtx[3] = y + h;
1952 vtx[4] = x + w; vtx[5] = y + h;
1953 vtx[6] = x + w; vtx[7] = y;
1954 }
1955 };
1956
1957 class h_stretch {
1958 const GLfloat hw_w, hw_h;
1959 public:
1960 h_stretch(uint32_t hw_w, uint32_t hw_h)
1961 : hw_w(hw_w), hw_h(hw_h) {
1962 }
1963 void operator()(GLfloat* vtx, float v) {
1964 const GLfloat w = hw_w - (hw_w * v);
1965 const GLfloat h = 1.0f;
1966 const GLfloat x = (hw_w - w) * 0.5f;
1967 const GLfloat y = (hw_h - h) * 0.5f;
1968 vtx[0] = x; vtx[1] = y;
1969 vtx[2] = x; vtx[3] = y + h;
1970 vtx[4] = x + w; vtx[5] = y + h;
1971 vtx[6] = x + w; vtx[7] = y;
1972 }
1973 };
1974
1975 VSyncWaiter vsync(mEventThread);
1976
1977 // the full animation is 24 frames
1978 char value[PROPERTY_VALUE_MAX];
1979 property_get("debug.sf.electron_frames", value, "24");
1980 int nbFrames = (atoi(value) + 1) >> 1;
1981 if (nbFrames <= 0) // just in case
1982 nbFrames = 24;
1983
1984 s_curve_interpolator itr(nbFrames, 7.5f);
1985 s_curve_interpolator itg(nbFrames, 8.0f);
1986 s_curve_interpolator itb(nbFrames, 8.5f);
1987
1988 v_stretch vverts(hw_w, hw_h);
1989
1990 glMatrixMode(GL_TEXTURE);
1991 glLoadIdentity();
1992 glMatrixMode(GL_MODELVIEW);
1993 glLoadIdentity();
1994
1995 glEnable(GL_BLEND);
1996 glBlendFunc(GL_ONE, GL_ONE);
1997 for (int i=0 ; i<nbFrames ; i++) {
1998 float x, y, w, h;
1999 const float vr = itr(i);
2000 const float vg = itg(i);
2001 const float vb = itb(i);
2002
2003 // wait for vsync
2004 vsync.wait();
2005
2006 // clear screen
2007 glColorMask(1,1,1,1);
2008 glClear(GL_COLOR_BUFFER_BIT);
2009 glEnable(GL_TEXTURE_2D);
2010
2011 // draw the red plane
2012 vverts(vtx, vr);
2013 glColorMask(1,0,0,1);
2014 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2015
2016 // draw the green plane
2017 vverts(vtx, vg);
2018 glColorMask(0,1,0,1);
2019 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2020
2021 // draw the blue plane
2022 vverts(vtx, vb);
2023 glColorMask(0,0,1,1);
2024 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2025
2026 // draw the white highlight (we use the last vertices)
2027 glDisable(GL_TEXTURE_2D);
2028 glColorMask(1,1,1,1);
2029 glColor4f(vg, vg, vg, 1);
2030 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2031 hw.flip(screenBounds);
2032 }
2033
2034 h_stretch hverts(hw_w, hw_h);
2035 glDisable(GL_BLEND);
2036 glDisable(GL_TEXTURE_2D);
2037 glColorMask(1,1,1,1);
2038 for (int i=0 ; i<nbFrames ; i++) {
2039 const float v = itg(i);
2040 hverts(vtx, v);
2041
2042 // wait for vsync
2043 vsync.wait();
2044
2045 glClear(GL_COLOR_BUFFER_BIT);
2046 glColor4f(1-v, 1-v, 1-v, 1);
2047 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2048 hw.flip(screenBounds);
2049 }
2050
2051 glColorMask(1,1,1,1);
2052 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2053 glDeleteTextures(1, &tname);
2054 glDisable(GL_TEXTURE_2D);
2055 glDisable(GL_BLEND);
2056 return NO_ERROR;
2057 }
2058
electronBeamOnAnimationImplLocked()2059 status_t SurfaceFlinger::electronBeamOnAnimationImplLocked()
2060 {
2061 status_t result = PERMISSION_DENIED;
2062
2063 if (!GLExtensions::getInstance().haveFramebufferObject())
2064 return INVALID_OPERATION;
2065
2066
2067 // get screen geometry
2068 const DisplayHardware& hw(graphicPlane(0).displayHardware());
2069 const uint32_t hw_w = hw.getWidth();
2070 const uint32_t hw_h = hw.getHeight();
2071 const Region screenBounds(hw.bounds());
2072
2073 GLfloat u, v;
2074 GLuint tname;
2075 result = renderScreenToTextureLocked(0, &tname, &u, &v);
2076 if (result != NO_ERROR) {
2077 return result;
2078 }
2079
2080 GLfloat vtx[8];
2081 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} };
2082 glBindTexture(GL_TEXTURE_2D, tname);
2083 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
2084 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2085 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2086 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2087 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2088 glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
2089 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
2090 glVertexPointer(2, GL_FLOAT, 0, vtx);
2091
2092 class s_curve_interpolator {
2093 const float nbFrames, s, v;
2094 public:
2095 s_curve_interpolator(int nbFrames, float s)
2096 : nbFrames(1.0f / (nbFrames-1)), s(s),
2097 v(1.0f + expf(-s + 0.5f*s)) {
2098 }
2099 float operator()(int f) {
2100 const float x = f * nbFrames;
2101 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f;
2102 }
2103 };
2104
2105 class v_stretch {
2106 const GLfloat hw_w, hw_h;
2107 public:
2108 v_stretch(uint32_t hw_w, uint32_t hw_h)
2109 : hw_w(hw_w), hw_h(hw_h) {
2110 }
2111 void operator()(GLfloat* vtx, float v) {
2112 const GLfloat w = hw_w + (hw_w * v);
2113 const GLfloat h = hw_h - (hw_h * v);
2114 const GLfloat x = (hw_w - w) * 0.5f;
2115 const GLfloat y = (hw_h - h) * 0.5f;
2116 vtx[0] = x; vtx[1] = y;
2117 vtx[2] = x; vtx[3] = y + h;
2118 vtx[4] = x + w; vtx[5] = y + h;
2119 vtx[6] = x + w; vtx[7] = y;
2120 }
2121 };
2122
2123 class h_stretch {
2124 const GLfloat hw_w, hw_h;
2125 public:
2126 h_stretch(uint32_t hw_w, uint32_t hw_h)
2127 : hw_w(hw_w), hw_h(hw_h) {
2128 }
2129 void operator()(GLfloat* vtx, float v) {
2130 const GLfloat w = hw_w - (hw_w * v);
2131 const GLfloat h = 1.0f;
2132 const GLfloat x = (hw_w - w) * 0.5f;
2133 const GLfloat y = (hw_h - h) * 0.5f;
2134 vtx[0] = x; vtx[1] = y;
2135 vtx[2] = x; vtx[3] = y + h;
2136 vtx[4] = x + w; vtx[5] = y + h;
2137 vtx[6] = x + w; vtx[7] = y;
2138 }
2139 };
2140
2141 VSyncWaiter vsync(mEventThread);
2142
2143 // the full animation is 12 frames
2144 int nbFrames = 8;
2145 s_curve_interpolator itr(nbFrames, 7.5f);
2146 s_curve_interpolator itg(nbFrames, 8.0f);
2147 s_curve_interpolator itb(nbFrames, 8.5f);
2148
2149 h_stretch hverts(hw_w, hw_h);
2150 glDisable(GL_BLEND);
2151 glDisable(GL_TEXTURE_2D);
2152 glColorMask(1,1,1,1);
2153 for (int i=nbFrames-1 ; i>=0 ; i--) {
2154 const float v = itg(i);
2155 hverts(vtx, v);
2156
2157 // wait for vsync
2158 vsync.wait();
2159
2160 glClear(GL_COLOR_BUFFER_BIT);
2161 glColor4f(1-v, 1-v, 1-v, 1);
2162 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2163 hw.flip(screenBounds);
2164 }
2165
2166 nbFrames = 4;
2167 v_stretch vverts(hw_w, hw_h);
2168 glEnable(GL_BLEND);
2169 glBlendFunc(GL_ONE, GL_ONE);
2170 for (int i=nbFrames-1 ; i>=0 ; i--) {
2171 float x, y, w, h;
2172 const float vr = itr(i);
2173 const float vg = itg(i);
2174 const float vb = itb(i);
2175
2176 // wait for vsync
2177 vsync.wait();
2178
2179 // clear screen
2180 glColorMask(1,1,1,1);
2181 glClear(GL_COLOR_BUFFER_BIT);
2182 glEnable(GL_TEXTURE_2D);
2183
2184 // draw the red plane
2185 vverts(vtx, vr);
2186 glColorMask(1,0,0,1);
2187 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2188
2189 // draw the green plane
2190 vverts(vtx, vg);
2191 glColorMask(0,1,0,1);
2192 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2193
2194 // draw the blue plane
2195 vverts(vtx, vb);
2196 glColorMask(0,0,1,1);
2197 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
2198
2199 hw.flip(screenBounds);
2200 }
2201
2202 glColorMask(1,1,1,1);
2203 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2204 glDeleteTextures(1, &tname);
2205 glDisable(GL_TEXTURE_2D);
2206 glDisable(GL_BLEND);
2207
2208 return NO_ERROR;
2209 }
2210
2211 // ---------------------------------------------------------------------------
2212
turnElectronBeamOffImplLocked(int32_t mode)2213 status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode)
2214 {
2215 ATRACE_CALL();
2216
2217 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2218 if (!hw.canDraw()) {
2219 // we're already off
2220 return NO_ERROR;
2221 }
2222
2223 // turn off hwc while we're doing the animation
2224 hw.getHwComposer().disable();
2225 // and make sure to turn it back on (if needed) next time we compose
2226 invalidateHwcGeometry();
2227
2228 if (mode & ISurfaceComposer::eElectronBeamAnimationOff) {
2229 electronBeamOffAnimationImplLocked();
2230 }
2231
2232 // always clear the whole screen at the end of the animation
2233 glClearColor(0,0,0,1);
2234 glClear(GL_COLOR_BUFFER_BIT);
2235 hw.flip( Region(hw.bounds()) );
2236
2237 return NO_ERROR;
2238 }
2239
turnElectronBeamOff(int32_t mode)2240 status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode)
2241 {
2242 class MessageTurnElectronBeamOff : public MessageBase {
2243 SurfaceFlinger* flinger;
2244 int32_t mode;
2245 status_t result;
2246 public:
2247 MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode)
2248 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2249 }
2250 status_t getResult() const {
2251 return result;
2252 }
2253 virtual bool handler() {
2254 Mutex::Autolock _l(flinger->mStateLock);
2255 result = flinger->turnElectronBeamOffImplLocked(mode);
2256 return true;
2257 }
2258 };
2259
2260 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode);
2261 status_t res = postMessageSync(msg);
2262 if (res == NO_ERROR) {
2263 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult();
2264
2265 // work-around: when the power-manager calls us we activate the
2266 // animation. eventually, the "on" animation will be called
2267 // by the power-manager itself
2268 mElectronBeamAnimationMode = mode;
2269 }
2270 return res;
2271 }
2272
2273 // ---------------------------------------------------------------------------
2274
turnElectronBeamOnImplLocked(int32_t mode)2275 status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode)
2276 {
2277 DisplayHardware& hw(graphicPlane(0).editDisplayHardware());
2278 if (hw.canDraw()) {
2279 // we're already on
2280 return NO_ERROR;
2281 }
2282 if (mode & ISurfaceComposer::eElectronBeamAnimationOn) {
2283 electronBeamOnAnimationImplLocked();
2284 }
2285
2286 // make sure to redraw the whole screen when the animation is done
2287 mDirtyRegion.set(hw.bounds());
2288 signalTransaction();
2289
2290 return NO_ERROR;
2291 }
2292
turnElectronBeamOn(int32_t mode)2293 status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode)
2294 {
2295 class MessageTurnElectronBeamOn : public MessageBase {
2296 SurfaceFlinger* flinger;
2297 int32_t mode;
2298 status_t result;
2299 public:
2300 MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode)
2301 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) {
2302 }
2303 status_t getResult() const {
2304 return result;
2305 }
2306 virtual bool handler() {
2307 Mutex::Autolock _l(flinger->mStateLock);
2308 result = flinger->turnElectronBeamOnImplLocked(mode);
2309 return true;
2310 }
2311 };
2312
2313 postMessageAsync( new MessageTurnElectronBeamOn(this, mode) );
2314 return NO_ERROR;
2315 }
2316
2317 // ---------------------------------------------------------------------------
2318
captureScreenImplLocked(DisplayID dpy,sp<IMemoryHeap> * heap,uint32_t * w,uint32_t * h,PixelFormat * f,uint32_t sw,uint32_t sh,uint32_t minLayerZ,uint32_t maxLayerZ)2319 status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2320 sp<IMemoryHeap>* heap,
2321 uint32_t* w, uint32_t* h, PixelFormat* f,
2322 uint32_t sw, uint32_t sh,
2323 uint32_t minLayerZ, uint32_t maxLayerZ)
2324 {
2325 ATRACE_CALL();
2326
2327 status_t result = PERMISSION_DENIED;
2328
2329 // only one display supported for now
2330 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2331 return BAD_VALUE;
2332
2333 if (!GLExtensions::getInstance().haveFramebufferObject())
2334 return INVALID_OPERATION;
2335
2336 // get screen geometry
2337 const DisplayHardware& hw(graphicPlane(dpy).displayHardware());
2338 const uint32_t hw_w = hw.getWidth();
2339 const uint32_t hw_h = hw.getHeight();
2340
2341 if ((sw > hw_w) || (sh > hw_h))
2342 return BAD_VALUE;
2343
2344 sw = (!sw) ? hw_w : sw;
2345 sh = (!sh) ? hw_h : sh;
2346 const size_t size = sw * sh * 4;
2347
2348 //ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2349 // sw, sh, minLayerZ, maxLayerZ);
2350
2351 // make sure to clear all GL error flags
2352 while ( glGetError() != GL_NO_ERROR ) ;
2353
2354 // create a FBO
2355 GLuint name, tname;
2356 glGenRenderbuffersOES(1, &tname);
2357 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2358 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2359
2360 glGenFramebuffersOES(1, &name);
2361 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2362 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2363 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2364
2365 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2366
2367 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2368
2369 // invert everything, b/c glReadPixel() below will invert the FB
2370 glViewport(0, 0, sw, sh);
2371 glMatrixMode(GL_PROJECTION);
2372 glPushMatrix();
2373 glLoadIdentity();
2374 glOrthof(0, hw_w, hw_h, 0, 0, 1);
2375 glMatrixMode(GL_MODELVIEW);
2376
2377 // redraw the screen entirely...
2378 glClearColor(0,0,0,1);
2379 glClear(GL_COLOR_BUFFER_BIT);
2380
2381 const LayerVector& layers(mDrawingState.layersSortedByZ);
2382 const size_t count = layers.size();
2383 for (size_t i=0 ; i<count ; ++i) {
2384 const sp<LayerBase>& layer(layers[i]);
2385 const uint32_t flags = layer->drawingState().flags;
2386 if (!(flags & ISurfaceComposer::eLayerHidden)) {
2387 const uint32_t z = layer->drawingState().z;
2388 if (z >= minLayerZ && z <= maxLayerZ) {
2389 layer->drawForSreenShot();
2390 }
2391 }
2392 }
2393
2394 // check for errors and return screen capture
2395 if (glGetError() != GL_NO_ERROR) {
2396 // error while rendering
2397 result = INVALID_OPERATION;
2398 } else {
2399 // allocate shared memory large enough to hold the
2400 // screen capture
2401 sp<MemoryHeapBase> base(
2402 new MemoryHeapBase(size, 0, "screen-capture") );
2403 void* const ptr = base->getBase();
2404 if (ptr) {
2405 // capture the screen with glReadPixels()
2406 ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2407 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2408 if (glGetError() == GL_NO_ERROR) {
2409 *heap = base;
2410 *w = sw;
2411 *h = sh;
2412 *f = PIXEL_FORMAT_RGBA_8888;
2413 result = NO_ERROR;
2414 }
2415 } else {
2416 result = NO_MEMORY;
2417 }
2418 }
2419 glViewport(0, 0, hw_w, hw_h);
2420 glMatrixMode(GL_PROJECTION);
2421 glPopMatrix();
2422 glMatrixMode(GL_MODELVIEW);
2423 } else {
2424 result = BAD_VALUE;
2425 }
2426
2427 // release FBO resources
2428 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2429 glDeleteRenderbuffersOES(1, &tname);
2430 glDeleteFramebuffersOES(1, &name);
2431
2432 hw.compositionComplete();
2433
2434 // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2435
2436 return result;
2437 }
2438
2439
captureScreen(DisplayID dpy,sp<IMemoryHeap> * heap,uint32_t * width,uint32_t * height,PixelFormat * format,uint32_t sw,uint32_t sh,uint32_t minLayerZ,uint32_t maxLayerZ)2440 status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2441 sp<IMemoryHeap>* heap,
2442 uint32_t* width, uint32_t* height, PixelFormat* format,
2443 uint32_t sw, uint32_t sh,
2444 uint32_t minLayerZ, uint32_t maxLayerZ)
2445 {
2446 // only one display supported for now
2447 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2448 return BAD_VALUE;
2449
2450 if (!GLExtensions::getInstance().haveFramebufferObject())
2451 return INVALID_OPERATION;
2452
2453 class MessageCaptureScreen : public MessageBase {
2454 SurfaceFlinger* flinger;
2455 DisplayID dpy;
2456 sp<IMemoryHeap>* heap;
2457 uint32_t* w;
2458 uint32_t* h;
2459 PixelFormat* f;
2460 uint32_t sw;
2461 uint32_t sh;
2462 uint32_t minLayerZ;
2463 uint32_t maxLayerZ;
2464 status_t result;
2465 public:
2466 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2467 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2468 uint32_t sw, uint32_t sh,
2469 uint32_t minLayerZ, uint32_t maxLayerZ)
2470 : flinger(flinger), dpy(dpy),
2471 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2472 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2473 result(PERMISSION_DENIED)
2474 {
2475 }
2476 status_t getResult() const {
2477 return result;
2478 }
2479 virtual bool handler() {
2480 Mutex::Autolock _l(flinger->mStateLock);
2481
2482 // if we have secure windows, never allow the screen capture
2483 if (flinger->mSecureFrameBuffer)
2484 return true;
2485
2486 result = flinger->captureScreenImplLocked(dpy,
2487 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2488
2489 return true;
2490 }
2491 };
2492
2493 sp<MessageBase> msg = new MessageCaptureScreen(this,
2494 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2495 status_t res = postMessageSync(msg);
2496 if (res == NO_ERROR) {
2497 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2498 }
2499 return res;
2500 }
2501
2502 // ---------------------------------------------------------------------------
2503
getLayer(const sp<ISurface> & sur) const2504 sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
2505 {
2506 sp<Layer> result;
2507 Mutex::Autolock _l(mStateLock);
2508 result = mLayerMap.valueFor( sur->asBinder() ).promote();
2509 return result;
2510 }
2511
2512 // ---------------------------------------------------------------------------
2513
Client(const sp<SurfaceFlinger> & flinger)2514 Client::Client(const sp<SurfaceFlinger>& flinger)
2515 : mFlinger(flinger), mNameGenerator(1)
2516 {
2517 }
2518
~Client()2519 Client::~Client()
2520 {
2521 const size_t count = mLayers.size();
2522 for (size_t i=0 ; i<count ; i++) {
2523 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
2524 if (layer != 0) {
2525 mFlinger->removeLayer(layer);
2526 }
2527 }
2528 }
2529
initCheck() const2530 status_t Client::initCheck() const {
2531 return NO_ERROR;
2532 }
2533
attachLayer(const sp<LayerBaseClient> & layer)2534 size_t Client::attachLayer(const sp<LayerBaseClient>& layer)
2535 {
2536 Mutex::Autolock _l(mLock);
2537 size_t name = mNameGenerator++;
2538 mLayers.add(name, layer);
2539 return name;
2540 }
2541
detachLayer(const LayerBaseClient * layer)2542 void Client::detachLayer(const LayerBaseClient* layer)
2543 {
2544 Mutex::Autolock _l(mLock);
2545 // we do a linear search here, because this doesn't happen often
2546 const size_t count = mLayers.size();
2547 for (size_t i=0 ; i<count ; i++) {
2548 if (mLayers.valueAt(i) == layer) {
2549 mLayers.removeItemsAt(i, 1);
2550 break;
2551 }
2552 }
2553 }
getLayerUser(int32_t i) const2554 sp<LayerBaseClient> Client::getLayerUser(int32_t i) const
2555 {
2556 Mutex::Autolock _l(mLock);
2557 sp<LayerBaseClient> lbc;
2558 wp<LayerBaseClient> layer(mLayers.valueFor(i));
2559 if (layer != 0) {
2560 lbc = layer.promote();
2561 ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
2562 }
2563 return lbc;
2564 }
2565
2566
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2567 status_t Client::onTransact(
2568 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2569 {
2570 // these must be checked
2571 IPCThreadState* ipc = IPCThreadState::self();
2572 const int pid = ipc->getCallingPid();
2573 const int uid = ipc->getCallingUid();
2574 const int self_pid = getpid();
2575 if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) {
2576 // we're called from a different process, do the real check
2577 if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger))
2578 {
2579 ALOGE("Permission Denial: "
2580 "can't openGlobalTransaction pid=%d, uid=%d", pid, uid);
2581 return PERMISSION_DENIED;
2582 }
2583 }
2584 return BnSurfaceComposerClient::onTransact(code, data, reply, flags);
2585 }
2586
2587
createSurface(ISurfaceComposerClient::surface_data_t * params,const String8 & name,DisplayID display,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags)2588 sp<ISurface> Client::createSurface(
2589 ISurfaceComposerClient::surface_data_t* params,
2590 const String8& name,
2591 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2592 uint32_t flags)
2593 {
2594 /*
2595 * createSurface must be called from the GL thread so that it can
2596 * have access to the GL context.
2597 */
2598
2599 class MessageCreateSurface : public MessageBase {
2600 sp<ISurface> result;
2601 SurfaceFlinger* flinger;
2602 ISurfaceComposerClient::surface_data_t* params;
2603 Client* client;
2604 const String8& name;
2605 DisplayID display;
2606 uint32_t w, h;
2607 PixelFormat format;
2608 uint32_t flags;
2609 public:
2610 MessageCreateSurface(SurfaceFlinger* flinger,
2611 ISurfaceComposerClient::surface_data_t* params,
2612 const String8& name, Client* client,
2613 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
2614 uint32_t flags)
2615 : flinger(flinger), params(params), client(client), name(name),
2616 display(display), w(w), h(h), format(format), flags(flags)
2617 {
2618 }
2619 sp<ISurface> getResult() const { return result; }
2620 virtual bool handler() {
2621 result = flinger->createSurface(params, name, client,
2622 display, w, h, format, flags);
2623 return true;
2624 }
2625 };
2626
2627 sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),
2628 params, name, this, display, w, h, format, flags);
2629 mFlinger->postMessageSync(msg);
2630 return static_cast<MessageCreateSurface*>( msg.get() )->getResult();
2631 }
destroySurface(SurfaceID sid)2632 status_t Client::destroySurface(SurfaceID sid) {
2633 return mFlinger->removeSurface(this, sid);
2634 }
2635
2636 // ---------------------------------------------------------------------------
2637
GraphicBufferAlloc()2638 GraphicBufferAlloc::GraphicBufferAlloc() {}
2639
~GraphicBufferAlloc()2640 GraphicBufferAlloc::~GraphicBufferAlloc() {}
2641
createGraphicBuffer(uint32_t w,uint32_t h,PixelFormat format,uint32_t usage,status_t * error)2642 sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2643 PixelFormat format, uint32_t usage, status_t* error) {
2644 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2645 status_t err = graphicBuffer->initCheck();
2646 *error = err;
2647 if (err != 0 || graphicBuffer->handle == 0) {
2648 if (err == NO_MEMORY) {
2649 GraphicBuffer::dumpAllocationsToSystemLog();
2650 }
2651 ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2652 "failed (%s), handle=%p",
2653 w, h, strerror(-err), graphicBuffer->handle);
2654 return 0;
2655 }
2656 return graphicBuffer;
2657 }
2658
2659 // ---------------------------------------------------------------------------
2660
GraphicPlane()2661 GraphicPlane::GraphicPlane()
2662 : mHw(0)
2663 {
2664 }
2665
~GraphicPlane()2666 GraphicPlane::~GraphicPlane() {
2667 delete mHw;
2668 }
2669
initialized() const2670 bool GraphicPlane::initialized() const {
2671 return mHw ? true : false;
2672 }
2673
getWidth() const2674 int GraphicPlane::getWidth() const {
2675 return mWidth;
2676 }
2677
getHeight() const2678 int GraphicPlane::getHeight() const {
2679 return mHeight;
2680 }
2681
setDisplayHardware(DisplayHardware * hw)2682 void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
2683 {
2684 mHw = hw;
2685
2686 // initialize the display orientation transform.
2687 // it's a constant that should come from the display driver.
2688 int displayOrientation = ISurfaceComposer::eOrientationDefault;
2689 char property[PROPERTY_VALUE_MAX];
2690 if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
2691 //displayOrientation
2692 switch (atoi(property)) {
2693 case 90:
2694 displayOrientation = ISurfaceComposer::eOrientation90;
2695 break;
2696 case 270:
2697 displayOrientation = ISurfaceComposer::eOrientation270;
2698 break;
2699 }
2700 }
2701
2702 const float w = hw->getWidth();
2703 const float h = hw->getHeight();
2704 GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
2705 &mDisplayTransform);
2706 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
2707 mDisplayWidth = h;
2708 mDisplayHeight = w;
2709 } else {
2710 mDisplayWidth = w;
2711 mDisplayHeight = h;
2712 }
2713
2714 setOrientation(ISurfaceComposer::eOrientationDefault);
2715 }
2716
orientationToTransfrom(int orientation,int w,int h,Transform * tr)2717 status_t GraphicPlane::orientationToTransfrom(
2718 int orientation, int w, int h, Transform* tr)
2719 {
2720 uint32_t flags = 0;
2721 switch (orientation) {
2722 case ISurfaceComposer::eOrientationDefault:
2723 flags = Transform::ROT_0;
2724 break;
2725 case ISurfaceComposer::eOrientation90:
2726 flags = Transform::ROT_90;
2727 break;
2728 case ISurfaceComposer::eOrientation180:
2729 flags = Transform::ROT_180;
2730 break;
2731 case ISurfaceComposer::eOrientation270:
2732 flags = Transform::ROT_270;
2733 break;
2734 default:
2735 return BAD_VALUE;
2736 }
2737 tr->set(flags, w, h);
2738 return NO_ERROR;
2739 }
2740
setOrientation(int orientation)2741 status_t GraphicPlane::setOrientation(int orientation)
2742 {
2743 // If the rotation can be handled in hardware, this is where
2744 // the magic should happen.
2745
2746 const DisplayHardware& hw(displayHardware());
2747 const float w = mDisplayWidth;
2748 const float h = mDisplayHeight;
2749 mWidth = int(w);
2750 mHeight = int(h);
2751
2752 Transform orientationTransform;
2753 GraphicPlane::orientationToTransfrom(orientation, w, h,
2754 &orientationTransform);
2755 if (orientation & ISurfaceComposer::eOrientationSwapMask) {
2756 mWidth = int(h);
2757 mHeight = int(w);
2758 }
2759
2760 mOrientation = orientation;
2761 mGlobalTransform = mDisplayTransform * orientationTransform;
2762 return NO_ERROR;
2763 }
2764
displayHardware() const2765 const DisplayHardware& GraphicPlane::displayHardware() const {
2766 return *mHw;
2767 }
2768
editDisplayHardware()2769 DisplayHardware& GraphicPlane::editDisplayHardware() {
2770 return *mHw;
2771 }
2772
transform() const2773 const Transform& GraphicPlane::transform() const {
2774 return mGlobalTransform;
2775 }
2776
getEGLDisplay() const2777 EGLDisplay GraphicPlane::getEGLDisplay() const {
2778 return mHw->getEGLDisplay();
2779 }
2780
2781 // ---------------------------------------------------------------------------
2782
2783 }; // namespace android
2784