blob: 5fd979e0614baf46d0781252e376df0c37c5079d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080017#include <stdlib.h>
18#include <stdio.h>
19#include <stdint.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <errno.h>
23#include <math.h>
Jean-Baptiste Querua837ba72009-01-26 11:51:12 -080024#include <limits.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/ioctl.h>
28
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
32#include <utils/IPCThreadState.h>
33#include <utils/IServiceManager.h>
34#include <utils/MemoryDealer.h>
35#include <utils/MemoryBase.h>
36#include <utils/String8.h>
37#include <utils/String16.h>
38#include <utils/StopWatch.h>
39
40#include <ui/PixelFormat.h>
41#include <ui/DisplayInfo.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
43#include <pixelflinger/pixelflinger.h>
44#include <GLES/gl.h>
45
46#include "clz.h"
Mathias Agopian076b1cc2009-04-10 14:24:30 -070047#include "BufferAllocator.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#include "Layer.h"
49#include "LayerBlur.h"
50#include "LayerBuffer.h"
51#include "LayerDim.h"
52#include "LayerBitmap.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054
55#include "DisplayHardware/DisplayHardware.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#define DISPLAY_COUNT 1
58
59namespace android {
60
61// ---------------------------------------------------------------------------
62
63void SurfaceFlinger::instantiate() {
64 defaultServiceManager()->addService(
65 String16("SurfaceFlinger"), new SurfaceFlinger());
66}
67
68void SurfaceFlinger::shutdown() {
69 // we should unregister here, but not really because
70 // when (if) the service manager goes away, all the services
71 // it has a reference to will leave too.
72}
73
74// ---------------------------------------------------------------------------
75
76SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
77 : lookup(rhs.lookup), layers(rhs.layers)
78{
79}
80
81ssize_t SurfaceFlinger::LayerVector::indexOf(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070082 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083{
84 if (guess<size() && lookup.keyAt(guess) == key)
85 return guess;
86 const ssize_t i = lookup.indexOfKey(key);
87 if (i>=0) {
88 const size_t idx = lookup.valueAt(i);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070089 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070091 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092 return idx;
93 }
94 return i;
95}
96
97ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070098 const sp<LayerBase>& layer,
99 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100{
101 size_t count = layers.size();
102 ssize_t l = 0;
103 ssize_t h = count-1;
104 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700105 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106 while (l <= h) {
107 mid = l + (h - l)/2;
108 const int c = cmp(a+mid, &layer);
109 if (c == 0) { l = mid; break; }
110 else if (c<0) { l = mid+1; }
111 else { h = mid-1; }
112 }
113 size_t order = l;
114 while (order<count && !cmp(&layer, a+order)) {
115 order++;
116 }
117 count = lookup.size();
118 for (size_t i=0 ; i<count ; i++) {
119 if (lookup.valueAt(i) >= order) {
120 lookup.editValueAt(i)++;
121 }
122 }
123 layers.insertAt(layer, order);
124 lookup.add(layer, order);
125 return order;
126}
127
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700128ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129{
130 const ssize_t keyIndex = lookup.indexOfKey(layer);
131 if (keyIndex >= 0) {
132 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700133 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 layers.removeItemsAt(index);
137 lookup.removeItemsAt(keyIndex);
138 const size_t count = lookup.size();
139 for (size_t i=0 ; i<count ; i++) {
140 if (lookup.valueAt(i) >= size_t(index)) {
141 lookup.editValueAt(i)--;
142 }
143 }
144 return index;
145 }
146 return NAME_NOT_FOUND;
147}
148
149ssize_t SurfaceFlinger::LayerVector::reorder(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700150 const sp<LayerBase>& layer,
151 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152{
153 // XXX: it's a little lame. but oh well...
154 ssize_t err = remove(layer);
155 if (err >=0)
156 err = add(layer, cmp);
157 return err;
158}
159
160// ---------------------------------------------------------------------------
161#if 0
162#pragma mark -
163#endif
164
165SurfaceFlinger::SurfaceFlinger()
166 : BnSurfaceComposer(), Thread(false),
167 mTransactionFlags(0),
168 mTransactionCount(0),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700169 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 mBootTime(systemTime()),
171 mLastScheduledBroadcast(NULL),
172 mVisibleRegionsDirty(false),
173 mDeferReleaseConsole(false),
174 mFreezeDisplay(false),
175 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700176 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugBackground(0),
179 mDebugNoBootAnimation(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800180 mConsoleSignals(0),
181 mSecureFrameBuffer(0)
182{
183 init();
184}
185
186void SurfaceFlinger::init()
187{
188 LOGI("SurfaceFlinger is starting");
189
190 // debugging stuff...
191 char value[PROPERTY_VALUE_MAX];
192 property_get("debug.sf.showupdates", value, "0");
193 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 property_get("debug.sf.showbackground", value, "0");
195 mDebugBackground = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 property_get("debug.sf.nobootanimation", value, "0");
197 mDebugNoBootAnimation = atoi(value);
198
199 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 LOGI_IF(mDebugNoBootAnimation, "boot animation disabled");
202}
203
204SurfaceFlinger::~SurfaceFlinger()
205{
206 glDeleteTextures(1, &mWormholeTexName);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207}
208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
210{
211 return graphicPlane(0).displayHardware().getOverlayEngine();
212}
213
214sp<IMemory> SurfaceFlinger::getCblk() const
215{
216 return mServerCblkMemory;
217}
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
220{
221 Mutex::Autolock _l(mStateLock);
222 uint32_t token = mTokens.acquire();
223
224 Client* client = new Client(token, this);
225 if ((client == 0) || (client->ctrlblk == 0)) {
226 mTokens.release(token);
227 return 0;
228 }
229 status_t err = mClientsMap.add(token, client);
230 if (err < 0) {
231 delete client;
232 mTokens.release(token);
233 return 0;
234 }
235 sp<BClient> bclient =
236 new BClient(this, token, client->controlBlockMemory());
237 return bclient;
238}
239
240void SurfaceFlinger::destroyConnection(ClientID cid)
241{
242 Mutex::Autolock _l(mStateLock);
243 Client* const client = mClientsMap.valueFor(cid);
244 if (client) {
245 // free all the layers this client owns
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700246 const Vector< wp<LayerBaseClient> >& layers = client->getLayers();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 const size_t count = layers.size();
248 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 sp<LayerBaseClient> layer(layers[i].promote());
250 if (layer != 0) {
251 removeLayer_l(layer);
252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 }
254
255 // the resources associated with this client will be freed
256 // during the next transaction, after these surfaces have been
257 // properly removed from the screen
258
259 // remove this client from our ClientID->Client mapping.
260 mClientsMap.removeItem(cid);
261
262 // and add it to the list of disconnected clients
263 mDisconnectedClients.add(client);
264
265 // request a transaction
266 setTransactionFlags(eTransactionNeeded);
267 }
268}
269
270const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
271{
272 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
273 const GraphicPlane& plane(mGraphicPlanes[dpy]);
274 return plane;
275}
276
277GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
278{
279 return const_cast<GraphicPlane&>(
280 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
281}
282
283void SurfaceFlinger::bootFinished()
284{
285 const nsecs_t now = systemTime();
286 const nsecs_t duration = now - mBootTime;
287 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
288 if (mBootAnimation != 0) {
289 mBootAnimation->requestExit();
290 mBootAnimation.clear();
291 }
292}
293
294void SurfaceFlinger::onFirstRef()
295{
296 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
297
298 // Wait for the main thread to be done with its initialization
299 mReadyToRunBarrier.wait();
300}
301
302
303static inline uint16_t pack565(int r, int g, int b) {
304 return (r<<11)|(g<<5)|b;
305}
306
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307status_t SurfaceFlinger::readyToRun()
308{
309 LOGI( "SurfaceFlinger's main thread ready to run. "
310 "Initializing graphics H/W...");
311
312 // create the shared control-block
313 mServerHeap = new MemoryDealer(4096, MemoryDealer::READ_ONLY);
314 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
315
316 mServerCblkMemory = mServerHeap->allocate(4096);
317 LOGE_IF(mServerCblkMemory==0, "can't create shared control block");
318
319 mServerCblk = static_cast<surface_flinger_cblk_t *>(mServerCblkMemory->pointer());
320 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
321 new(mServerCblk) surface_flinger_cblk_t;
322
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 // we only support one display currently
324 int dpy = 0;
325
326 {
327 // initialize the main display
328 GraphicPlane& plane(graphicPlane(dpy));
329 DisplayHardware* const hw = new DisplayHardware(this, dpy);
330 plane.setDisplayHardware(hw);
331 }
332
333 // initialize primary screen
334 // (other display should be initialized in the same manner, but
335 // asynchronously, as they could come and go. None of this is supported
336 // yet).
337 const GraphicPlane& plane(graphicPlane(dpy));
338 const DisplayHardware& hw = plane.displayHardware();
339 const uint32_t w = hw.getWidth();
340 const uint32_t h = hw.getHeight();
341 const uint32_t f = hw.getFormat();
342 hw.makeCurrent();
343
344 // initialize the shared control block
345 mServerCblk->connected |= 1<<dpy;
346 display_cblk_t* dcblk = mServerCblk->displays + dpy;
347 memset(dcblk, 0, sizeof(display_cblk_t));
348 dcblk->w = w;
349 dcblk->h = h;
350 dcblk->format = f;
351 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
352 dcblk->xdpi = hw.getDpiX();
353 dcblk->ydpi = hw.getDpiY();
354 dcblk->fps = hw.getRefreshRate();
355 dcblk->density = hw.getDensity();
356 asm volatile ("":::"memory");
357
358 // Initialize OpenGL|ES
359 glActiveTexture(GL_TEXTURE0);
360 glBindTexture(GL_TEXTURE_2D, 0);
361 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
362 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
363 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
364 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
365 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
366 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
367 glPixelStorei(GL_PACK_ALIGNMENT, 4);
368 glEnableClientState(GL_VERTEX_ARRAY);
369 glEnable(GL_SCISSOR_TEST);
370 glShadeModel(GL_FLAT);
371 glDisable(GL_DITHER);
372 glDisable(GL_CULL_FACE);
373
374 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
375 const uint16_t g1 = pack565(0x17,0x2f,0x17);
376 const uint16_t textureData[4] = { g0, g1, g1, g0 };
377 glGenTextures(1, &mWormholeTexName);
378 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
379 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
380 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
381 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
382 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
383 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
384 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
385
386 glViewport(0, 0, w, h);
387 glMatrixMode(GL_PROJECTION);
388 glLoadIdentity();
389 glOrthof(0, w, h, 0, 0, 1);
390
391 LayerDim::initDimmer(this, w, h);
392
393 mReadyToRunBarrier.open();
394
395 /*
396 * We're now ready to accept clients...
397 */
398
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 // the boot animation!
400 if (mDebugNoBootAnimation == false)
401 mBootAnimation = new BootAnimation(this);
402
403 return NO_ERROR;
404}
405
406// ----------------------------------------------------------------------------
407#if 0
408#pragma mark -
409#pragma mark Events Handler
410#endif
411
412void SurfaceFlinger::waitForEvent()
413{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700414 while (true) {
415 nsecs_t timeout = -1;
416 if (UNLIKELY(isFrozen())) {
417 // wait 5 seconds
418 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
419 const nsecs_t now = systemTime();
420 if (mFreezeDisplayTime == 0) {
421 mFreezeDisplayTime = now;
422 }
423 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
424 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700425 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700426
Mathias Agopianb6683b52009-04-28 03:17:50 -0700427 MessageList::value_type msg = mEventQueue.waitMessage(timeout);
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700428 if (msg != 0) {
429 mFreezeDisplayTime = 0;
430 switch (msg->what) {
431 case MessageQueue::INVALIDATE:
432 // invalidate message, just return to the main loop
433 return;
434 }
435 } else {
436 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 if (isFrozen()) {
438 // we timed out and are still frozen
439 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
440 mFreezeDisplay, mFreezeCount);
441 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700442 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700443 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 }
447}
448
449void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700450 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451}
452
453void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700454 // this is the IPC call
455 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800456}
457
458void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
459{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700460 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800461}
462
463// ----------------------------------------------------------------------------
464#if 0
465#pragma mark -
466#pragma mark Main loop
467#endif
468
469bool SurfaceFlinger::threadLoop()
470{
471 waitForEvent();
472
473 // check for transactions
474 if (UNLIKELY(mConsoleSignals)) {
475 handleConsoleEvents();
476 }
477
478 if (LIKELY(mTransactionCount == 0)) {
479 // if we're in a global transaction, don't do anything.
480 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
481 uint32_t transactionFlags = getTransactionFlags(mask);
482 if (LIKELY(transactionFlags)) {
483 handleTransaction(transactionFlags);
484 }
485 }
486
487 // post surfaces (if needed)
488 handlePageFlip();
489
490 const DisplayHardware& hw(graphicPlane(0).displayHardware());
491 if (LIKELY(hw.canDraw())) {
492 // repaint the framebuffer (if needed)
493 handleRepaint();
494
495 // release the clients before we flip ('cause flip might block)
496 unlockClients();
497 executeScheduledBroadcasts();
498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800499 postFramebuffer();
500 } else {
501 // pretend we did the post
502 unlockClients();
503 executeScheduledBroadcasts();
504 usleep(16667); // 60 fps period
505 }
506 return true;
507}
508
509void SurfaceFlinger::postFramebuffer()
510{
Mathias Agopian0926f502009-05-04 14:17:04 -0700511 if (isFrozen()) {
512 // we are not allowed to draw, but pause a bit to make sure
513 // apps don't end up using the whole CPU, if they depend on
514 // surfaceflinger for synchronization.
515 usleep(8333); // 8.3ms ~ 120fps
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516 return;
517 }
518
519 if (!mInvalidRegion.isEmpty()) {
520 const DisplayHardware& hw(graphicPlane(0).displayHardware());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522 mInvalidRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523 }
524}
525
526void SurfaceFlinger::handleConsoleEvents()
527{
528 // something to do with the console
529 const DisplayHardware& hw = graphicPlane(0).displayHardware();
530
531 int what = android_atomic_and(0, &mConsoleSignals);
532 if (what & eConsoleAcquired) {
533 hw.acquireScreen();
534 }
535
536 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700537 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539 hw.releaseScreen();
540 }
541
542 if (what & eConsoleReleased) {
543 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544 hw.releaseScreen();
545 } else {
546 mDeferReleaseConsole = true;
547 }
548 }
549
550 mDirtyRegion.set(hw.bounds());
551}
552
553void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
554{
555 Mutex::Autolock _l(mStateLock);
556
557 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
558 const size_t count = currentLayers.size();
559
560 /*
561 * Traversal of the children
562 * (perform the transaction for each of them if needed)
563 */
564
565 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
566 if (layersNeedTransaction) {
567 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700568 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
570 if (!trFlags) continue;
571
572 const uint32_t flags = layer->doTransaction(0);
573 if (flags & Layer::eVisibleRegion)
574 mVisibleRegionsDirty = true;
575
576 if (flags & Layer::eRestartTransaction) {
577 // restart the transaction, but back-off a little
578 layer->setTransactionFlags(eTransactionNeeded);
579 setTransactionFlags(eTraversalNeeded, ms2ns(8));
580 }
581 }
582 }
583
584 /*
585 * Perform our own transaction if needed
586 */
587
588 if (transactionFlags & eTransactionNeeded) {
589 if (mCurrentState.orientation != mDrawingState.orientation) {
590 // the orientation has changed, recompute all visible regions
591 // and invalidate everything.
592
593 const int dpy = 0;
594 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700595 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596 GraphicPlane& plane(graphicPlane(dpy));
597 plane.setOrientation(orientation);
598
599 // update the shared control block
600 const DisplayHardware& hw(plane.displayHardware());
601 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
602 dcblk->orientation = orientation;
603 if (orientation & eOrientationSwapMask) {
604 // 90 or 270 degrees orientation
605 dcblk->w = hw.getHeight();
606 dcblk->h = hw.getWidth();
607 } else {
608 dcblk->w = hw.getWidth();
609 dcblk->h = hw.getHeight();
610 }
611
612 mVisibleRegionsDirty = true;
613 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700614 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800615 }
616
617 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
618 // freezing or unfreezing the display -> trigger animation if needed
619 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800620 }
621
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700622 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
623 // layers have been added
624 mVisibleRegionsDirty = true;
625 }
626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800627 // some layers might have been removed, so
628 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700629 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700631 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
632 const ssize_t count = previousLayers.size();
633 for (ssize_t i=0 ; i<count ; i++) {
634 const sp<LayerBase>& layer(previousLayers[i]);
635 if (currentLayers.indexOf( layer ) < 0) {
636 // this layer is not visible anymore
637 // FIXME: would be better to call without the lock held
638 //LOGD("ditching layer %p", layer.get());
639 layer->ditch();
640 }
641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 }
643
644 // get rid of all resources we don't need anymore
645 // (layers and clients)
646 free_resources_l();
647 }
648
649 commitTransaction();
650}
651
652sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
653{
654 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
655}
656
657void SurfaceFlinger::computeVisibleRegions(
658 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
659{
660 const GraphicPlane& plane(graphicPlane(0));
661 const Transform& planeTransform(plane.transform());
662
663 Region aboveOpaqueLayers;
664 Region aboveCoveredLayers;
665 Region dirty;
666
667 bool secureFrameBuffer = false;
668
669 size_t i = currentLayers.size();
670 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700671 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672 layer->validateVisibility(planeTransform);
673
674 // start with the whole surface at its current location
675 const Layer::State& s = layer->drawingState();
676 const Rect bounds(layer->visibleBounds());
677
678 // handle hidden surfaces by setting the visible region to empty
679 Region opaqueRegion;
680 Region visibleRegion;
681 Region coveredRegion;
682 if (UNLIKELY((s.flags & ISurfaceComposer::eLayerHidden) || !s.alpha)) {
683 visibleRegion.clear();
684 } else {
685 const bool translucent = layer->needsBlending();
686 visibleRegion.set(bounds);
687 coveredRegion = visibleRegion;
688
689 // Remove the transparent area from the visible region
690 if (translucent) {
691 visibleRegion.subtractSelf(layer->transparentRegionScreen);
692 }
693
694 // compute the opaque region
695 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
696 // the opaque region is the visible region
697 opaqueRegion = visibleRegion;
698 }
699 }
700
701 // subtract the opaque region covered by the layers above us
702 visibleRegion.subtractSelf(aboveOpaqueLayers);
703 coveredRegion.andSelf(aboveCoveredLayers);
704
705 // compute this layer's dirty region
706 if (layer->contentDirty) {
707 // we need to invalidate the whole region
708 dirty = visibleRegion;
709 // as well, as the old visible region
710 dirty.orSelf(layer->visibleRegionScreen);
711 layer->contentDirty = false;
712 } else {
713 // compute the exposed region
714 // dirty = what's visible now - what's wasn't covered before
715 // = what's visible now & what's was covered before
716 dirty = visibleRegion.intersect(layer->coveredRegionScreen);
717 }
718 dirty.subtractSelf(aboveOpaqueLayers);
719
720 // accumulate to the screen dirty region
721 dirtyRegion.orSelf(dirty);
722
Mathias Agopian62b74442009-04-14 23:02:51 -0700723 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724 aboveOpaqueLayers.orSelf(opaqueRegion);
725 aboveCoveredLayers.orSelf(bounds);
726
727 // Store the visible region is screen space
728 layer->setVisibleRegion(visibleRegion);
729 layer->setCoveredRegion(coveredRegion);
730
Mathias Agopian62b74442009-04-14 23:02:51 -0700731 // If a secure layer is partially visible, lock down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732 if (layer->isSecure() && !visibleRegion.isEmpty()) {
733 secureFrameBuffer = true;
734 }
735 }
736
737 mSecureFrameBuffer = secureFrameBuffer;
738 opaqueRegion = aboveOpaqueLayers;
739}
740
741
742void SurfaceFlinger::commitTransaction()
743{
744 mDrawingState = mCurrentState;
745 mTransactionCV.signal();
746}
747
748void SurfaceFlinger::handlePageFlip()
749{
750 bool visibleRegions = mVisibleRegionsDirty;
751 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
752 visibleRegions |= lockPageFlip(currentLayers);
753
754 const DisplayHardware& hw = graphicPlane(0).displayHardware();
755 const Region screenRegion(hw.bounds());
756 if (visibleRegions) {
757 Region opaqueRegion;
758 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
759 mWormholeRegion = screenRegion.subtract(opaqueRegion);
760 mVisibleRegionsDirty = false;
761 }
762
763 unlockPageFlip(currentLayers);
764 mDirtyRegion.andSelf(screenRegion);
765}
766
767bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
768{
769 bool recomputeVisibleRegions = false;
770 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700771 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700773 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800774 layer->lockPageFlip(recomputeVisibleRegions);
775 }
776 return recomputeVisibleRegions;
777}
778
779void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
780{
781 const GraphicPlane& plane(graphicPlane(0));
782 const Transform& planeTransform(plane.transform());
783 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700784 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700786 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800787 layer->unlockPageFlip(planeTransform, mDirtyRegion);
788 }
789}
790
791void SurfaceFlinger::handleRepaint()
792{
793 // set the frame buffer
794 const DisplayHardware& hw(graphicPlane(0).displayHardware());
795 glMatrixMode(GL_MODELVIEW);
796 glLoadIdentity();
797
798 if (UNLIKELY(mDebugRegion)) {
799 debugFlashRegions();
800 }
801
802 // compute the invalid region
803 mInvalidRegion.orSelf(mDirtyRegion);
804
805 uint32_t flags = hw.getFlags();
806 if (flags & DisplayHardware::BUFFER_PRESERVED) {
807 // here we assume DisplayHardware::flip()'s implementation
808 // performs the copy-back optimization.
809 } else {
810 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
811 // we need to fully redraw the part that will be updated
812 mDirtyRegion.set(mInvalidRegion.bounds());
813 } else {
814 // we need to redraw everything
815 mDirtyRegion.set(hw.bounds());
816 mInvalidRegion = mDirtyRegion;
817 }
818 }
819
820 // compose all surfaces
821 composeSurfaces(mDirtyRegion);
822
823 // clear the dirty regions
824 mDirtyRegion.clear();
825}
826
827void SurfaceFlinger::composeSurfaces(const Region& dirty)
828{
829 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
830 // should never happen unless the window manager has a bug
831 // draw something...
832 drawWormhole();
833 }
834 const SurfaceFlinger& flinger(*this);
835 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
836 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700837 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700839 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840 const Region& visibleRegion(layer->visibleRegionScreen);
841 if (!visibleRegion.isEmpty()) {
842 const Region clip(dirty.intersect(visibleRegion));
843 if (!clip.isEmpty()) {
844 layer->draw(clip);
845 }
846 }
847 }
848}
849
850void SurfaceFlinger::unlockClients()
851{
852 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
853 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700854 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700856 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857 layer->finishPageFlip();
858 }
859}
860
861void SurfaceFlinger::scheduleBroadcast(Client* client)
862{
863 if (mLastScheduledBroadcast != client) {
864 mLastScheduledBroadcast = client;
865 mScheduledBroadcasts.add(client);
866 }
867}
868
869void SurfaceFlinger::executeScheduledBroadcasts()
870{
871 SortedVector<Client*>& list = mScheduledBroadcasts;
872 size_t count = list.size();
873 while (count--) {
874 per_client_cblk_t* const cblk = list[count]->ctrlblk;
875 if (cblk->lock.tryLock() == NO_ERROR) {
876 cblk->cv.broadcast();
877 list.removeAt(count);
878 cblk->lock.unlock();
879 } else {
880 // schedule another round
881 LOGW("executeScheduledBroadcasts() skipped, "
882 "contention on the client. We'll try again later...");
883 signalDelayedEvent(ms2ns(4));
884 }
885 }
886 mLastScheduledBroadcast = 0;
887}
888
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800889void SurfaceFlinger::debugFlashRegions()
890{
Mathias Agopian0926f502009-05-04 14:17:04 -0700891 const DisplayHardware& hw(graphicPlane(0).displayHardware());
892 const uint32_t flags = hw.getFlags();
893 if (!(flags & DisplayHardware::BUFFER_PRESERVED)) {
894 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
895 mDirtyRegion.bounds() : hw.bounds());
896 composeSurfaces(repaint);
897 }
898
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800899 glDisable(GL_TEXTURE_2D);
900 glDisable(GL_BLEND);
901 glDisable(GL_DITHER);
902 glDisable(GL_SCISSOR_TEST);
903
Mathias Agopian0926f502009-05-04 14:17:04 -0700904 static int toggle = 0;
905 toggle = 1 - toggle;
906 if (toggle) {
907 glColor4x(0x10000, 0, 0x10000, 0x10000);
908 } else {
909 glColor4x(0x10000, 0x10000, 0, 0x10000);
910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800911
912 Rect r;
913 Region::iterator iterator(mDirtyRegion);
914 while (iterator.iterate(&r)) {
915 GLfloat vertices[][2] = {
916 { r.left, r.top },
917 { r.left, r.bottom },
918 { r.right, r.bottom },
919 { r.right, r.top }
920 };
921 glVertexPointer(2, GL_FLOAT, 0, vertices);
922 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
923 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700924
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800925 hw.flip(mDirtyRegion.merge(mInvalidRegion));
926 mInvalidRegion.clear();
927
928 if (mDebugRegion > 1)
929 usleep(mDebugRegion * 1000);
930
931 glEnable(GL_SCISSOR_TEST);
932 //mDirtyRegion.dump("mDirtyRegion");
933}
934
935void SurfaceFlinger::drawWormhole() const
936{
937 const Region region(mWormholeRegion.intersect(mDirtyRegion));
938 if (region.isEmpty())
939 return;
940
941 const DisplayHardware& hw(graphicPlane(0).displayHardware());
942 const int32_t width = hw.getWidth();
943 const int32_t height = hw.getHeight();
944
945 glDisable(GL_BLEND);
946 glDisable(GL_DITHER);
947
948 if (LIKELY(!mDebugBackground)) {
949 glClearColorx(0,0,0,0);
950 Rect r;
951 Region::iterator iterator(region);
952 while (iterator.iterate(&r)) {
953 const GLint sy = height - (r.top + r.height());
954 glScissor(r.left, sy, r.width(), r.height());
955 glClear(GL_COLOR_BUFFER_BIT);
956 }
957 } else {
958 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
959 { width, height }, { 0, height } };
960 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
961 glVertexPointer(2, GL_SHORT, 0, vertices);
962 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
963 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
964 glEnable(GL_TEXTURE_2D);
965 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
966 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
967 glMatrixMode(GL_TEXTURE);
968 glLoadIdentity();
969 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
970 Rect r;
971 Region::iterator iterator(region);
972 while (iterator.iterate(&r)) {
973 const GLint sy = height - (r.top + r.height());
974 glScissor(r.left, sy, r.width(), r.height());
975 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
976 }
977 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
978 }
979}
980
981void SurfaceFlinger::debugShowFPS() const
982{
983 static int mFrameCount;
984 static int mLastFrameCount = 0;
985 static nsecs_t mLastFpsTime = 0;
986 static float mFps = 0;
987 mFrameCount++;
988 nsecs_t now = systemTime();
989 nsecs_t diff = now - mLastFpsTime;
990 if (diff > ms2ns(250)) {
991 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
992 mLastFpsTime = now;
993 mLastFrameCount = mFrameCount;
994 }
995 // XXX: mFPS has the value we want
996 }
997
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700998status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999{
1000 Mutex::Autolock _l(mStateLock);
1001 addLayer_l(layer);
1002 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1003 return NO_ERROR;
1004}
1005
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001006status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001007{
1008 Mutex::Autolock _l(mStateLock);
1009 removeLayer_l(layer);
1010 setTransactionFlags(eTransactionNeeded);
1011 return NO_ERROR;
1012}
1013
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001014status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015{
1016 layer->forceVisibilityTransaction();
1017 setTransactionFlags(eTraversalNeeded);
1018 return NO_ERROR;
1019}
1020
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001021status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001022{
1023 ssize_t i = mCurrentState.layersSortedByZ.add(
1024 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001025 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1026 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027 mLayerMap.add(lbc->serverIndex(), lbc);
1028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029 return NO_ERROR;
1030}
1031
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001032status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033{
1034 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1035 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001036 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001037 sp<LayerBaseClient> layer =
1038 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001039 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040 mLayerMap.removeItem(layer->serverIndex());
1041 }
1042 return NO_ERROR;
1043 }
1044 // it's possible that we don't find a layer, because it might
1045 // have been destroyed already -- this is not technically an error
Mathias Agopian9a112062009-04-17 19:36:26 -07001046 // from the user because there is a race between BClient::destroySurface(),
1047 // ~BClient() and destroySurface-from-a-transaction.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048 return (index == NAME_NOT_FOUND) ? status_t(NO_ERROR) : index;
1049}
1050
Mathias Agopian9a112062009-04-17 19:36:26 -07001051status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1052{
1053 // First add the layer to the purgatory list, which makes sure it won't
1054 // go away, then remove it from the main list (through a transaction).
1055 ssize_t err = removeLayer_l(layerBase);
1056 if (err >= 0) {
1057 mLayerPurgatory.add(layerBase);
1058 }
1059 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1060}
1061
1062
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001063void SurfaceFlinger::free_resources_l()
1064{
1065 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001066 mLayersRemoved = false;
1067
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 // free resources associated with disconnected clients
1069 SortedVector<Client*>& scheduledBroadcasts(mScheduledBroadcasts);
1070 Vector<Client*>& disconnectedClients(mDisconnectedClients);
1071 const size_t count = disconnectedClients.size();
1072 for (size_t i=0 ; i<count ; i++) {
1073 Client* client = disconnectedClients[i];
1074 // if this client is the scheduled broadcast list,
1075 // remove it from there (and we don't need to signal it
1076 // since it is dead).
1077 int32_t index = scheduledBroadcasts.indexOf(client);
1078 if (index >= 0) {
1079 scheduledBroadcasts.removeItemsAt(index);
1080 }
1081 mTokens.release(client->cid);
1082 delete client;
1083 }
1084 disconnectedClients.clear();
1085}
1086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001087uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1088{
1089 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1090}
1091
1092uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1093{
1094 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1095 if ((old & flags)==0) { // wake the server up
1096 if (delay > 0) {
1097 signalDelayedEvent(delay);
1098 } else {
1099 signalEvent();
1100 }
1101 }
1102 return old;
1103}
1104
1105void SurfaceFlinger::openGlobalTransaction()
1106{
1107 android_atomic_inc(&mTransactionCount);
1108}
1109
1110void SurfaceFlinger::closeGlobalTransaction()
1111{
1112 if (android_atomic_dec(&mTransactionCount) == 1) {
1113 signalEvent();
1114 }
1115}
1116
1117status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1118{
1119 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1120 return BAD_VALUE;
1121
1122 Mutex::Autolock _l(mStateLock);
1123 mCurrentState.freezeDisplay = 1;
1124 setTransactionFlags(eTransactionNeeded);
1125
1126 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001127 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001128 return NO_ERROR;
1129}
1130
1131status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1132{
1133 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1134 return BAD_VALUE;
1135
1136 Mutex::Autolock _l(mStateLock);
1137 mCurrentState.freezeDisplay = 0;
1138 setTransactionFlags(eTransactionNeeded);
1139
1140 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001141 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142 return NO_ERROR;
1143}
1144
Mathias Agopianc08731e2009-03-27 18:11:38 -07001145int SurfaceFlinger::setOrientation(DisplayID dpy,
1146 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001147{
1148 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1149 return BAD_VALUE;
1150
1151 Mutex::Autolock _l(mStateLock);
1152 if (mCurrentState.orientation != orientation) {
1153 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001154 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155 mCurrentState.orientation = orientation;
1156 setTransactionFlags(eTransactionNeeded);
1157 mTransactionCV.wait(mStateLock);
1158 } else {
1159 orientation = BAD_VALUE;
1160 }
1161 }
1162 return orientation;
1163}
1164
1165sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1166 ISurfaceFlingerClient::surface_data_t* params,
1167 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1168 uint32_t flags)
1169{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001170 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171 sp<LayerBaseClient::Surface> surfaceHandle;
1172 Mutex::Autolock _l(mStateLock);
1173 Client* const c = mClientsMap.valueFor(clientId);
1174 if (UNLIKELY(!c)) {
1175 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1176 return surfaceHandle;
1177 }
1178
1179 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1180 int32_t id = c->generateId(pid);
1181 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1182 LOGE("createSurface() failed, generateId = %d", id);
1183 return surfaceHandle;
1184 }
1185
1186 switch (flags & eFXSurfaceMask) {
1187 case eFXSurfaceNormal:
1188 if (UNLIKELY(flags & ePushBuffers)) {
1189 layer = createPushBuffersSurfaceLocked(c, d, id, w, h, flags);
1190 } else {
1191 layer = createNormalSurfaceLocked(c, d, id, w, h, format, flags);
1192 }
1193 break;
1194 case eFXSurfaceBlur:
1195 layer = createBlurSurfaceLocked(c, d, id, w, h, flags);
1196 break;
1197 case eFXSurfaceDim:
1198 layer = createDimSurfaceLocked(c, d, id, w, h, flags);
1199 break;
1200 }
1201
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001202 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001203 setTransactionFlags(eTransactionNeeded);
1204 surfaceHandle = layer->getSurface();
1205 if (surfaceHandle != 0)
1206 surfaceHandle->getSurfaceData(params);
1207 }
1208
1209 return surfaceHandle;
1210}
1211
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001212sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213 Client* client, DisplayID display,
1214 int32_t id, uint32_t w, uint32_t h, PixelFormat format, uint32_t flags)
1215{
1216 // initialize the surfaces
1217 switch (format) { // TODO: take h/w into account
1218 case PIXEL_FORMAT_TRANSPARENT:
1219 case PIXEL_FORMAT_TRANSLUCENT:
1220 format = PIXEL_FORMAT_RGBA_8888;
1221 break;
1222 case PIXEL_FORMAT_OPAQUE:
1223 format = PIXEL_FORMAT_RGB_565;
1224 break;
1225 }
1226
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001227 sp<Layer> layer = new Layer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001228 status_t err = layer->setBuffers(client, w, h, format, flags);
1229 if (LIKELY(err == NO_ERROR)) {
1230 layer->initStates(w, h, flags);
1231 addLayer_l(layer);
1232 } else {
1233 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001234 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001235 }
1236 return layer;
1237}
1238
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001239sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001240 Client* client, DisplayID display,
1241 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1242{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001243 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244 layer->initStates(w, h, flags);
1245 addLayer_l(layer);
1246 return layer;
1247}
1248
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001249sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001250 Client* client, DisplayID display,
1251 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1252{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001253 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254 layer->initStates(w, h, flags);
1255 addLayer_l(layer);
1256 return layer;
1257}
1258
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001259sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001260 Client* client, DisplayID display,
1261 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1262{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001263 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264 layer->initStates(w, h, flags);
1265 addLayer_l(layer);
1266 return layer;
1267}
1268
Mathias Agopian9a112062009-04-17 19:36:26 -07001269status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270{
Mathias Agopian9a112062009-04-17 19:36:26 -07001271 /*
1272 * called by the window manager, when a surface should be marked for
1273 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001274 *
1275 * The surface is removed from the current and drawing lists, but placed
1276 * in the purgatory queue, so it's not destroyed right-away (we need
1277 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001278 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001279
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001280 Mutex::Autolock _l(mStateLock);
1281 sp<LayerBaseClient> layer = getLayerUser_l(index);
1282 status_t err = purgatorizeLayer_l(layer);
1283 if (err == NO_ERROR) {
1284 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001285 }
1286 return err;
1287}
1288
1289status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1290{
1291 /*
1292 * called by ~ISurface() when all references are gone
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001293 *
1294 * the surface must be removed from purgatory from the main thread
1295 * since its dtor must run from there (b/c of OpenGL ES).
Mathias Agopian9a112062009-04-17 19:36:26 -07001296 */
1297
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001298 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001299 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001300 sp<LayerBaseClient> layer;
1301 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001302 MessageDestroySurface(
1303 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1304 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001305 virtual bool handler() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001306 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001307 ssize_t idx = flinger->mLayerPurgatory.remove(layer);
1308 LOGE_IF(idx<0, "layer=%p is not in the purgatory list", layer.get());
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001309 return true;
1310 }
1311 };
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001312 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001313 return NO_ERROR;
1314}
1315
1316status_t SurfaceFlinger::setClientState(
1317 ClientID cid,
1318 int32_t count,
1319 const layer_state_t* states)
1320{
1321 Mutex::Autolock _l(mStateLock);
1322 uint32_t flags = 0;
1323 cid <<= 16;
1324 for (int i=0 ; i<count ; i++) {
1325 const layer_state_t& s = states[i];
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001326 const sp<LayerBaseClient>& layer = getLayerUser_l(s.surface | cid);
1327 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328 const uint32_t what = s.what;
1329 // check if it has been destroyed first
1330 if (what & eDestroyed) {
1331 if (removeLayer_l(layer) == NO_ERROR) {
1332 flags |= eTransactionNeeded;
1333 // we skip everything else... well, no, not really
1334 // we skip ONLY that transaction.
1335 continue;
1336 }
1337 }
1338 if (what & ePositionChanged) {
1339 if (layer->setPosition(s.x, s.y))
1340 flags |= eTraversalNeeded;
1341 }
1342 if (what & eLayerChanged) {
1343 if (layer->setLayer(s.z)) {
1344 mCurrentState.layersSortedByZ.reorder(
1345 layer, &Layer::compareCurrentStateZ);
1346 // we need traversal (state changed)
1347 // AND transaction (list changed)
1348 flags |= eTransactionNeeded|eTraversalNeeded;
1349 }
1350 }
1351 if (what & eSizeChanged) {
1352 if (layer->setSize(s.w, s.h))
1353 flags |= eTraversalNeeded;
1354 }
1355 if (what & eAlphaChanged) {
1356 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1357 flags |= eTraversalNeeded;
1358 }
1359 if (what & eMatrixChanged) {
1360 if (layer->setMatrix(s.matrix))
1361 flags |= eTraversalNeeded;
1362 }
1363 if (what & eTransparentRegionChanged) {
1364 if (layer->setTransparentRegionHint(s.transparentRegion))
1365 flags |= eTraversalNeeded;
1366 }
1367 if (what & eVisibilityChanged) {
1368 if (layer->setFlags(s.flags, s.mask))
1369 flags |= eTraversalNeeded;
1370 }
1371 }
1372 }
1373 if (flags) {
1374 setTransactionFlags(flags);
1375 }
1376 return NO_ERROR;
1377}
1378
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001379sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001381 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1382 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001383}
1384
1385void SurfaceFlinger::screenReleased(int dpy)
1386{
1387 // this may be called by a signal handler, we can't do too much in here
1388 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1389 signalEvent();
1390}
1391
1392void SurfaceFlinger::screenAcquired(int dpy)
1393{
1394 // this may be called by a signal handler, we can't do too much in here
1395 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1396 signalEvent();
1397}
1398
1399status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1400{
1401 const size_t SIZE = 1024;
1402 char buffer[SIZE];
1403 String8 result;
1404 if (checkCallingPermission(
1405 String16("android.permission.DUMP")) == false)
1406 { // not allowed
1407 snprintf(buffer, SIZE, "Permission Denial: "
1408 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1409 IPCThreadState::self()->getCallingPid(),
1410 IPCThreadState::self()->getCallingUid());
1411 result.append(buffer);
1412 } else {
1413 Mutex::Autolock _l(mStateLock);
1414 size_t s = mClientsMap.size();
1415 char name[64];
1416 for (size_t i=0 ; i<s ; i++) {
1417 Client* client = mClientsMap.valueAt(i);
1418 sprintf(name, " Client (id=0x%08x)", client->cid);
1419 client->dump(name);
1420 }
1421 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1422 const size_t count = currentLayers.size();
1423 for (size_t i=0 ; i<count ; i++) {
1424 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001425 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001426 const Layer::State& s = layer->drawingState();
1427 snprintf(buffer, SIZE,
1428 "+ %s %p\n"
1429 " "
1430 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1431 "needsBlending=%1d, invalidate=%1d, "
1432 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001433 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001434 s.z, layer->tx(), layer->ty(), s.w, s.h,
1435 layer->needsBlending(), layer->contentDirty,
1436 s.alpha, s.flags,
1437 s.transform[0], s.transform[1],
1438 s.transform[2], s.transform[3]);
1439 result.append(buffer);
1440 buffer[0] = 0;
1441 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001442 sp<LayerBaseClient> lbc =
1443 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1444 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001445 snprintf(buffer, SIZE,
1446 " "
1447 "id=0x%08x, client=0x%08x, identity=%u\n",
1448 lbc->clientIndex(), lbc->client ? lbc->client->cid : 0,
1449 lbc->getIdentity());
1450 }
1451 result.append(buffer);
1452 buffer[0] = 0;
1453 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001454 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1455 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001456 const LayerBitmap& buf0(l->getBuffer(0));
1457 const LayerBitmap& buf1(l->getBuffer(1));
1458 snprintf(buffer, SIZE,
1459 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001460 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461 " freezeLock=%p, swapState=0x%08x\n",
1462 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001463 buf0.getWidth(), buf0.getHeight(),
1464 buf0.getBuffer()->getStride(),
1465 buf1.getWidth(), buf1.getHeight(),
1466 buf1.getBuffer()->getStride(),
1467 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468 l->lcblk->swapState);
1469 }
1470 result.append(buffer);
1471 buffer[0] = 0;
1472 s.transparentRegion.dump(result, "transparentRegion");
1473 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1474 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1475 }
1476 mWormholeRegion.dump(result, "WormholeRegion");
1477 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1478 snprintf(buffer, SIZE,
1479 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1480 mFreezeDisplay?"yes":"no", mFreezeCount,
1481 mCurrentState.orientation, hw.canDraw());
1482 result.append(buffer);
1483
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001484 const BufferAllocator& alloc(BufferAllocator::get());
1485 alloc.dump(result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001486 }
1487 write(fd, result.string(), result.size());
1488 return NO_ERROR;
1489}
1490
1491status_t SurfaceFlinger::onTransact(
1492 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1493{
1494 switch (code) {
1495 case CREATE_CONNECTION:
1496 case OPEN_GLOBAL_TRANSACTION:
1497 case CLOSE_GLOBAL_TRANSACTION:
1498 case SET_ORIENTATION:
1499 case FREEZE_DISPLAY:
1500 case UNFREEZE_DISPLAY:
1501 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001502 {
1503 // codes that require permission check
1504 IPCThreadState* ipc = IPCThreadState::self();
1505 const int pid = ipc->getCallingPid();
1506 const int self_pid = getpid();
1507 if (UNLIKELY(pid != self_pid)) {
1508 // we're called from a different process, do the real check
1509 if (!checkCallingPermission(
1510 String16("android.permission.ACCESS_SURFACE_FLINGER")))
1511 {
1512 const int uid = ipc->getCallingUid();
1513 LOGE("Permission Denial: "
1514 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1515 return PERMISSION_DENIED;
1516 }
1517 }
1518 }
1519 }
1520
1521 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1522 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1523 // HARDWARE_TEST stuff...
1524 if (UNLIKELY(checkCallingPermission(
1525 String16("android.permission.HARDWARE_TEST")) == false))
1526 { // not allowed
1527 LOGE("Permission Denial: pid=%d, uid=%d\n",
1528 IPCThreadState::self()->getCallingPid(),
1529 IPCThreadState::self()->getCallingUid());
1530 return PERMISSION_DENIED;
1531 }
1532 int n;
1533 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001534 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001536 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001537 return NO_ERROR;
1538 case 1002: // SHOW_UPDATES
1539 n = data.readInt32();
1540 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1541 return NO_ERROR;
1542 case 1003: // SHOW_BACKGROUND
1543 n = data.readInt32();
1544 mDebugBackground = n ? 1 : 0;
1545 return NO_ERROR;
1546 case 1004:{ // repaint everything
1547 Mutex::Autolock _l(mStateLock);
1548 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1549 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1550 signalEvent();
1551 }
1552 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553 case 1007: // set mFreezeCount
1554 mFreezeCount = data.readInt32();
1555 return NO_ERROR;
1556 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001557 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001558 reply->writeInt32(0);
1559 reply->writeInt32(mDebugRegion);
1560 reply->writeInt32(mDebugBackground);
1561 return NO_ERROR;
1562 case 1013: {
1563 Mutex::Autolock _l(mStateLock);
1564 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1565 reply->writeInt32(hw.getPageFlipCount());
1566 }
1567 return NO_ERROR;
1568 }
1569 }
1570 return err;
1571}
1572
1573// ---------------------------------------------------------------------------
1574#if 0
1575#pragma mark -
1576#endif
1577
1578Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1579 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1580{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581 const int pgsize = getpagesize();
1582 const int cblksize=((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1583 mCblkHeap = new MemoryDealer(cblksize);
1584 mCblkMemory = mCblkHeap->allocate(cblksize);
1585 if (mCblkMemory != 0) {
1586 ctrlblk = static_cast<per_client_cblk_t *>(mCblkMemory->pointer());
1587 if (ctrlblk) { // construct the shared structure in-place.
1588 new(ctrlblk) per_client_cblk_t;
1589 }
1590 }
1591}
1592
1593Client::~Client() {
1594 if (ctrlblk) {
1595 const int pgsize = getpagesize();
1596 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1597 }
1598}
1599
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001600int32_t Client::generateId(int pid)
1601{
1602 const uint32_t i = clz( ~mBitmap );
1603 if (i >= NUM_LAYERS_MAX) {
1604 return NO_MEMORY;
1605 }
1606 mPid = pid;
1607 mInUse.add(uint8_t(i));
1608 mBitmap |= 1<<(31-i);
1609 return i;
1610}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001611
1612status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001613{
1614 ssize_t idx = mInUse.indexOf(id);
1615 if (idx < 0)
1616 return NAME_NOT_FOUND;
1617 return mLayers.insertAt(layer, idx);
1618}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001620void Client::free(int32_t id)
1621{
1622 ssize_t idx = mInUse.remove(uint8_t(id));
1623 if (idx >= 0) {
1624 mBitmap &= ~(1<<(31-id));
1625 mLayers.removeItemsAt(idx);
1626 }
1627}
1628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001629bool Client::isValid(int32_t i) const {
1630 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1631}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001632
1633sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1634 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001635 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001636 if (idx >= 0) {
1637 lbc = mLayers[idx].promote();
1638 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1639 }
1640 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001641}
1642
1643void Client::dump(const char* what)
1644{
1645}
1646
1647// ---------------------------------------------------------------------------
1648#if 0
1649#pragma mark -
1650#endif
1651
1652BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemory>& cblk)
1653 : mId(cid), mFlinger(flinger), mCblk(cblk)
1654{
1655}
1656
1657BClient::~BClient() {
1658 // destroy all resources attached to this client
1659 mFlinger->destroyConnection(mId);
1660}
1661
1662void BClient::getControlBlocks(sp<IMemory>* ctrl) const {
1663 *ctrl = mCblk;
1664}
1665
1666sp<ISurface> BClient::createSurface(
1667 ISurfaceFlingerClient::surface_data_t* params, int pid,
1668 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1669 uint32_t flags)
1670{
1671 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1672}
1673
1674status_t BClient::destroySurface(SurfaceID sid)
1675{
1676 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001677 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001678}
1679
1680status_t BClient::setState(int32_t count, const layer_state_t* states)
1681{
1682 return mFlinger->setClientState(mId, count, states);
1683}
1684
1685// ---------------------------------------------------------------------------
1686
1687GraphicPlane::GraphicPlane()
1688 : mHw(0)
1689{
1690}
1691
1692GraphicPlane::~GraphicPlane() {
1693 delete mHw;
1694}
1695
1696bool GraphicPlane::initialized() const {
1697 return mHw ? true : false;
1698}
1699
1700void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1701 mHw = hw;
1702}
1703
1704void GraphicPlane::setTransform(const Transform& tr) {
1705 mTransform = tr;
1706 mGlobalTransform = mOrientationTransform * mTransform;
1707}
1708
1709status_t GraphicPlane::orientationToTransfrom(
1710 int orientation, int w, int h, Transform* tr)
1711{
1712 float a, b, c, d, x, y;
1713 switch (orientation) {
1714 case ISurfaceComposer::eOrientationDefault:
1715 a=1; b=0; c=0; d=1; x=0; y=0;
1716 break;
1717 case ISurfaceComposer::eOrientation90:
1718 a=0; b=-1; c=1; d=0; x=w; y=0;
1719 break;
1720 case ISurfaceComposer::eOrientation180:
1721 a=-1; b=0; c=0; d=-1; x=w; y=h;
1722 break;
1723 case ISurfaceComposer::eOrientation270:
1724 a=0; b=1; c=-1; d=0; x=0; y=h;
1725 break;
1726 default:
1727 return BAD_VALUE;
1728 }
1729 tr->set(a, b, c, d);
1730 tr->set(x, y);
1731 return NO_ERROR;
1732}
1733
1734status_t GraphicPlane::setOrientation(int orientation)
1735{
1736 const DisplayHardware& hw(displayHardware());
1737 const float w = hw.getWidth();
1738 const float h = hw.getHeight();
1739
1740 if (orientation == ISurfaceComposer::eOrientationDefault) {
1741 // make sure the default orientation is optimal
1742 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001743 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001744 mGlobalTransform = mTransform;
1745 return NO_ERROR;
1746 }
1747
1748 // If the rotation can be handled in hardware, this is where
1749 // the magic should happen.
1750 if (UNLIKELY(orientation == 42)) {
1751 float a, b, c, d, x, y;
1752 const float r = (3.14159265f / 180.0f) * 42.0f;
1753 const float si = sinf(r);
1754 const float co = cosf(r);
1755 a=co; b=-si; c=si; d=co;
1756 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1757 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1758 mOrientationTransform.set(a, b, c, d);
1759 mOrientationTransform.set(x, y);
1760 } else {
1761 GraphicPlane::orientationToTransfrom(orientation, w, h,
1762 &mOrientationTransform);
1763 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001764 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765 mGlobalTransform = mOrientationTransform * mTransform;
1766 return NO_ERROR;
1767}
1768
1769const DisplayHardware& GraphicPlane::displayHardware() const {
1770 return *mHw;
1771}
1772
1773const Transform& GraphicPlane::transform() const {
1774 return mGlobalTransform;
1775}
1776
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001777EGLDisplay GraphicPlane::getEGLDisplay() const {
1778 return mHw->getEGLDisplay();
1779}
1780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781// ---------------------------------------------------------------------------
1782
1783}; // namespace android