blob: d915a8424b6db6fef724ca188d9e8ea752b49731 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "SurfaceFlinger"
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 <sys/types.h>
27#include <sys/stat.h>
28#include <sys/ioctl.h>
29
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
33#include <utils/IPCThreadState.h>
34#include <utils/IServiceManager.h>
35#include <utils/MemoryDealer.h>
36#include <utils/MemoryBase.h>
37#include <utils/String8.h>
38#include <utils/String16.h>
39#include <utils/StopWatch.h>
40
41#include <ui/PixelFormat.h>
42#include <ui/DisplayInfo.h>
43#include <ui/EGLDisplaySurface.h>
44
45#include <pixelflinger/pixelflinger.h>
46#include <GLES/gl.h>
47
48#include "clz.h"
49#include "CPUGauge.h"
50#include "Layer.h"
51#include "LayerBlur.h"
52#include "LayerBuffer.h"
53#include "LayerDim.h"
54#include "LayerBitmap.h"
55#include "LayerOrientationAnim.h"
56#include "OrientationAnimation.h"
57#include "SurfaceFlinger.h"
58#include "VRamHeap.h"
59
60#include "DisplayHardware/DisplayHardware.h"
61#include "GPUHardware/GPUHardware.h"
62
63
64#define DISPLAY_COUNT 1
65
66namespace android {
67
68// ---------------------------------------------------------------------------
69
70void SurfaceFlinger::instantiate() {
71 defaultServiceManager()->addService(
72 String16("SurfaceFlinger"), new SurfaceFlinger());
73}
74
75void SurfaceFlinger::shutdown() {
76 // we should unregister here, but not really because
77 // when (if) the service manager goes away, all the services
78 // it has a reference to will leave too.
79}
80
81// ---------------------------------------------------------------------------
82
83SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
84 : lookup(rhs.lookup), layers(rhs.layers)
85{
86}
87
88ssize_t SurfaceFlinger::LayerVector::indexOf(
89 LayerBase* key, size_t guess) const
90{
91 if (guess<size() && lookup.keyAt(guess) == key)
92 return guess;
93 const ssize_t i = lookup.indexOfKey(key);
94 if (i>=0) {
95 const size_t idx = lookup.valueAt(i);
96 LOG_ASSERT(layers[idx]==key,
97 "LayerVector[%p]: layers[%d]=%p, key=%p",
98 this, int(idx), layers[idx], key);
99 return idx;
100 }
101 return i;
102}
103
104ssize_t SurfaceFlinger::LayerVector::add(
105 LayerBase* layer,
106 Vector<LayerBase*>::compar_t cmp)
107{
108 size_t count = layers.size();
109 ssize_t l = 0;
110 ssize_t h = count-1;
111 ssize_t mid;
112 LayerBase* const* a = layers.array();
113 while (l <= h) {
114 mid = l + (h - l)/2;
115 const int c = cmp(a+mid, &layer);
116 if (c == 0) { l = mid; break; }
117 else if (c<0) { l = mid+1; }
118 else { h = mid-1; }
119 }
120 size_t order = l;
121 while (order<count && !cmp(&layer, a+order)) {
122 order++;
123 }
124 count = lookup.size();
125 for (size_t i=0 ; i<count ; i++) {
126 if (lookup.valueAt(i) >= order) {
127 lookup.editValueAt(i)++;
128 }
129 }
130 layers.insertAt(layer, order);
131 lookup.add(layer, order);
132 return order;
133}
134
135ssize_t SurfaceFlinger::LayerVector::remove(LayerBase* layer)
136{
137 const ssize_t keyIndex = lookup.indexOfKey(layer);
138 if (keyIndex >= 0) {
139 const size_t index = lookup.valueAt(keyIndex);
140 LOG_ASSERT(layers[index]==layer,
141 "LayerVector[%p]: layers[%u]=%p, layer=%p",
142 this, int(index), layers[index], layer);
143 layers.removeItemsAt(index);
144 lookup.removeItemsAt(keyIndex);
145 const size_t count = lookup.size();
146 for (size_t i=0 ; i<count ; i++) {
147 if (lookup.valueAt(i) >= size_t(index)) {
148 lookup.editValueAt(i)--;
149 }
150 }
151 return index;
152 }
153 return NAME_NOT_FOUND;
154}
155
156ssize_t SurfaceFlinger::LayerVector::reorder(
157 LayerBase* layer,
158 Vector<LayerBase*>::compar_t cmp)
159{
160 // XXX: it's a little lame. but oh well...
161 ssize_t err = remove(layer);
162 if (err >=0)
163 err = add(layer, cmp);
164 return err;
165}
166
167// ---------------------------------------------------------------------------
168#if 0
169#pragma mark -
170#endif
171
172SurfaceFlinger::SurfaceFlinger()
173 : BnSurfaceComposer(), Thread(false),
174 mTransactionFlags(0),
175 mTransactionCount(0),
176 mBootTime(systemTime()),
177 mLastScheduledBroadcast(NULL),
178 mVisibleRegionsDirty(false),
179 mDeferReleaseConsole(false),
180 mFreezeDisplay(false),
181 mFreezeCount(0),
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700182 mFreezeDisplayTime(0),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 mDebugRegion(0),
184 mDebugCpu(0),
185 mDebugFps(0),
186 mDebugBackground(0),
187 mDebugNoBootAnimation(0),
188 mSyncObject(),
189 mDeplayedTransactionPending(0),
190 mConsoleSignals(0),
191 mSecureFrameBuffer(0)
192{
193 init();
194}
195
196void SurfaceFlinger::init()
197{
198 LOGI("SurfaceFlinger is starting");
199
200 // debugging stuff...
201 char value[PROPERTY_VALUE_MAX];
202 property_get("debug.sf.showupdates", value, "0");
203 mDebugRegion = atoi(value);
204 property_get("debug.sf.showcpu", value, "0");
205 mDebugCpu = atoi(value);
206 property_get("debug.sf.showbackground", value, "0");
207 mDebugBackground = atoi(value);
208 property_get("debug.sf.showfps", value, "0");
209 mDebugFps = atoi(value);
210 property_get("debug.sf.nobootanimation", value, "0");
211 mDebugNoBootAnimation = atoi(value);
212
213 LOGI_IF(mDebugRegion, "showupdates enabled");
214 LOGI_IF(mDebugCpu, "showcpu enabled");
215 LOGI_IF(mDebugBackground, "showbackground enabled");
216 LOGI_IF(mDebugFps, "showfps enabled");
217 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
218}
219
220SurfaceFlinger::~SurfaceFlinger()
221{
222 glDeleteTextures(1, &mWormholeTexName);
223 delete mOrientationAnimation;
224}
225
226copybit_device_t* SurfaceFlinger::getBlitEngine() const
227{
228 return graphicPlane(0).displayHardware().getBlitEngine();
229}
230
231overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
232{
233 return graphicPlane(0).displayHardware().getOverlayEngine();
234}
235
236sp<IMemory> SurfaceFlinger::getCblk() const
237{
238 return mServerCblkMemory;
239}
240
241status_t SurfaceFlinger::requestGPU(const sp<IGPUCallback>& callback,
242 gpu_info_t* gpu)
243{
244 IPCThreadState* ipc = IPCThreadState::self();
245 const int pid = ipc->getCallingPid();
246 status_t err = mGPU->request(pid, callback, gpu);
247 return err;
248}
249
250status_t SurfaceFlinger::revokeGPU()
251{
252 return mGPU->friendlyRevoke();
253}
254
255sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
256{
257 Mutex::Autolock _l(mStateLock);
258 uint32_t token = mTokens.acquire();
259
260 Client* client = new Client(token, this);
261 if ((client == 0) || (client->ctrlblk == 0)) {
262 mTokens.release(token);
263 return 0;
264 }
265 status_t err = mClientsMap.add(token, client);
266 if (err < 0) {
267 delete client;
268 mTokens.release(token);
269 return 0;
270 }
271 sp<BClient> bclient =
272 new BClient(this, token, client->controlBlockMemory());
273 return bclient;
274}
275
276void SurfaceFlinger::destroyConnection(ClientID cid)
277{
278 Mutex::Autolock _l(mStateLock);
279 Client* const client = mClientsMap.valueFor(cid);
280 if (client) {
281 // free all the layers this client owns
282 const Vector<LayerBaseClient*>& layers = client->getLayers();
283 const size_t count = layers.size();
284 for (size_t i=0 ; i<count ; i++) {
285 LayerBaseClient* const layer = layers[i];
286 removeLayer_l(layer);
287 }
288
289 // the resources associated with this client will be freed
290 // during the next transaction, after these surfaces have been
291 // properly removed from the screen
292
293 // remove this client from our ClientID->Client mapping.
294 mClientsMap.removeItem(cid);
295
296 // and add it to the list of disconnected clients
297 mDisconnectedClients.add(client);
298
299 // request a transaction
300 setTransactionFlags(eTransactionNeeded);
301 }
302}
303
304const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
305{
306 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
307 const GraphicPlane& plane(mGraphicPlanes[dpy]);
308 return plane;
309}
310
311GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
312{
313 return const_cast<GraphicPlane&>(
314 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
315}
316
317void SurfaceFlinger::bootFinished()
318{
319 const nsecs_t now = systemTime();
320 const nsecs_t duration = now - mBootTime;
321 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
322 if (mBootAnimation != 0) {
323 mBootAnimation->requestExit();
324 mBootAnimation.clear();
325 }
326}
327
328void SurfaceFlinger::onFirstRef()
329{
330 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
331
332 // Wait for the main thread to be done with its initialization
333 mReadyToRunBarrier.wait();
334}
335
336
337static inline uint16_t pack565(int r, int g, int b) {
338 return (r<<11)|(g<<5)|b;
339}
340
341// this is defined in libGLES_CM.so
342extern ISurfaceComposer* GLES_localSurfaceManager;
343
344status_t SurfaceFlinger::readyToRun()
345{
346 LOGI( "SurfaceFlinger's main thread ready to run. "
347 "Initializing graphics H/W...");
348
349 // create the shared control-block
350 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
351 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
352
353 mServerCblkMemory = mServerHeap->allocate(4096);
354 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
355
356 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
357 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
358 new(mServerCblk) surface_flinger_cblk_t;
359
360 // get a reference to the GPU if we have one
361 mGPU = GPUFactory::getGPU();
362
363 // create the surface Heap manager, which manages the heaps
364 // (be it in RAM or VRAM) where surfaces are allocated
365 // We give 8 MB per client.
366 mSurfaceHeapManager = new SurfaceHeapManager(this, 8 << 20);
367
368
369 GLES_localSurfaceManager = static_cast<ISurfaceComposer*>(this);
370
371 // we only support one display currently
372 int dpy = 0;
373
374 {
375 // initialize the main display
376 GraphicPlane& plane(graphicPlane(dpy));
377 DisplayHardware* const hw = new DisplayHardware(this, dpy);
378 plane.setDisplayHardware(hw);
379 }
380
381 // initialize primary screen
382 // (other display should be initialized in the same manner, but
383 // asynchronously, as they could come and go. None of this is supported
384 // yet).
385 const GraphicPlane& plane(graphicPlane(dpy));
386 const DisplayHardware& hw = plane.displayHardware();
387 const uint32_t w = hw.getWidth();
388 const uint32_t h = hw.getHeight();
389 const uint32_t f = hw.getFormat();
390 hw.makeCurrent();
391
392 // initialize the shared control block
393 mServerCblk->connected |= 1<<dpy;
394 display_cblk_t* dcblk = mServerCblk->displays + dpy;
395 memset(dcblk, 0, sizeof(display_cblk_t));
396 dcblk->w = w;
397 dcblk->h = h;
398 dcblk->format = f;
399 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
400 dcblk->xdpi = hw.getDpiX();
401 dcblk->ydpi = hw.getDpiY();
402 dcblk->fps = hw.getRefreshRate();
403 dcblk->density = hw.getDensity();
404 asm volatile ("":::"memory");
405
406 // Initialize OpenGL|ES
407 glActiveTexture(GL_TEXTURE0);
408 glBindTexture(GL_TEXTURE_2D, 0);
409 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
410 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
411 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
412 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
413 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
414 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
415 glPixelStorei(GL_PACK_ALIGNMENT, 4);
416 glEnableClientState(GL_VERTEX_ARRAY);
417 glEnable(GL_SCISSOR_TEST);
418 glShadeModel(GL_FLAT);
419 glDisable(GL_DITHER);
420 glDisable(GL_CULL_FACE);
421
422 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
423 const uint16_t g1 = pack565(0x17,0x2f,0x17);
424 const uint16_t textureData[4] = { g0, g1, g1, g0 };
425 glGenTextures(1, &mWormholeTexName);
426 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
427 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
428 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
429 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
430 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
431 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
432 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
433
434 glViewport(0, 0, w, h);
435 glMatrixMode(GL_PROJECTION);
436 glLoadIdentity();
437 glOrthof(0, w, h, 0, 0, 1);
438
439 LayerDim::initDimmer(this, w, h);
440
441 mReadyToRunBarrier.open();
442
443 /*
444 * We're now ready to accept clients...
445 */
446
447 mOrientationAnimation = new OrientationAnimation(this);
448
449 // start CPU gauge display
450 if (mDebugCpu)
451 mCpuGauge = new CPUGauge(this, ms2ns(500));
452
453 // the boot animation!
454 if (mDebugNoBootAnimation == false)
455 mBootAnimation = new BootAnimation(this);
456
457 return NO_ERROR;
458}
459
460// ----------------------------------------------------------------------------
461#if 0
462#pragma mark -
463#pragma mark Events Handler
464#endif
465
466void SurfaceFlinger::waitForEvent()
467{
468 // wait for something to do
469 if (UNLIKELY(isFrozen())) {
470 // wait 5 seconds
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700471 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
472 const nsecs_t now = systemTime();
473 if (mFreezeDisplayTime == 0) {
474 mFreezeDisplayTime = now;
475 }
476 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
477 int err = (waitTime > 0) ? mSyncObject.wait(waitTime) : TIMED_OUT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 if (err != NO_ERROR) {
479 if (isFrozen()) {
480 // we timed out and are still frozen
481 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
482 mFreezeDisplay, mFreezeCount);
483 mFreezeCount = 0;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700484 mFreezeDisplay = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 }
486 }
487 } else {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700488 mFreezeDisplayTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 mSyncObject.wait();
490 }
491}
492
493void SurfaceFlinger::signalEvent() {
494 mSyncObject.open();
495}
496
497void SurfaceFlinger::signal() const {
498 mSyncObject.open();
499}
500
501void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
502{
503 if (android_atomic_or(1, &mDeplayedTransactionPending) == 0) {
504 sp<DelayedTransaction> delayedEvent(new DelayedTransaction(this, delay));
505 delayedEvent->run("DelayedeEvent", PRIORITY_URGENT_DISPLAY);
506 }
507}
508
509// ----------------------------------------------------------------------------
510#if 0
511#pragma mark -
512#pragma mark Main loop
513#endif
514
515bool SurfaceFlinger::threadLoop()
516{
517 waitForEvent();
518
519 // check for transactions
520 if (UNLIKELY(mConsoleSignals)) {
521 handleConsoleEvents();
522 }
523
524 if (LIKELY(mTransactionCount == 0)) {
525 // if we're in a global transaction, don't do anything.
526 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
527 uint32_t transactionFlags = getTransactionFlags(mask);
528 if (LIKELY(transactionFlags)) {
529 handleTransaction(transactionFlags);
530 }
531 }
532
533 // post surfaces (if needed)
534 handlePageFlip();
535
536 const DisplayHardware& hw(graphicPlane(0).displayHardware());
537 if (LIKELY(hw.canDraw())) {
538 // repaint the framebuffer (if needed)
539 handleRepaint();
540
541 // release the clients before we flip ('cause flip might block)
542 unlockClients();
543 executeScheduledBroadcasts();
544
545 // sample the cpu gauge
546 if (UNLIKELY(mDebugCpu)) {
547 handleDebugCpu();
548 }
549
550 postFramebuffer();
551 } else {
552 // pretend we did the post
553 unlockClients();
554 executeScheduledBroadcasts();
555 usleep(16667); // 60 fps period
556 }
557 return true;
558}
559
560void SurfaceFlinger::postFramebuffer()
561{
562 const bool skip = mOrientationAnimation->run();
563 if (UNLIKELY(skip)) {
564 return;
565 }
566
567 if (!mInvalidRegion.isEmpty()) {
568 const DisplayHardware& hw(graphicPlane(0).displayHardware());
569
570 if (UNLIKELY(mDebugFps)) {
571 debugShowFPS();
572 }
573
574 hw.flip(mInvalidRegion);
575
576 mInvalidRegion.clear();
577
578 if (Layer::deletedTextures.size()) {
579 glDeleteTextures(
580 Layer::deletedTextures.size(),
581 Layer::deletedTextures.array());
582 Layer::deletedTextures.clear();
583 }
584 }
585}
586
587void SurfaceFlinger::handleConsoleEvents()
588{
589 // something to do with the console
590 const DisplayHardware& hw = graphicPlane(0).displayHardware();
591
592 int what = android_atomic_and(0, &mConsoleSignals);
593 if (what & eConsoleAcquired) {
594 hw.acquireScreen();
595 }
596
597 if (mDeferReleaseConsole && hw.canDraw()) {
598 // We got the release signal before the aquire signal
599 mDeferReleaseConsole = false;
600 revokeGPU();
601 hw.releaseScreen();
602 }
603
604 if (what & eConsoleReleased) {
605 if (hw.canDraw()) {
606 revokeGPU();
607 hw.releaseScreen();
608 } else {
609 mDeferReleaseConsole = true;
610 }
611 }
612
613 mDirtyRegion.set(hw.bounds());
614}
615
616void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
617{
618 Mutex::Autolock _l(mStateLock);
619
620 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
621 const size_t count = currentLayers.size();
622
623 /*
624 * Traversal of the children
625 * (perform the transaction for each of them if needed)
626 */
627
628 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
629 if (layersNeedTransaction) {
630 for (size_t i=0 ; i<count ; i++) {
631 LayerBase* const layer = currentLayers[i];
632 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
633 if (!trFlags) continue;
634
635 const uint32_t flags = layer->doTransaction(0);
636 if (flags & Layer::eVisibleRegion)
637 mVisibleRegionsDirty = true;
638
639 if (flags & Layer::eRestartTransaction) {
640 // restart the transaction, but back-off a little
641 layer->setTransactionFlags(eTransactionNeeded);
642 setTransactionFlags(eTraversalNeeded, ms2ns(8));
643 }
644 }
645 }
646
647 /*
648 * Perform our own transaction if needed
649 */
650
651 if (transactionFlags & eTransactionNeeded) {
652 if (mCurrentState.orientation != mDrawingState.orientation) {
653 // the orientation has changed, recompute all visible regions
654 // and invalidate everything.
655
656 const int dpy = 0;
657 const int orientation = mCurrentState.orientation;
658 GraphicPlane& plane(graphicPlane(dpy));
659 plane.setOrientation(orientation);
660
661 // update the shared control block
662 const DisplayHardware& hw(plane.displayHardware());
663 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
664 dcblk->orientation = orientation;
665 if (orientation & eOrientationSwapMask) {
666 // 90 or 270 degrees orientation
667 dcblk->w = hw.getHeight();
668 dcblk->h = hw.getWidth();
669 } else {
670 dcblk->w = hw.getWidth();
671 dcblk->h = hw.getHeight();
672 }
673
674 mVisibleRegionsDirty = true;
675 mDirtyRegion.set(hw.bounds());
676
677 mOrientationAnimation->onOrientationChanged();
678 }
679
680 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
681 // freezing or unfreezing the display -> trigger animation if needed
682 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684
685 // some layers might have been removed, so
686 // we need to update the regions they're exposing.
687 size_t c = mRemovedLayers.size();
688 if (c) {
689 mVisibleRegionsDirty = true;
690 }
691
692 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
693 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
694 // layers have been added
695 mVisibleRegionsDirty = true;
696 }
697
698 // get rid of all resources we don't need anymore
699 // (layers and clients)
700 free_resources_l();
701 }
702
703 commitTransaction();
704}
705
706sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
707{
708 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
709}
710
711void SurfaceFlinger::computeVisibleRegions(
712 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
713{
714 const GraphicPlane& plane(graphicPlane(0));
715 const Transform& planeTransform(plane.transform());
716
717 Region aboveOpaqueLayers;
718 Region aboveCoveredLayers;
719 Region dirty;
720
721 bool secureFrameBuffer = false;
722
723 size_t i = currentLayers.size();
724 while (i--) {
725 LayerBase* const layer = currentLayers[i];
726 layer->validateVisibility(planeTransform);
727
728 // start with the whole surface at its current location
729 const Layer::State& s = layer->drawingState();
730 const Rect bounds(layer->visibleBounds());
731
732 // handle hidden surfaces by setting the visible region to empty
733 Region opaqueRegion;
734 Region visibleRegion;
735 Region coveredRegion;
736 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
737 visibleRegion.clear();
738 } else {
739 const bool translucent = layer->needsBlending();
740 visibleRegion.set(bounds);
741 coveredRegion = visibleRegion;
742
743 // Remove the transparent area from the visible region
744 if (translucent) {
745 visibleRegion.subtractSelf(layer->transparentRegionScreen);
746 }
747
748 // compute the opaque region
749 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
750 // the opaque region is the visible region
751 opaqueRegion = visibleRegion;
752 }
753 }
754
755 // subtract the opaque region covered by the layers above us
756 visibleRegion.subtractSelf(aboveOpaqueLayers);
757 coveredRegion.andSelf(aboveCoveredLayers);
758
759 // compute this layer's dirty region
760 if (layer->contentDirty) {
761 // we need to invalidate the whole region
762 dirty = visibleRegion;
763 // as well, as the old visible region
764 dirty.orSelf(layer->visibleRegionScreen);
765 layer->contentDirty = false;
766 } else {
767 // compute the exposed region
768 // dirty = what's visible now - what's wasn't covered before
769 // = what's visible now & what's was covered before
770 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
771 }
772 dirty.subtractSelf(aboveOpaqueLayers);
773
774 // accumulate to the screen dirty region
775 dirtyRegion.orSelf(dirty);
776
777 // updade aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
778 aboveOpaqueLayers.orSelf(opaqueRegion);
779 aboveCoveredLayers.orSelf(bounds);
780
781 // Store the visible region is screen space
782 layer->setVisibleRegion(visibleRegion);
783 layer->setCoveredRegion(coveredRegion);
784
785 // If a secure layer is partially visible, lockdown the screen!
786 if (layer->isSecure() && !visibleRegion.isEmpty()) {
787 secureFrameBuffer = true;
788 }
789 }
790
791 mSecureFrameBuffer = secureFrameBuffer;
792 opaqueRegion = aboveOpaqueLayers;
793}
794
795
796void SurfaceFlinger::commitTransaction()
797{
798 mDrawingState = mCurrentState;
799 mTransactionCV.signal();
800}
801
802void SurfaceFlinger::handlePageFlip()
803{
804 bool visibleRegions = mVisibleRegionsDirty;
805 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
806 visibleRegions |= lockPageFlip(currentLayers);
807
808 const DisplayHardware& hw = graphicPlane(0).displayHardware();
809 const Region screenRegion(hw.bounds());
810 if (visibleRegions) {
811 Region opaqueRegion;
812 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
813 mWormholeRegion = screenRegion.subtract(opaqueRegion);
814 mVisibleRegionsDirty = false;
815 }
816
817 unlockPageFlip(currentLayers);
818 mDirtyRegion.andSelf(screenRegion);
819}
820
821bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
822{
823 bool recomputeVisibleRegions = false;
824 size_t count = currentLayers.size();
825 LayerBase* const* layers = currentLayers.array();
826 for (size_t i=0 ; i<count ; i++) {
827 LayerBase* const layer = layers[i];
828 layer->lockPageFlip(recomputeVisibleRegions);
829 }
830 return recomputeVisibleRegions;
831}
832
833void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
834{
835 const GraphicPlane& plane(graphicPlane(0));
836 const Transform& planeTransform(plane.transform());
837 size_t count = currentLayers.size();
838 LayerBase* const* layers = currentLayers.array();
839 for (size_t i=0 ; i<count ; i++) {
840 LayerBase* const layer = layers[i];
841 layer->unlockPageFlip(planeTransform, mDirtyRegion);
842 }
843}
844
845void SurfaceFlinger::handleRepaint()
846{
847 // set the frame buffer
848 const DisplayHardware& hw(graphicPlane(0).displayHardware());
849 glMatrixMode(GL_MODELVIEW);
850 glLoadIdentity();
851
852 if (UNLIKELY(mDebugRegion)) {
853 debugFlashRegions();
854 }
855
856 // compute the invalid region
857 mInvalidRegion.orSelf(mDirtyRegion);
858
859 uint32_t flags = hw.getFlags();
860 if (flags & DisplayHardware::BUFFER_PRESERVED) {
861 // here we assume DisplayHardware::flip()'s implementation
862 // performs the copy-back optimization.
863 } else {
864 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
865 // we need to fully redraw the part that will be updated
866 mDirtyRegion.set(mInvalidRegion.bounds());
867 } else {
868 // we need to redraw everything
869 mDirtyRegion.set(hw.bounds());
870 mInvalidRegion = mDirtyRegion;
871 }
872 }
873
874 // compose all surfaces
875 composeSurfaces(mDirtyRegion);
876
877 // clear the dirty regions
878 mDirtyRegion.clear();
879}
880
881void SurfaceFlinger::composeSurfaces(const Region& dirty)
882{
883 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
884 // should never happen unless the window manager has a bug
885 // draw something...
886 drawWormhole();
887 }
888 const SurfaceFlinger& flinger(*this);
889 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
890 const size_t count = drawingLayers.size();
891 LayerBase const* const* const layers = drawingLayers.array();
892 for (size_t i=0 ; i<count ; ++i) {
893 LayerBase const * const layer = layers[i];
894 const Region& visibleRegion(layer->visibleRegionScreen);
895 if (!visibleRegion.isEmpty()) {
896 const Region clip(dirty.intersect(visibleRegion));
897 if (!clip.isEmpty()) {
898 layer->draw(clip);
899 }
900 }
901 }
902}
903
904void SurfaceFlinger::unlockClients()
905{
906 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
907 const size_t count = drawingLayers.size();
908 LayerBase* const* const layers = drawingLayers.array();
909 for (size_t i=0 ; i<count ; ++i) {
910 LayerBase* const layer = layers[i];
911 layer->finishPageFlip();
912 }
913}
914
915void SurfaceFlinger::scheduleBroadcast(Client* client)
916{
917 if (mLastScheduledBroadcast != client) {
918 mLastScheduledBroadcast = client;
919 mScheduledBroadcasts.add(client);
920 }
921}
922
923void SurfaceFlinger::executeScheduledBroadcasts()
924{
925 SortedVector<Client*>& list = mScheduledBroadcasts;
926 size_t count = list.size();
927 while (count--) {
928 per_client_cblk_t* const cblk = list[count]->ctrlblk;
929 if (cblk->lock.tryLock() == NO_ERROR) {
930 cblk->cv.broadcast();
931 list.removeAt(count);
932 cblk->lock.unlock();
933 } else {
934 // schedule another round
935 LOGW("executeScheduledBroadcasts() skipped, "
936 "contention on the client. We'll try again later...");
937 signalDelayedEvent(ms2ns(4));
938 }
939 }
940 mLastScheduledBroadcast = 0;
941}
942
943void SurfaceFlinger::handleDebugCpu()
944{
945 Mutex::Autolock _l(mDebugLock);
946 if (mCpuGauge != 0)
947 mCpuGauge->sample();
948}
949
950void SurfaceFlinger::debugFlashRegions()
951{
952 if (UNLIKELY(!mDirtyRegion.isRect())) {
953 // TODO: do this only if we don't have preserving
954 // swapBuffer. If we don't have update-on-demand,
955 // redraw everything.
956 composeSurfaces(Region(mDirtyRegion.bounds()));
957 }
958
959 glDisable(GL_TEXTURE_2D);
960 glDisable(GL_BLEND);
961 glDisable(GL_DITHER);
962 glDisable(GL_SCISSOR_TEST);
963
964 glColor4x(0x10000, 0, 0x10000, 0x10000);
965
966 Rect r;
967 Region::iterator iterator(mDirtyRegion);
968 while (iterator.iterate(&r)) {
969 GLfloat vertices[][2] = {
970 { r.left, r.top },
971 { r.left, r.bottom },
972 { r.right, r.bottom },
973 { r.right, r.top }
974 };
975 glVertexPointer(2, GL_FLOAT, 0, vertices);
976 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
977 }
978
979 const DisplayHardware& hw(graphicPlane(0).displayHardware());
980 hw.flip(mDirtyRegion.merge(mInvalidRegion));
981 mInvalidRegion.clear();
982
983 if (mDebugRegion > 1)
984 usleep(mDebugRegion * 1000);
985
986 glEnable(GL_SCISSOR_TEST);
987 //mDirtyRegion.dump("mDirtyRegion");
988}
989
990void SurfaceFlinger::drawWormhole() const
991{
992 const Region region(mWormholeRegion.intersect(mDirtyRegion));
993 if (region.isEmpty())
994 return;
995
996 const DisplayHardware& hw(graphicPlane(0).displayHardware());
997 const int32_t width = hw.getWidth();
998 const int32_t height = hw.getHeight();
999
1000 glDisable(GL_BLEND);
1001 glDisable(GL_DITHER);
1002
1003 if (LIKELY(!mDebugBackground)) {
1004 glClearColorx(0,0,0,0);
1005 Rect r;
1006 Region::iterator iterator(region);
1007 while (iterator.iterate(&r)) {
1008 const GLint sy = height - (r.top + r.height());
1009 glScissor(r.left, sy, r.width(), r.height());
1010 glClear(GL_COLOR_BUFFER_BIT);
1011 }
1012 } else {
1013 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1014 { width, height }, { 0, height } };
1015 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
1016 glVertexPointer(2, GL_SHORT, 0, vertices);
1017 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1018 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1019 glEnable(GL_TEXTURE_2D);
1020 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1021 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1022 glMatrixMode(GL_TEXTURE);
1023 glLoadIdentity();
1024 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1025 Rect r;
1026 Region::iterator iterator(region);
1027 while (iterator.iterate(&r)) {
1028 const GLint sy = height - (r.top + r.height());
1029 glScissor(r.left, sy, r.width(), r.height());
1030 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1031 }
1032 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1033 }
1034}
1035
1036void SurfaceFlinger::debugShowFPS() const
1037{
1038 static int mFrameCount;
1039 static int mLastFrameCount = 0;
1040 static nsecs_t mLastFpsTime = 0;
1041 static float mFps = 0;
1042 mFrameCount++;
1043 nsecs_t now = systemTime();
1044 nsecs_t diff = now - mLastFpsTime;
1045 if (diff > ms2ns(250)) {
1046 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1047 mLastFpsTime = now;
1048 mLastFrameCount = mFrameCount;
1049 }
1050 // XXX: mFPS has the value we want
1051 }
1052
1053status_t SurfaceFlinger::addLayer(LayerBase* layer)
1054{
1055 Mutex::Autolock _l(mStateLock);
1056 addLayer_l(layer);
1057 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1058 return NO_ERROR;
1059}
1060
1061status_t SurfaceFlinger::removeLayer(LayerBase* layer)
1062{
1063 Mutex::Autolock _l(mStateLock);
1064 removeLayer_l(layer);
1065 setTransactionFlags(eTransactionNeeded);
1066 return NO_ERROR;
1067}
1068
1069status_t SurfaceFlinger::invalidateLayerVisibility(LayerBase* layer)
1070{
1071 layer->forceVisibilityTransaction();
1072 setTransactionFlags(eTraversalNeeded);
1073 return NO_ERROR;
1074}
1075
1076status_t SurfaceFlinger::addLayer_l(LayerBase* layer)
1077{
1078 ssize_t i = mCurrentState.layersSortedByZ.add(
1079 layer, &LayerBase::compareCurrentStateZ);
1080 LayerBaseClient* lbc = LayerBase::dynamicCast<LayerBaseClient*>(layer);
1081 if (lbc) {
1082 mLayerMap.add(lbc->serverIndex(), lbc);
1083 }
1084 mRemovedLayers.remove(layer);
1085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::removeLayer_l(LayerBase* layerBase)
1089{
1090 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1091 if (index >= 0) {
1092 mRemovedLayers.add(layerBase);
1093 LayerBaseClient* layer = LayerBase::dynamicCast<LayerBaseClient*>(layerBase);
1094 if (layer) {
1095 mLayerMap.removeItem(layer->serverIndex());
1096 }
1097 return NO_ERROR;
1098 }
1099 // it's possible that we don't find a layer, because it might
1100 // have been destroyed already -- this is not technically an error
1101 // from the user because there is a race between destroySurface,
1102 // destroyclient and destroySurface-from-a-transaction.
1103 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1104}
1105
1106void SurfaceFlinger::free_resources_l()
1107{
1108 // Destroy layers that were removed
1109 destroy_all_removed_layers_l();
1110
1111 // free resources associated with disconnected clients
1112 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1113 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1114 const size_t count = disconnectedClients.size();
1115 for (size_t i=0 ; i<count ; i++) {
1116 Client* client = disconnectedClients[i];
1117 // if this client is the scheduled broadcast list,
1118 // remove it from there (and we don't need to signal it
1119 // since it is dead).
1120 int32_t index = scheduledBroadcasts.indexOf(client);
1121 if (index >= 0) {
1122 scheduledBroadcasts.removeItemsAt(index);
1123 }
1124 mTokens.release(client->cid);
1125 delete client;
1126 }
1127 disconnectedClients.clear();
1128}
1129
1130void SurfaceFlinger::destroy_all_removed_layers_l()
1131{
1132 size_t c = mRemovedLayers.size();
1133 while (c--) {
1134 LayerBase* const removed_layer = mRemovedLayers[c];
1135
1136 LOGE_IF(mCurrentState.layersSortedByZ.indexOf(removed_layer) >= 0,
1137 "layer %p removed but still in the current state list",
1138 removed_layer);
1139
1140 delete removed_layer;
1141 }
1142 mRemovedLayers.clear();
1143}
1144
1145
1146uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1147{
1148 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1149}
1150
1151uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1152{
1153 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1154 if ((old & flags)==0) { // wake the server up
1155 if (delay > 0) {
1156 signalDelayedEvent(delay);
1157 } else {
1158 signalEvent();
1159 }
1160 }
1161 return old;
1162}
1163
1164void SurfaceFlinger::openGlobalTransaction()
1165{
1166 android_atomic_inc(&mTransactionCount);
1167}
1168
1169void SurfaceFlinger::closeGlobalTransaction()
1170{
1171 if (android_atomic_dec(&mTransactionCount) == 1) {
1172 signalEvent();
1173 }
1174}
1175
1176status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1177{
1178 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1179 return BAD_VALUE;
1180
1181 Mutex::Autolock _l(mStateLock);
1182 mCurrentState.freezeDisplay = 1;
1183 setTransactionFlags(eTransactionNeeded);
1184
1185 // flags is intended to communicate some sort of animation behavior
1186 // (for instance fadding)
1187 return NO_ERROR;
1188}
1189
1190status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1191{
1192 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1193 return BAD_VALUE;
1194
1195 Mutex::Autolock _l(mStateLock);
1196 mCurrentState.freezeDisplay = 0;
1197 setTransactionFlags(eTransactionNeeded);
1198
1199 // flags is intended to communicate some sort of animation behavior
1200 // (for instance fadding)
1201 return NO_ERROR;
1202}
1203
1204int SurfaceFlinger::setOrientation(DisplayID dpy, int orientation)
1205{
1206 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1207 return BAD_VALUE;
1208
1209 Mutex::Autolock _l(mStateLock);
1210 if (mCurrentState.orientation != orientation) {
1211 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1212 mCurrentState.orientation = orientation;
1213 setTransactionFlags(eTransactionNeeded);
1214 mTransactionCV.wait(mStateLock);
1215 } else {
1216 orientation = BAD_VALUE;
1217 }
1218 }
1219 return orientation;
1220}
1221
1222sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1223 ISurfaceFlingerClient::surface_data_t* params,
1224 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1225 uint32_t flags)
1226{
1227 LayerBaseClient* layer = 0;
1228 sp<LayerBaseClient::Surface> surfaceHandle;
1229 Mutex::Autolock _l(mStateLock);
1230 Client* const c = mClientsMap.valueFor(clientId);
1231 if (UNLIKELY(!c)) {
1232 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1233 return surfaceHandle;
1234 }
1235
1236 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1237 int32_t id = c->generateId(pid);
1238 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1239 LOGE("createSurface() failed, generateId = %d", id);
1240 return surfaceHandle;
1241 }
1242
1243 switch (flags & eFXSurfaceMask) {
1244 case eFXSurfaceNormal:
1245 if (UNLIKELY(flags & ePushBuffers)) {
1246 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1247 } else {
1248 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1249 }
1250 break;
1251 case eFXSurfaceBlur:
1252 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1253 break;
1254 case eFXSurfaceDim:
1255 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1256 break;
1257 }
1258
1259 if (layer) {
1260 setTransactionFlags(eTransactionNeeded);
1261 surfaceHandle = layer->getSurface();
1262 if (surfaceHandle != 0)
1263 surfaceHandle->getSurfaceData(params);
1264 }
1265
1266 return surfaceHandle;
1267}
1268
1269LayerBaseClient* SurfaceFlinger::createNormalSurfaceLocked(
1270 Client* client, DisplayID display,
1271 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1272{
1273 // initialize the surfaces
1274 switch (format) { // TODO: take h/w into account
1275 case PIXEL_FORMAT_TRANSPARENT:
1276 case PIXEL_FORMAT_TRANSLUCENT:
1277 format = PIXEL_FORMAT_RGBA_8888;
1278 break;
1279 case PIXEL_FORMAT_OPAQUE:
1280 format = PIXEL_FORMAT_RGB_565;
1281 break;
1282 }
1283
1284 Layer* layer = new Layer(this, display, client, id);
1285 status_t err = layer->setBuffers(client, w, h, format, flags);
1286 if (LIKELY(err == NO_ERROR)) {
1287 layer->initStates(w, h, flags);
1288 addLayer_l(layer);
1289 } else {
1290 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1291 delete layer;
1292 return 0;
1293 }
1294 return layer;
1295}
1296
1297LayerBaseClient* SurfaceFlinger::createBlurSurfaceLocked(
1298 Client* client, DisplayID display,
1299 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1300{
1301 LayerBlur* layer = new LayerBlur(this, display, client, id);
1302 layer->initStates(w, h, flags);
1303 addLayer_l(layer);
1304 return layer;
1305}
1306
1307LayerBaseClient* SurfaceFlinger::createDimSurfaceLocked(
1308 Client* client, DisplayID display,
1309 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1310{
1311 LayerDim* layer = new LayerDim(this, display, client, id);
1312 layer->initStates(w, h, flags);
1313 addLayer_l(layer);
1314 return layer;
1315}
1316
1317LayerBaseClient* SurfaceFlinger::createPushBuffersSurfaceLocked(
1318 Client* client, DisplayID display,
1319 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1320{
1321 LayerBuffer* layer = new LayerBuffer(this, display, client, id);
1322 layer->initStates(w, h, flags);
1323 addLayer_l(layer);
1324 return layer;
1325}
1326
1327status_t SurfaceFlinger::destroySurface(SurfaceID index)
1328{
1329 Mutex::Autolock _l(mStateLock);
1330 LayerBaseClient* const layer = getLayerUser_l(index);
1331 status_t err = removeLayer_l(layer);
1332 if (err < 0)
1333 return err;
1334 setTransactionFlags(eTransactionNeeded);
1335 return NO_ERROR;
1336}
1337
1338status_t SurfaceFlinger::setClientState(
1339 ClientID cid,
1340 int32_t count,
1341 const layer_state_t* states)
1342{
1343 Mutex::Autolock _l(mStateLock);
1344 uint32_t flags = 0;
1345 cid <<= 16;
1346 for (int i=0 ; i<count ; i++) {
1347 const layer_state_t& s = states[i];
1348 LayerBaseClient* layer = getLayerUser_l(s.surface | cid);
1349 if (layer) {
1350 const uint32_t what = s.what;
1351 // check if it has been destroyed first
1352 if (what & eDestroyed) {
1353 if (removeLayer_l(layer) == NO_ERROR) {
1354 flags |= eTransactionNeeded;
1355 // we skip everything else... well, no, not really
1356 // we skip ONLY that transaction.
1357 continue;
1358 }
1359 }
1360 if (what & ePositionChanged) {
1361 if (layer->setPosition(s.x, s.y))
1362 flags |= eTraversalNeeded;
1363 }
1364 if (what & eLayerChanged) {
1365 if (layer->setLayer(s.z)) {
1366 mCurrentState.layersSortedByZ.reorder(
1367 layer, &Layer::compareCurrentStateZ);
1368 // we need traversal (state changed)
1369 // AND transaction (list changed)
1370 flags |= eTransactionNeeded|eTraversalNeeded;
1371 }
1372 }
1373 if (what & eSizeChanged) {
1374 if (layer->setSize(s.w, s.h))
1375 flags |= eTraversalNeeded;
1376 }
1377 if (what & eAlphaChanged) {
1378 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1379 flags |= eTraversalNeeded;
1380 }
1381 if (what & eMatrixChanged) {
1382 if (layer->setMatrix(s.matrix))
1383 flags |= eTraversalNeeded;
1384 }
1385 if (what & eTransparentRegionChanged) {
1386 if (layer->setTransparentRegionHint(s.transparentRegion))
1387 flags |= eTraversalNeeded;
1388 }
1389 if (what & eVisibilityChanged) {
1390 if (layer->setFlags(s.flags, s.mask))
1391 flags |= eTraversalNeeded;
1392 }
1393 }
1394 }
1395 if (flags) {
1396 setTransactionFlags(flags);
1397 }
1398 return NO_ERROR;
1399}
1400
1401LayerBaseClient* SurfaceFlinger::getLayerUser_l(SurfaceID s) const
1402{
1403 return mLayerMap.valueFor(s);
1404}
1405
1406void SurfaceFlinger::screenReleased(int dpy)
1407{
1408 // this may be called by a signal handler, we can't do too much in here
1409 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1410 signalEvent();
1411}
1412
1413void SurfaceFlinger::screenAcquired(int dpy)
1414{
1415 // this may be called by a signal handler, we can't do too much in here
1416 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1417 signalEvent();
1418}
1419
1420status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1421{
1422 const size_t SIZE = 1024;
1423 char buffer[SIZE];
1424 String8 result;
1425 if (checkCallingPermission(
1426 String16("android.permission.DUMP")) == false)
1427 { // not allowed
1428 snprintf(buffer, SIZE, "Permission Denial: "
1429 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1430 IPCThreadState::self()->getCallingPid(),
1431 IPCThreadState::self()->getCallingUid());
1432 result.append(buffer);
1433 } else {
1434 Mutex::Autolock _l(mStateLock);
1435 size_t s = mClientsMap.size();
1436 char name[64];
1437 for (size_t i=0 ; i<s ; i++) {
1438 Client* client = mClientsMap.valueAt(i);
1439 sprintf(name, " Client (id=0x%08x)", client->cid);
1440 client->dump(name);
1441 }
1442 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1443 const size_t count = currentLayers.size();
1444 for (size_t i=0 ; i<count ; i++) {
1445 /*** LayerBase ***/
1446 LayerBase const * const layer = currentLayers[i];
1447 const Layer::State& s = layer->drawingState();
1448 snprintf(buffer, SIZE,
1449 "+ %s %p\n"
1450 " "
1451 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1452 "needsBlending=%1d, invalidate=%1d, "
1453 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
1454 layer->getTypeID(), layer,
1455 s.z, layer->tx(), layer->ty(), s.w, s.h,
1456 layer->needsBlending(), layer->contentDirty,
1457 s.alpha, s.flags,
1458 s.transform[0], s.transform[1],
1459 s.transform[2], s.transform[3]);
1460 result.append(buffer);
1461 buffer[0] = 0;
1462 /*** LayerBaseClient ***/
1463 LayerBaseClient* const lbc =
1464 LayerBase::dynamicCast<LayerBaseClient*>((LayerBase*)layer);
1465 if (lbc) {
1466 snprintf(buffer, SIZE,
1467 " "
1468 "id=0x%08x, client=0x%08x, identity=%u\n",
1469 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1470 lbc->getIdentity());
1471 }
1472 result.append(buffer);
1473 buffer[0] = 0;
1474 /*** Layer ***/
1475 Layer* const l = LayerBase::dynamicCast<Layer*>((LayerBase*)layer);
1476 if (l) {
1477 const LayerBitmap& buf0(l->getBuffer(0));
1478 const LayerBitmap& buf1(l->getBuffer(1));
1479 snprintf(buffer, SIZE,
1480 " "
1481 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u], mTextureName=%d,"
1482 " freezeLock=%p, swapState=0x%08x\n",
1483 l->pixelFormat(),
1484 buf0.width(), buf0.height(), buf0.stride(),
1485 buf1.width(), buf1.height(), buf1.stride(),
1486 l->getTextureName(), l->getFreezeLock().get(),
1487 l->lcblk->swapState);
1488 }
1489 result.append(buffer);
1490 buffer[0] = 0;
1491 s.transparentRegion.dump(result, "transparentRegion");
1492 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1493 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1494 }
1495 mWormholeRegion.dump(result, "WormholeRegion");
1496 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1497 snprintf(buffer, SIZE,
1498 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1499 mFreezeDisplay?"yes":"no", mFreezeCount,
1500 mCurrentState.orientation, hw.canDraw());
1501 result.append(buffer);
1502
1503 sp<AllocatorInterface> allocator;
1504 if (mGPU != 0) {
1505 snprintf(buffer, SIZE, " GPU owner: %d\n", mGPU->getOwner());
1506 result.append(buffer);
1507 allocator = mGPU->getAllocator();
1508 if (allocator != 0) {
1509 allocator->dump(result, "GPU Allocator");
1510 }
1511 }
1512 allocator = mSurfaceHeapManager->getAllocator(NATIVE_MEMORY_TYPE_PMEM);
1513 if (allocator != 0) {
1514 allocator->dump(result, "PMEM Allocator");
1515 }
1516 }
1517 write(fd, result.string(), result.size());
1518 return NO_ERROR;
1519}
1520
1521status_t SurfaceFlinger::onTransact(
1522 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1523{
1524 switch (code) {
1525 case CREATE_CONNECTION:
1526 case OPEN_GLOBAL_TRANSACTION:
1527 case CLOSE_GLOBAL_TRANSACTION:
1528 case SET_ORIENTATION:
1529 case FREEZE_DISPLAY:
1530 case UNFREEZE_DISPLAY:
1531 case BOOT_FINISHED:
1532 case REVOKE_GPU:
1533 {
1534 // codes that require permission check
1535 IPCThreadState* ipc = IPCThreadState::self();
1536 const int pid = ipc->getCallingPid();
1537 const int self_pid = getpid();
1538 if (UNLIKELY(pid != self_pid)) {
1539 // we're called from a different process, do the real check
1540 if (!checkCallingPermission(
1541 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1542 {
1543 const int uid = ipc->getCallingUid();
1544 LOGE("Permission Denial: "
1545 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1546 return PERMISSION_DENIED;
1547 }
1548 }
1549 }
1550 }
1551
1552 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1553 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1554 // HARDWARE_TEST stuff...
1555 if (UNLIKELY(checkCallingPermission(
1556 String16("android.permission.HARDWARE_TEST")) == false))
1557 { // not allowed
1558 LOGE("Permission Denial: pid=%d, uid=%d\n",
1559 IPCThreadState::self()->getCallingPid(),
1560 IPCThreadState::self()->getCallingUid());
1561 return PERMISSION_DENIED;
1562 }
1563 int n;
1564 switch (code) {
1565 case 1000: // SHOW_CPU
1566 n = data.readInt32();
1567 mDebugCpu = n ? 1 : 0;
1568 if (mDebugCpu) {
1569 if (mCpuGauge == 0) {
1570 mCpuGauge = new CPUGauge(this, ms2ns(500));
1571 }
1572 } else {
1573 if (mCpuGauge != 0) {
1574 mCpuGauge->requestExitAndWait();
1575 Mutex::Autolock _l(mDebugLock);
1576 mCpuGauge.clear();
1577 }
1578 }
1579 return NO_ERROR;
1580 case 1001: // SHOW_FPS
1581 n = data.readInt32();
1582 mDebugFps = n ? 1 : 0;
1583 return NO_ERROR;
1584 case 1002: // SHOW_UPDATES
1585 n = data.readInt32();
1586 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1587 return NO_ERROR;
1588 case 1003: // SHOW_BACKGROUND
1589 n = data.readInt32();
1590 mDebugBackground = n ? 1 : 0;
1591 return NO_ERROR;
1592 case 1004:{ // repaint everything
1593 Mutex::Autolock _l(mStateLock);
1594 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1595 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1596 signalEvent();
1597 }
1598 return NO_ERROR;
1599 case 1005: // ask GPU revoke
1600 mGPU->friendlyRevoke();
1601 return NO_ERROR;
1602 case 1006: // revoke GPU
1603 mGPU->unconditionalRevoke();
1604 return NO_ERROR;
1605 case 1007: // set mFreezeCount
1606 mFreezeCount = data.readInt32();
1607 return NO_ERROR;
1608 case 1010: // interrogate.
1609 reply->writeInt32(mDebugCpu);
1610 reply->writeInt32(0);
1611 reply->writeInt32(mDebugRegion);
1612 reply->writeInt32(mDebugBackground);
1613 return NO_ERROR;
1614 case 1013: {
1615 Mutex::Autolock _l(mStateLock);
1616 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1617 reply->writeInt32(hw.getPageFlipCount());
1618 }
1619 return NO_ERROR;
1620 }
1621 }
1622 return err;
1623}
1624
1625// ---------------------------------------------------------------------------
1626#if 0
1627#pragma mark -
1628#endif
1629
1630Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1631 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1632{
1633 mSharedHeapAllocator = getSurfaceHeapManager()->createHeap();
1634 const int pgsize = getpagesize();
1635 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1636 mCblkHeap = new MemoryDealer(cblksize);
1637 mCblkMemory = mCblkHeap->allocate(cblksize);
1638 if (mCblkMemory != 0) {
1639 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1640 if (ctrlblk) { // construct the shared structure in-place.
1641 new(ctrlblk) per_client_cblk_t;
1642 }
1643 }
1644}
1645
1646Client::~Client() {
1647 if (ctrlblk) {
1648 const int pgsize = getpagesize();
1649 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1650 }
1651}
1652
1653const sp<SurfaceHeapManager>& Client::getSurfaceHeapManager() const {
1654 return mFlinger->getSurfaceHeapManager();
1655}
1656
1657int32_t Client::generateId(int pid)
1658{
1659 const uint32_t i = clz( ~mBitmap );
1660 if (i >= NUM_LAYERS_MAX) {
1661 return NO_MEMORY;
1662 }
1663 mPid = pid;
1664 mInUse.add(uint8_t(i));
1665 mBitmap |= 1<<(31-i);
1666 return i;
1667}
1668status_t Client::bindLayer(LayerBaseClient* layer, int32_t id)
1669{
1670 ssize_t idx = mInUse.indexOf(id);
1671 if (idx < 0)
1672 return NAME_NOT_FOUND;
1673 return mLayers.insertAt(layer, idx);
1674}
1675void Client::free(int32_t id)
1676{
1677 ssize_t idx = mInUse.remove(uint8_t(id));
1678 if (idx >= 0) {
1679 mBitmap &= ~(1<<(31-id));
1680 mLayers.removeItemsAt(idx);
1681 }
1682}
1683
1684sp<MemoryDealer> Client::createAllocator(uint32_t flags)
1685{
1686 sp<MemoryDealer> allocator;
1687 allocator = getSurfaceHeapManager()->createHeap(
1688 flags, getClientPid(), mSharedHeapAllocator);
1689 return allocator;
1690}
1691
1692bool Client::isValid(int32_t i) const {
1693 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1694}
1695const uint8_t* Client::inUseArray() const {
1696 return mInUse.array();
1697}
1698size_t Client::numActiveLayers() const {
1699 return mInUse.size();
1700}
1701LayerBaseClient* Client::getLayerUser(int32_t i) const {
1702 ssize_t idx = mInUse.indexOf(uint8_t(i));
1703 if (idx<0) return 0;
1704 return mLayers[idx];
1705}
1706
1707void Client::dump(const char* what)
1708{
1709}
1710
1711// ---------------------------------------------------------------------------
1712#if 0
1713#pragma mark -
1714#endif
1715
1716BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1717 : mId(cid), mFlinger(flinger), mCblk(cblk)
1718{
1719}
1720
1721BClient::~BClient() {
1722 // destroy all resources attached to this client
1723 mFlinger->destroyConnection(mId);
1724}
1725
1726void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1727 *ctrl = mCblk;
1728}
1729
1730sp<ISurface> BClient::createSurface(
1731 ISurfaceFlingerClient::surface_data_t* params, int pid,
1732 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1733 uint32_t flags)
1734{
1735 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1736}
1737
1738status_t BClient::destroySurface(SurfaceID sid)
1739{
1740 sid |= (mId << 16); // add the client-part to id
1741 return mFlinger->destroySurface(sid);
1742}
1743
1744status_t BClient::setState(int32_t count, const layer_state_t* states)
1745{
1746 return mFlinger->setClientState(mId, count, states);
1747}
1748
1749// ---------------------------------------------------------------------------
1750
1751GraphicPlane::GraphicPlane()
1752 : mHw(0)
1753{
1754}
1755
1756GraphicPlane::~GraphicPlane() {
1757 delete mHw;
1758}
1759
1760bool GraphicPlane::initialized() const {
1761 return mHw ? true : false;
1762}
1763
1764void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1765 mHw = hw;
1766}
1767
1768void GraphicPlane::setTransform(const Transform& tr) {
1769 mTransform = tr;
1770 mGlobalTransform = mOrientationTransform * mTransform;
1771}
1772
1773status_t GraphicPlane::orientationToTransfrom(
1774 int orientation, int w, int h, Transform* tr)
1775{
1776 float a, b, c, d, x, y;
1777 switch (orientation) {
1778 case ISurfaceComposer::eOrientationDefault:
1779 a=1; b=0; c=0; d=1; x=0; y=0;
1780 break;
1781 case ISurfaceComposer::eOrientation90:
1782 a=0; b=-1; c=1; d=0; x=w; y=0;
1783 break;
1784 case ISurfaceComposer::eOrientation180:
1785 a=-1; b=0; c=0; d=-1; x=w; y=h;
1786 break;
1787 case ISurfaceComposer::eOrientation270:
1788 a=0; b=1; c=-1; d=0; x=0; y=h;
1789 break;
1790 default:
1791 return BAD_VALUE;
1792 }
1793 tr->set(a, b, c, d);
1794 tr->set(x, y);
1795 return NO_ERROR;
1796}
1797
1798status_t GraphicPlane::setOrientation(int orientation)
1799{
1800 const DisplayHardware& hw(displayHardware());
1801 const float w = hw.getWidth();
1802 const float h = hw.getHeight();
1803
1804 if (orientation == ISurfaceComposer::eOrientationDefault) {
1805 // make sure the default orientation is optimal
1806 mOrientationTransform.reset();
1807 mGlobalTransform = mTransform;
1808 return NO_ERROR;
1809 }
1810
1811 // If the rotation can be handled in hardware, this is where
1812 // the magic should happen.
1813 if (UNLIKELY(orientation == 42)) {
1814 float a, b, c, d, x, y;
1815 const float r = (3.14159265f / 180.0f) * 42.0f;
1816 const float si = sinf(r);
1817 const float co = cosf(r);
1818 a=co; b=-si; c=si; d=co;
1819 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1820 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1821 mOrientationTransform.set(a, b, c, d);
1822 mOrientationTransform.set(x, y);
1823 } else {
1824 GraphicPlane::orientationToTransfrom(orientation, w, h,
1825 &mOrientationTransform);
1826 }
Mathias Agopian2764f302009-03-24 22:43:22 -07001827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 mGlobalTransform = mOrientationTransform * mTransform;
1829 return NO_ERROR;
1830}
1831
1832const DisplayHardware& GraphicPlane::displayHardware() const {
1833 return *mHw;
1834}
1835
1836const Transform& GraphicPlane::transform() const {
1837 return mGlobalTransform;
1838}
1839
1840// ---------------------------------------------------------------------------
1841
1842}; // namespace android