blob: a72294a2ac1d06a4ac09e1b586db18c179acd3c7 [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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070034#include <binder/MemoryHeapBase.h>
35
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036#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
Mathias Agopiana1ecca92009-05-21 19:21:59 -070057/* ideally AID_GRAPHICS would be in a semi-public header
58 * or there would be a way to map a user/group name to its id
59 */
60#ifndef AID_GRAPHICS
61#define AID_GRAPHICS 1003
62#endif
63
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#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(
Mathias Agopian076b1cc2009-04-10 14:24:30 -070089 const sp<LayerBase>& key, size_t guess) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090{
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);
Mathias Agopian076b1cc2009-04-10 14:24:30 -070096 LOGE_IF(layers[idx]!=key,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097 "LayerVector[%p]: layers[%d]=%p, key=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -070098 this, int(idx), layers[idx].get(), key.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099 return idx;
100 }
101 return i;
102}
103
104ssize_t SurfaceFlinger::LayerVector::add(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700105 const sp<LayerBase>& layer,
106 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107{
108 size_t count = layers.size();
109 ssize_t l = 0;
110 ssize_t h = count-1;
111 ssize_t mid;
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700112 sp<LayerBase> const* a = layers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113 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
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136{
137 const ssize_t keyIndex = lookup.indexOfKey(layer);
138 if (keyIndex >= 0) {
139 const size_t index = lookup.valueAt(keyIndex);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700140 LOGE_IF(layers[index]!=layer,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 "LayerVector[%p]: layers[%u]=%p, layer=%p",
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700142 this, int(index), layers[index].get(), layer.get());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 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(
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700157 const sp<LayerBase>& layer,
158 Vector< sp<LayerBase> >::compar_t cmp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159{
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),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700176 mLayersRemoved(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 mBootTime(systemTime()),
Mathias Agopian375f5632009-06-15 18:24:59 -0700178 mHardwareTest("android.permission.HARDWARE_TEST"),
179 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
180 mDump("android.permission.DUMP"),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 mLastScheduledBroadcast(NULL),
182 mVisibleRegionsDirty(false),
183 mDeferReleaseConsole(false),
184 mFreezeDisplay(false),
185 mFreezeCount(0),
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700186 mFreezeDisplayTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187 mDebugRegion(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188 mDebugBackground(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700189 mDebugInSwapBuffers(0),
190 mLastSwapBufferTime(0),
191 mDebugInTransaction(0),
192 mLastTransactionTime(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193 mConsoleSignals(0),
194 mSecureFrameBuffer(0)
195{
196 init();
197}
198
199void SurfaceFlinger::init()
200{
201 LOGI("SurfaceFlinger is starting");
202
203 // debugging stuff...
204 char value[PROPERTY_VALUE_MAX];
205 property_get("debug.sf.showupdates", value, "0");
206 mDebugRegion = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 property_get("debug.sf.showbackground", value, "0");
208 mDebugBackground = atoi(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
210 LOGI_IF(mDebugRegion, "showupdates enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 LOGI_IF(mDebugBackground, "showbackground enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212}
213
214SurfaceFlinger::~SurfaceFlinger()
215{
216 glDeleteTextures(1, &mWormholeTexName);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217}
218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
220{
221 return graphicPlane(0).displayHardware().getOverlayEngine();
222}
223
Mathias Agopian7303c6b2009-07-02 18:11:53 -0700224sp<IMemoryHeap> SurfaceFlinger::getCblk() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225{
Mathias Agopian7303c6b2009-07-02 18:11:53 -0700226 return mServerHeap;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227}
228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229sp<ISurfaceFlingerClient> SurfaceFlinger::createConnection()
230{
231 Mutex::Autolock _l(mStateLock);
232 uint32_t token = mTokens.acquire();
233
Mathias Agopianf9d93272009-06-19 17:00:27 -0700234 sp<Client> client = new Client(token, this);
235 if (client->ctrlblk == 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 mTokens.release(token);
237 return 0;
238 }
239 status_t err = mClientsMap.add(token, client);
240 if (err < 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 mTokens.release(token);
242 return 0;
243 }
244 sp<BClient> bclient =
Mathias Agopian7303c6b2009-07-02 18:11:53 -0700245 new BClient(this, token, client->getControlBlockMemory());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 return bclient;
247}
248
249void SurfaceFlinger::destroyConnection(ClientID cid)
250{
251 Mutex::Autolock _l(mStateLock);
Mathias Agopianf9d93272009-06-19 17:00:27 -0700252 sp<Client> client = mClientsMap.valueFor(cid);
253 if (client != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 // free all the layers this client owns
Mathias Agopian3d579642009-06-04 18:46:21 -0700255 Vector< wp<LayerBaseClient> > layers(client->getLayers());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 const size_t count = layers.size();
257 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700258 sp<LayerBaseClient> layer(layers[i].promote());
259 if (layer != 0) {
Mathias Agopian3d579642009-06-04 18:46:21 -0700260 purgatorizeLayer_l(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 }
263
264 // the resources associated with this client will be freed
265 // during the next transaction, after these surfaces have been
266 // properly removed from the screen
267
268 // remove this client from our ClientID->Client mapping.
269 mClientsMap.removeItem(cid);
270
271 // and add it to the list of disconnected clients
272 mDisconnectedClients.add(client);
273
274 // request a transaction
275 setTransactionFlags(eTransactionNeeded);
276 }
277}
278
279const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
280{
281 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
282 const GraphicPlane& plane(mGraphicPlanes[dpy]);
283 return plane;
284}
285
286GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
287{
288 return const_cast<GraphicPlane&>(
289 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
290}
291
292void SurfaceFlinger::bootFinished()
293{
294 const nsecs_t now = systemTime();
295 const nsecs_t duration = now - mBootTime;
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700296 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
297 property_set("ctl.stop", "bootanim");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298}
299
300void SurfaceFlinger::onFirstRef()
301{
302 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
303
304 // Wait for the main thread to be done with its initialization
305 mReadyToRunBarrier.wait();
306}
307
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308static inline uint16_t pack565(int r, int g, int b) {
309 return (r<<11)|(g<<5)|b;
310}
311
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312status_t SurfaceFlinger::readyToRun()
313{
314 LOGI( "SurfaceFlinger's main thread ready to run. "
315 "Initializing graphics H/W...");
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317 // we only support one display currently
318 int dpy = 0;
319
320 {
321 // initialize the main display
322 GraphicPlane& plane(graphicPlane(dpy));
323 DisplayHardware* const hw = new DisplayHardware(this, dpy);
324 plane.setDisplayHardware(hw);
325 }
326
Mathias Agopian7303c6b2009-07-02 18:11:53 -0700327 // create the shared control-block
328 mServerHeap = new MemoryHeapBase(4096,
329 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
330 LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
331
332 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
333 LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
334
335 new(mServerCblk) surface_flinger_cblk_t;
336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 // initialize primary screen
338 // (other display should be initialized in the same manner, but
339 // asynchronously, as they could come and go. None of this is supported
340 // yet).
341 const GraphicPlane& plane(graphicPlane(dpy));
342 const DisplayHardware& hw = plane.displayHardware();
343 const uint32_t w = hw.getWidth();
344 const uint32_t h = hw.getHeight();
345 const uint32_t f = hw.getFormat();
346 hw.makeCurrent();
347
348 // initialize the shared control block
349 mServerCblk->connected |= 1<<dpy;
350 display_cblk_t* dcblk = mServerCblk->displays + dpy;
351 memset(dcblk, 0, sizeof(display_cblk_t));
352 dcblk->w = w;
353 dcblk->h = h;
354 dcblk->format = f;
355 dcblk->orientation = ISurfaceComposer::eOrientationDefault;
356 dcblk->xdpi = hw.getDpiX();
357 dcblk->ydpi = hw.getDpiY();
358 dcblk->fps = hw.getRefreshRate();
359 dcblk->density = hw.getDensity();
360 asm volatile ("":::"memory");
361
362 // Initialize OpenGL|ES
363 glActiveTexture(GL_TEXTURE0);
364 glBindTexture(GL_TEXTURE_2D, 0);
365 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
366 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
367 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
368 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
369 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
370 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
371 glPixelStorei(GL_PACK_ALIGNMENT, 4);
372 glEnableClientState(GL_VERTEX_ARRAY);
373 glEnable(GL_SCISSOR_TEST);
374 glShadeModel(GL_FLAT);
375 glDisable(GL_DITHER);
376 glDisable(GL_CULL_FACE);
377
378 const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
379 const uint16_t g1 = pack565(0x17,0x2f,0x17);
380 const uint16_t textureData[4] = { g0, g1, g1, g0 };
381 glGenTextures(1, &mWormholeTexName);
382 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
383 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
384 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
385 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
386 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
387 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
388 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
389
390 glViewport(0, 0, w, h);
391 glMatrixMode(GL_PROJECTION);
392 glLoadIdentity();
393 glOrthof(0, w, h, 0, 0, 1);
394
395 LayerDim::initDimmer(this, w, h);
396
397 mReadyToRunBarrier.open();
398
399 /*
400 * We're now ready to accept clients...
401 */
402
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700403 // start boot animation
404 property_set("ctl.start", "bootanim");
405
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406 return NO_ERROR;
407}
408
409// ----------------------------------------------------------------------------
410#if 0
411#pragma mark -
412#pragma mark Events Handler
413#endif
414
415void SurfaceFlinger::waitForEvent()
416{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700417 while (true) {
418 nsecs_t timeout = -1;
419 if (UNLIKELY(isFrozen())) {
420 // wait 5 seconds
421 const nsecs_t freezeDisplayTimeout = ms2ns(5000);
422 const nsecs_t now = systemTime();
423 if (mFreezeDisplayTime == 0) {
424 mFreezeDisplayTime = now;
425 }
426 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
427 timeout = waitTime>0 ? waitTime : 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700428 }
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700429
Mathias Agopianb6683b52009-04-28 03:17:50 -0700430 MessageList::value_type msg = mEventQueue.waitMessage(timeout);
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700431 if (msg != 0) {
432 mFreezeDisplayTime = 0;
433 switch (msg->what) {
434 case MessageQueue::INVALIDATE:
435 // invalidate message, just return to the main loop
436 return;
437 }
438 } else {
439 // we timed out
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 if (isFrozen()) {
441 // we timed out and are still frozen
442 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
443 mFreezeDisplay, mFreezeCount);
444 mFreezeCount = 0;
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700445 mFreezeDisplay = false;
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700446 return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447 }
448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
450}
451
452void SurfaceFlinger::signalEvent() {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700453 mEventQueue.invalidate();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
456void SurfaceFlinger::signal() const {
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700457 // this is the IPC call
458 const_cast<SurfaceFlinger*>(this)->signalEvent();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800459}
460
461void SurfaceFlinger::signalDelayedEvent(nsecs_t delay)
462{
Mathias Agopianf1d8e872009-04-20 19:39:12 -0700463 mEventQueue.postMessage( new MessageBase(MessageQueue::INVALIDATE), delay);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464}
465
466// ----------------------------------------------------------------------------
467#if 0
468#pragma mark -
469#pragma mark Main loop
470#endif
471
472bool SurfaceFlinger::threadLoop()
473{
474 waitForEvent();
475
476 // check for transactions
477 if (UNLIKELY(mConsoleSignals)) {
478 handleConsoleEvents();
479 }
480
481 if (LIKELY(mTransactionCount == 0)) {
482 // if we're in a global transaction, don't do anything.
483 const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
484 uint32_t transactionFlags = getTransactionFlags(mask);
485 if (LIKELY(transactionFlags)) {
486 handleTransaction(transactionFlags);
487 }
488 }
489
490 // post surfaces (if needed)
491 handlePageFlip();
492
493 const DisplayHardware& hw(graphicPlane(0).displayHardware());
494 if (LIKELY(hw.canDraw())) {
495 // repaint the framebuffer (if needed)
496 handleRepaint();
497
498 // release the clients before we flip ('cause flip might block)
499 unlockClients();
500 executeScheduledBroadcasts();
501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502 postFramebuffer();
503 } else {
504 // pretend we did the post
505 unlockClients();
506 executeScheduledBroadcasts();
507 usleep(16667); // 60 fps period
508 }
509 return true;
510}
511
512void SurfaceFlinger::postFramebuffer()
513{
Mathias Agopian0926f502009-05-04 14:17:04 -0700514 if (isFrozen()) {
515 // we are not allowed to draw, but pause a bit to make sure
516 // apps don't end up using the whole CPU, if they depend on
517 // surfaceflinger for synchronization.
518 usleep(8333); // 8.3ms ~ 120fps
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519 return;
520 }
521
522 if (!mInvalidRegion.isEmpty()) {
523 const DisplayHardware& hw(graphicPlane(0).displayHardware());
Mathias Agopian9795c422009-08-26 16:36:26 -0700524 const nsecs_t now = systemTime();
525 mDebugInSwapBuffers = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526 hw.flip(mInvalidRegion);
Mathias Agopian9795c422009-08-26 16:36:26 -0700527 mLastSwapBufferTime = systemTime() - now;
528 mDebugInSwapBuffers = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529 mInvalidRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 }
531}
532
533void SurfaceFlinger::handleConsoleEvents()
534{
535 // something to do with the console
536 const DisplayHardware& hw = graphicPlane(0).displayHardware();
537
538 int what = android_atomic_and(0, &mConsoleSignals);
539 if (what & eConsoleAcquired) {
540 hw.acquireScreen();
541 }
542
543 if (mDeferReleaseConsole && hw.canDraw()) {
Mathias Agopian62b74442009-04-14 23:02:51 -0700544 // We got the release signal before the acquire signal
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545 mDeferReleaseConsole = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 hw.releaseScreen();
547 }
548
549 if (what & eConsoleReleased) {
550 if (hw.canDraw()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551 hw.releaseScreen();
552 } else {
553 mDeferReleaseConsole = true;
554 }
555 }
556
557 mDirtyRegion.set(hw.bounds());
558}
559
560void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
561{
Mathias Agopian3d579642009-06-04 18:46:21 -0700562 Vector< sp<LayerBase> > ditchedLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800563
Mathias Agopian3d579642009-06-04 18:46:21 -0700564 { // scope for the lock
565 Mutex::Autolock _l(mStateLock);
Mathias Agopian9795c422009-08-26 16:36:26 -0700566 const nsecs_t now = systemTime();
567 mDebugInTransaction = now;
Mathias Agopian3d579642009-06-04 18:46:21 -0700568 handleTransactionLocked(transactionFlags, ditchedLayers);
Mathias Agopian9795c422009-08-26 16:36:26 -0700569 mLastTransactionTime = systemTime() - now;
570 mDebugInTransaction = 0;
Mathias Agopian3d579642009-06-04 18:46:21 -0700571 }
572
573 // do this without lock held
574 const size_t count = ditchedLayers.size();
575 for (size_t i=0 ; i<count ; i++) {
576 //LOGD("ditching layer %p", ditchedLayers[i].get());
577 ditchedLayers[i]->ditch();
578 }
579}
580
581void SurfaceFlinger::handleTransactionLocked(
582 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
583{
584 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585 const size_t count = currentLayers.size();
586
587 /*
588 * Traversal of the children
589 * (perform the transaction for each of them if needed)
590 */
591
592 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
593 if (layersNeedTransaction) {
594 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700595 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800596 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
597 if (!trFlags) continue;
598
599 const uint32_t flags = layer->doTransaction(0);
600 if (flags & Layer::eVisibleRegion)
601 mVisibleRegionsDirty = true;
602
603 if (flags & Layer::eRestartTransaction) {
604 // restart the transaction, but back-off a little
605 layer->setTransactionFlags(eTransactionNeeded);
606 setTransactionFlags(eTraversalNeeded, ms2ns(8));
607 }
608 }
609 }
610
611 /*
612 * Perform our own transaction if needed
613 */
614
615 if (transactionFlags & eTransactionNeeded) {
616 if (mCurrentState.orientation != mDrawingState.orientation) {
617 // the orientation has changed, recompute all visible regions
618 // and invalidate everything.
619
620 const int dpy = 0;
621 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700622 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800623 GraphicPlane& plane(graphicPlane(dpy));
624 plane.setOrientation(orientation);
625
626 // update the shared control block
627 const DisplayHardware& hw(plane.displayHardware());
628 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
629 dcblk->orientation = orientation;
630 if (orientation & eOrientationSwapMask) {
631 // 90 or 270 degrees orientation
632 dcblk->w = hw.getHeight();
633 dcblk->h = hw.getWidth();
634 } else {
635 dcblk->w = hw.getWidth();
636 dcblk->h = hw.getHeight();
637 }
638
639 mVisibleRegionsDirty = true;
640 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700641 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642 }
643
644 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
645 // freezing or unfreezing the display -> trigger animation if needed
646 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647 }
648
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700649 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
650 // layers have been added
651 mVisibleRegionsDirty = true;
652 }
653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 // some layers might have been removed, so
655 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700656 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700658 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
Mathias Agopian3d579642009-06-04 18:46:21 -0700659 const size_t count = previousLayers.size();
660 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700661 const sp<LayerBase>& layer(previousLayers[i]);
662 if (currentLayers.indexOf( layer ) < 0) {
663 // this layer is not visible anymore
Mathias Agopian3d579642009-06-04 18:46:21 -0700664 ditchedLayers.add(layer);
Mathias Agopian5d7126b2009-07-28 14:20:21 -0700665 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700666 }
667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800668 }
669
670 // get rid of all resources we don't need anymore
671 // (layers and clients)
672 free_resources_l();
673 }
674
675 commitTransaction();
676}
677
678sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
679{
680 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
681}
682
683void SurfaceFlinger::computeVisibleRegions(
684 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
685{
686 const GraphicPlane& plane(graphicPlane(0));
687 const Transform& planeTransform(plane.transform());
688
689 Region aboveOpaqueLayers;
690 Region aboveCoveredLayers;
691 Region dirty;
692
693 bool secureFrameBuffer = false;
694
695 size_t i = currentLayers.size();
696 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700697 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800698 layer->validateVisibility(planeTransform);
699
700 // start with the whole surface at its current location
Mathias Agopian97011222009-07-28 10:57:27 -0700701 const Layer::State& s(layer->drawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800702
703 // handle hidden surfaces by setting the visible region to empty
704 Region opaqueRegion;
705 Region visibleRegion;
706 Region coveredRegion;
Mathias Agopian97011222009-07-28 10:57:27 -0700707 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708 const bool translucent = layer->needsBlending();
Mathias Agopian97011222009-07-28 10:57:27 -0700709 const Rect bounds(layer->visibleBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800710 visibleRegion.set(bounds);
711 coveredRegion = visibleRegion;
712
713 // Remove the transparent area from the visible region
714 if (translucent) {
715 visibleRegion.subtractSelf(layer->transparentRegionScreen);
716 }
717
718 // compute the opaque region
719 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
720 // the opaque region is the visible region
721 opaqueRegion = visibleRegion;
722 }
723 }
724
725 // subtract the opaque region covered by the layers above us
726 visibleRegion.subtractSelf(aboveOpaqueLayers);
727 coveredRegion.andSelf(aboveCoveredLayers);
728
729 // compute this layer's dirty region
730 if (layer->contentDirty) {
731 // we need to invalidate the whole region
732 dirty = visibleRegion;
733 // as well, as the old visible region
734 dirty.orSelf(layer->visibleRegionScreen);
735 layer->contentDirty = false;
736 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -0700737 /* compute the exposed region:
738 * exposed = what's VISIBLE and NOT COVERED now
739 * but was COVERED before
740 */
741 dirty = (visibleRegion - coveredRegion) & layer->coveredRegionScreen;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742 }
743 dirty.subtractSelf(aboveOpaqueLayers);
744
745 // accumulate to the screen dirty region
746 dirtyRegion.orSelf(dirty);
747
Mathias Agopian62b74442009-04-14 23:02:51 -0700748 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749 aboveOpaqueLayers.orSelf(opaqueRegion);
Mathias Agopiana8d44f72009-06-28 02:54:16 -0700750 aboveCoveredLayers.orSelf(visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751
752 // Store the visible region is screen space
753 layer->setVisibleRegion(visibleRegion);
754 layer->setCoveredRegion(coveredRegion);
755
Mathias Agopian97011222009-07-28 10:57:27 -0700756 // If a secure layer is partially visible, lock-down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800757 if (layer->isSecure() && !visibleRegion.isEmpty()) {
758 secureFrameBuffer = true;
759 }
760 }
761
Mathias Agopian97011222009-07-28 10:57:27 -0700762 // invalidate the areas where a layer was removed
763 dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
764 mDirtyRegionRemovedLayer.clear();
765
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800766 mSecureFrameBuffer = secureFrameBuffer;
767 opaqueRegion = aboveOpaqueLayers;
768}
769
770
771void SurfaceFlinger::commitTransaction()
772{
773 mDrawingState = mCurrentState;
774 mTransactionCV.signal();
775}
776
777void SurfaceFlinger::handlePageFlip()
778{
779 bool visibleRegions = mVisibleRegionsDirty;
780 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
781 visibleRegions |= lockPageFlip(currentLayers);
782
783 const DisplayHardware& hw = graphicPlane(0).displayHardware();
784 const Region screenRegion(hw.bounds());
785 if (visibleRegions) {
786 Region opaqueRegion;
787 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
788 mWormholeRegion = screenRegion.subtract(opaqueRegion);
789 mVisibleRegionsDirty = false;
790 }
791
792 unlockPageFlip(currentLayers);
793 mDirtyRegion.andSelf(screenRegion);
794}
795
796bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
797{
798 bool recomputeVisibleRegions = false;
799 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700800 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700802 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800803 layer->lockPageFlip(recomputeVisibleRegions);
804 }
805 return recomputeVisibleRegions;
806}
807
808void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
809{
810 const GraphicPlane& plane(graphicPlane(0));
811 const Transform& planeTransform(plane.transform());
812 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700813 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700815 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800816 layer->unlockPageFlip(planeTransform, mDirtyRegion);
817 }
818}
819
Mathias Agopianb8a55602009-06-26 19:06:36 -0700820
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800821void SurfaceFlinger::handleRepaint()
822{
Mathias Agopianb8a55602009-06-26 19:06:36 -0700823 // compute the invalid region
824 mInvalidRegion.orSelf(mDirtyRegion);
825 if (mInvalidRegion.isEmpty()) {
826 // nothing to do
827 return;
828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829
830 if (UNLIKELY(mDebugRegion)) {
831 debugFlashRegions();
832 }
833
Mathias Agopianb8a55602009-06-26 19:06:36 -0700834 // set the frame buffer
835 const DisplayHardware& hw(graphicPlane(0).displayHardware());
836 glMatrixMode(GL_MODELVIEW);
837 glLoadIdentity();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838
839 uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700840 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
841 (flags & DisplayHardware::BUFFER_PRESERVED))
842 {
Mathias Agopian29d06ac2009-06-29 18:49:56 -0700843 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
844 // takes a rectangle, we must make sure to update that whole
845 // rectangle in that case
846 if (flags & DisplayHardware::SWAP_RECTANGLE) {
847 // FIXME: we really should be able to pass a region to
848 // SWAP_RECTANGLE so that we don't have to redraw all this.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849 mDirtyRegion.set(mInvalidRegion.bounds());
850 } else {
Mathias Agopian29d06ac2009-06-29 18:49:56 -0700851 // in the BUFFER_PRESERVED case, obviously, we can update only
852 // what's needed and nothing more.
853 // NOTE: this is NOT a common case, as preserving the backbuffer
854 // is costly and usually involves copying the whole update back.
855 }
856 } else {
857 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
858 // We need to redraw the rectangle that will be updated
859 // (pushed to the framebuffer).
860 // This is needed because UPDATE_ON_DEMAND only takes one
861 // rectangle instead of a region (see DisplayHardware::flip())
862 mDirtyRegion.set(mInvalidRegion.bounds());
863 } else {
864 // we need to redraw everything (the whole screen)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800865 mDirtyRegion.set(hw.bounds());
866 mInvalidRegion = mDirtyRegion;
867 }
868 }
869
870 // compose all surfaces
871 composeSurfaces(mDirtyRegion);
872
873 // clear the dirty regions
874 mDirtyRegion.clear();
875}
876
877void SurfaceFlinger::composeSurfaces(const Region& dirty)
878{
879 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
880 // should never happen unless the window manager has a bug
881 // draw something...
882 drawWormhole();
883 }
884 const SurfaceFlinger& flinger(*this);
885 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
886 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700887 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700889 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800890 const Region& visibleRegion(layer->visibleRegionScreen);
891 if (!visibleRegion.isEmpty()) {
892 const Region clip(dirty.intersect(visibleRegion));
893 if (!clip.isEmpty()) {
894 layer->draw(clip);
895 }
896 }
897 }
898}
899
900void SurfaceFlinger::unlockClients()
901{
902 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
903 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700904 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800905 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700906 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907 layer->finishPageFlip();
908 }
909}
910
Mathias Agopianf9d93272009-06-19 17:00:27 -0700911void SurfaceFlinger::scheduleBroadcast(const sp<Client>& client)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800912{
913 if (mLastScheduledBroadcast != client) {
914 mLastScheduledBroadcast = client;
915 mScheduledBroadcasts.add(client);
916 }
917}
918
919void SurfaceFlinger::executeScheduledBroadcasts()
920{
Mathias Agopianf9d93272009-06-19 17:00:27 -0700921 SortedVector< wp<Client> >& list(mScheduledBroadcasts);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800922 size_t count = list.size();
923 while (count--) {
Mathias Agopianf9d93272009-06-19 17:00:27 -0700924 sp<Client> client = list[count].promote();
925 if (client != 0) {
926 per_client_cblk_t* const cblk = client->ctrlblk;
927 if (cblk->lock.tryLock() == NO_ERROR) {
928 cblk->cv.broadcast();
929 list.removeAt(count);
930 cblk->lock.unlock();
931 } else {
932 // schedule another round
933 LOGW("executeScheduledBroadcasts() skipped, "
934 "contention on the client. We'll try again later...");
935 signalDelayedEvent(ms2ns(4));
936 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800937 }
938 }
939 mLastScheduledBroadcast = 0;
940}
941
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800942void SurfaceFlinger::debugFlashRegions()
943{
Mathias Agopian0926f502009-05-04 14:17:04 -0700944 const DisplayHardware& hw(graphicPlane(0).displayHardware());
945 const uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700946
947 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
948 (flags & DisplayHardware::BUFFER_PRESERVED))) {
Mathias Agopian0926f502009-05-04 14:17:04 -0700949 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
950 mDirtyRegion.bounds() : hw.bounds());
951 composeSurfaces(repaint);
952 }
953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800954 glDisable(GL_TEXTURE_2D);
955 glDisable(GL_BLEND);
956 glDisable(GL_DITHER);
957 glDisable(GL_SCISSOR_TEST);
958
Mathias Agopian0926f502009-05-04 14:17:04 -0700959 static int toggle = 0;
960 toggle = 1 - toggle;
961 if (toggle) {
962 glColor4x(0x10000, 0, 0x10000, 0x10000);
963 } else {
964 glColor4x(0x10000, 0x10000, 0, 0x10000);
965 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800966
Mathias Agopian20f68782009-05-11 00:03:41 -0700967 Region::const_iterator it = mDirtyRegion.begin();
968 Region::const_iterator const end = mDirtyRegion.end();
969 while (it != end) {
970 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800971 GLfloat vertices[][2] = {
972 { r.left, r.top },
973 { r.left, r.bottom },
974 { r.right, r.bottom },
975 { r.right, r.top }
976 };
977 glVertexPointer(2, GL_FLOAT, 0, vertices);
978 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
979 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700980
Mathias Agopianb8a55602009-06-26 19:06:36 -0700981 if (mInvalidRegion.isEmpty()) {
982 mDirtyRegion.dump("mDirtyRegion");
983 mInvalidRegion.dump("mInvalidRegion");
984 }
985 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800986
987 if (mDebugRegion > 1)
988 usleep(mDebugRegion * 1000);
989
990 glEnable(GL_SCISSOR_TEST);
991 //mDirtyRegion.dump("mDirtyRegion");
992}
993
994void SurfaceFlinger::drawWormhole() const
995{
996 const Region region(mWormholeRegion.intersect(mDirtyRegion));
997 if (region.isEmpty())
998 return;
999
1000 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1001 const int32_t width = hw.getWidth();
1002 const int32_t height = hw.getHeight();
1003
1004 glDisable(GL_BLEND);
1005 glDisable(GL_DITHER);
1006
1007 if (LIKELY(!mDebugBackground)) {
1008 glClearColorx(0,0,0,0);
Mathias Agopian20f68782009-05-11 00:03:41 -07001009 Region::const_iterator it = region.begin();
1010 Region::const_iterator const end = region.end();
1011 while (it != end) {
1012 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013 const GLint sy = height - (r.top + r.height());
1014 glScissor(r.left, sy, r.width(), r.height());
1015 glClear(GL_COLOR_BUFFER_BIT);
1016 }
1017 } else {
1018 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1019 { width, height }, { 0, height } };
1020 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
1021 glVertexPointer(2, GL_SHORT, 0, vertices);
1022 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1023 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1024 glEnable(GL_TEXTURE_2D);
1025 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1026 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1027 glMatrixMode(GL_TEXTURE);
1028 glLoadIdentity();
1029 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
Mathias Agopian20f68782009-05-11 00:03:41 -07001030 Region::const_iterator it = region.begin();
1031 Region::const_iterator const end = region.end();
1032 while (it != end) {
1033 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001034 const GLint sy = height - (r.top + r.height());
1035 glScissor(r.left, sy, r.width(), r.height());
1036 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1037 }
1038 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1039 }
1040}
1041
1042void SurfaceFlinger::debugShowFPS() const
1043{
1044 static int mFrameCount;
1045 static int mLastFrameCount = 0;
1046 static nsecs_t mLastFpsTime = 0;
1047 static float mFps = 0;
1048 mFrameCount++;
1049 nsecs_t now = systemTime();
1050 nsecs_t diff = now - mLastFpsTime;
1051 if (diff > ms2ns(250)) {
1052 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1053 mLastFpsTime = now;
1054 mLastFrameCount = mFrameCount;
1055 }
1056 // XXX: mFPS has the value we want
1057 }
1058
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001059status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001060{
1061 Mutex::Autolock _l(mStateLock);
1062 addLayer_l(layer);
1063 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1064 return NO_ERROR;
1065}
1066
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001067status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068{
1069 Mutex::Autolock _l(mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001070 status_t err = purgatorizeLayer_l(layer);
1071 if (err == NO_ERROR)
1072 setTransactionFlags(eTransactionNeeded);
1073 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001074}
1075
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001076status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001077{
1078 layer->forceVisibilityTransaction();
1079 setTransactionFlags(eTraversalNeeded);
1080 return NO_ERROR;
1081}
1082
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001083status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001084{
1085 ssize_t i = mCurrentState.layersSortedByZ.add(
1086 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001087 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1088 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089 mLayerMap.add(lbc->serverIndex(), lbc);
1090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091 return NO_ERROR;
1092}
1093
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001094status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001095{
1096 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1097 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001098 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001099 sp<LayerBaseClient> layer =
1100 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001101 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001102 mLayerMap.removeItem(layer->serverIndex());
1103 }
1104 return NO_ERROR;
1105 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001106 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001107}
1108
Mathias Agopian9a112062009-04-17 19:36:26 -07001109status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1110{
Mathias Agopian759fdb22009-07-02 17:33:40 -07001111 // remove the layer from the main list (through a transaction).
Mathias Agopian9a112062009-04-17 19:36:26 -07001112 ssize_t err = removeLayer_l(layerBase);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001113
Mathias Agopian3d579642009-06-04 18:46:21 -07001114 // it's possible that we don't find a layer, because it might
1115 // have been destroyed already -- this is not technically an error
1116 // from the user because there is a race between BClient::destroySurface(),
1117 // ~BClient() and ~ISurface().
Mathias Agopian9a112062009-04-17 19:36:26 -07001118 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1119}
1120
1121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001122void SurfaceFlinger::free_resources_l()
1123{
1124 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001125 mLayersRemoved = false;
1126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001127 // free resources associated with disconnected clients
Mathias Agopianf9d93272009-06-19 17:00:27 -07001128 SortedVector< wp<Client> >& scheduledBroadcasts(mScheduledBroadcasts);
1129 Vector< sp<Client> >& disconnectedClients(mDisconnectedClients);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130 const size_t count = disconnectedClients.size();
1131 for (size_t i=0 ; i<count ; i++) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001132 sp<Client> client = disconnectedClients[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133 // if this client is the scheduled broadcast list,
1134 // remove it from there (and we don't need to signal it
1135 // since it is dead).
1136 int32_t index = scheduledBroadcasts.indexOf(client);
1137 if (index >= 0) {
1138 scheduledBroadcasts.removeItemsAt(index);
1139 }
1140 mTokens.release(client->cid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001141 }
1142 disconnectedClients.clear();
1143}
1144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001145uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1146{
1147 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1148}
1149
1150uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1151{
1152 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1153 if ((old & flags)==0) { // wake the server up
1154 if (delay > 0) {
1155 signalDelayedEvent(delay);
1156 } else {
1157 signalEvent();
1158 }
1159 }
1160 return old;
1161}
1162
1163void SurfaceFlinger::openGlobalTransaction()
1164{
1165 android_atomic_inc(&mTransactionCount);
1166}
1167
1168void SurfaceFlinger::closeGlobalTransaction()
1169{
1170 if (android_atomic_dec(&mTransactionCount) == 1) {
1171 signalEvent();
1172 }
1173}
1174
1175status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1176{
1177 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1178 return BAD_VALUE;
1179
1180 Mutex::Autolock _l(mStateLock);
1181 mCurrentState.freezeDisplay = 1;
1182 setTransactionFlags(eTransactionNeeded);
1183
1184 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001185 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186 return NO_ERROR;
1187}
1188
1189status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1190{
1191 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1192 return BAD_VALUE;
1193
1194 Mutex::Autolock _l(mStateLock);
1195 mCurrentState.freezeDisplay = 0;
1196 setTransactionFlags(eTransactionNeeded);
1197
1198 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001199 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001200 return NO_ERROR;
1201}
1202
Mathias Agopianc08731e2009-03-27 18:11:38 -07001203int SurfaceFlinger::setOrientation(DisplayID dpy,
1204 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205{
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) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001212 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213 mCurrentState.orientation = orientation;
1214 setTransactionFlags(eTransactionNeeded);
1215 mTransactionCV.wait(mStateLock);
1216 } else {
1217 orientation = BAD_VALUE;
1218 }
1219 }
1220 return orientation;
1221}
1222
1223sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1224 ISurfaceFlingerClient::surface_data_t* params,
1225 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1226 uint32_t flags)
1227{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001228 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001229 sp<LayerBaseClient::Surface> surfaceHandle;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07001230
1231 if (int32_t(w|h) < 0) {
1232 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1233 int(w), int(h));
1234 return surfaceHandle;
1235 }
1236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237 Mutex::Autolock _l(mStateLock);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001238 sp<Client> client = mClientsMap.valueFor(clientId);
1239 if (UNLIKELY(client == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001240 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1241 return surfaceHandle;
1242 }
1243
1244 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001245 int32_t id = client->generateId(pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001246 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1247 LOGE("createSurface() failed, generateId = %d", id);
1248 return surfaceHandle;
1249 }
1250
1251 switch (flags & eFXSurfaceMask) {
1252 case eFXSurfaceNormal:
1253 if (UNLIKELY(flags & ePushBuffers)) {
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001254 layer = createPushBuffersSurfaceLocked(client, d, id,
1255 w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256 } else {
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001257 layer = createNormalSurfaceLocked(client, d, id,
1258 w, h, flags, format);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259 }
1260 break;
1261 case eFXSurfaceBlur:
Mathias Agopianf9d93272009-06-19 17:00:27 -07001262 layer = createBlurSurfaceLocked(client, d, id, w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263 break;
1264 case eFXSurfaceDim:
Mathias Agopianf9d93272009-06-19 17:00:27 -07001265 layer = createDimSurfaceLocked(client, d, id, w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001266 break;
1267 }
1268
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001269 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270 setTransactionFlags(eTransactionNeeded);
1271 surfaceHandle = layer->getSurface();
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001272 if (surfaceHandle != 0) {
1273 params->token = surfaceHandle->getToken();
1274 params->identity = surfaceHandle->getIdentity();
1275 params->width = w;
1276 params->height = h;
1277 params->format = format;
1278 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001279 }
1280
1281 return surfaceHandle;
1282}
1283
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001284sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001285 const sp<Client>& client, DisplayID display,
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001286 int32_t id, uint32_t w, uint32_t h, uint32_t flags,
1287 PixelFormat& format)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288{
1289 // initialize the surfaces
1290 switch (format) { // TODO: take h/w into account
1291 case PIXEL_FORMAT_TRANSPARENT:
1292 case PIXEL_FORMAT_TRANSLUCENT:
1293 format = PIXEL_FORMAT_RGBA_8888;
1294 break;
1295 case PIXEL_FORMAT_OPAQUE:
1296 format = PIXEL_FORMAT_RGB_565;
1297 break;
1298 }
1299
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001300 sp<Layer> layer = new Layer(this, display, client, id);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001301 status_t err = layer->setBuffers(w, h, format, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001302 if (LIKELY(err == NO_ERROR)) {
1303 layer->initStates(w, h, flags);
1304 addLayer_l(layer);
1305 } else {
1306 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001307 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001308 }
1309 return layer;
1310}
1311
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001312sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001313 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001314 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1315{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001316 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001317 layer->initStates(w, h, flags);
1318 addLayer_l(layer);
1319 return layer;
1320}
1321
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001322sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001323 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1325{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001326 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001327 layer->initStates(w, h, flags);
1328 addLayer_l(layer);
1329 return layer;
1330}
1331
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001332sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001333 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1335{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001336 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337 layer->initStates(w, h, flags);
1338 addLayer_l(layer);
1339 return layer;
1340}
1341
Mathias Agopian9a112062009-04-17 19:36:26 -07001342status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001343{
Mathias Agopian9a112062009-04-17 19:36:26 -07001344 /*
1345 * called by the window manager, when a surface should be marked for
1346 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001347 *
1348 * The surface is removed from the current and drawing lists, but placed
1349 * in the purgatory queue, so it's not destroyed right-away (we need
1350 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001351 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001352
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001353 Mutex::Autolock _l(mStateLock);
1354 sp<LayerBaseClient> layer = getLayerUser_l(index);
1355 status_t err = purgatorizeLayer_l(layer);
1356 if (err == NO_ERROR) {
1357 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001358 }
1359 return err;
1360}
1361
1362status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1363{
Mathias Agopian759fdb22009-07-02 17:33:40 -07001364 // called by ~ISurface() when all references are gone
Mathias Agopian9a112062009-04-17 19:36:26 -07001365
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001366 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001367 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001368 sp<LayerBaseClient> layer;
1369 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001370 MessageDestroySurface(
1371 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1372 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001373 virtual bool handler() {
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001374 sp<LayerBaseClient> l(layer);
1375 layer.clear(); // clear it outside of the lock;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001376 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001377 /*
1378 * remove the layer from the current list -- chances are that it's
1379 * not in the list anyway, because it should have been removed
1380 * already upon request of the client (eg: window manager).
1381 * However, a buggy client could have not done that.
1382 * Since we know we don't have any more clients, we don't need
1383 * to use the purgatory.
1384 */
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001385 status_t err = flinger->removeLayer_l(l);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001386 LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1387 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001388 return true;
1389 }
1390 };
Mathias Agopian3d579642009-06-04 18:46:21 -07001391
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001392 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001393 return NO_ERROR;
1394}
1395
1396status_t SurfaceFlinger::setClientState(
1397 ClientID cid,
1398 int32_t count,
1399 const layer_state_t* states)
1400{
1401 Mutex::Autolock _l(mStateLock);
1402 uint32_t flags = 0;
1403 cid <<= 16;
1404 for (int i=0 ; i<count ; i++) {
1405 const layer_state_t& s = states[i];
Mathias Agopian3d579642009-06-04 18:46:21 -07001406 sp<LayerBaseClient> layer(getLayerUser_l(s.surface | cid));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001407 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001408 const uint32_t what = s.what;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001409 if (what & ePositionChanged) {
1410 if (layer->setPosition(s.x, s.y))
1411 flags |= eTraversalNeeded;
1412 }
1413 if (what & eLayerChanged) {
1414 if (layer->setLayer(s.z)) {
1415 mCurrentState.layersSortedByZ.reorder(
1416 layer, &Layer::compareCurrentStateZ);
1417 // we need traversal (state changed)
1418 // AND transaction (list changed)
1419 flags |= eTransactionNeeded|eTraversalNeeded;
1420 }
1421 }
1422 if (what & eSizeChanged) {
1423 if (layer->setSize(s.w, s.h))
1424 flags |= eTraversalNeeded;
1425 }
1426 if (what & eAlphaChanged) {
1427 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1428 flags |= eTraversalNeeded;
1429 }
1430 if (what & eMatrixChanged) {
1431 if (layer->setMatrix(s.matrix))
1432 flags |= eTraversalNeeded;
1433 }
1434 if (what & eTransparentRegionChanged) {
1435 if (layer->setTransparentRegionHint(s.transparentRegion))
1436 flags |= eTraversalNeeded;
1437 }
1438 if (what & eVisibilityChanged) {
1439 if (layer->setFlags(s.flags, s.mask))
1440 flags |= eTraversalNeeded;
1441 }
1442 }
1443 }
1444 if (flags) {
1445 setTransactionFlags(flags);
1446 }
1447 return NO_ERROR;
1448}
1449
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001450sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001451{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001452 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1453 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001454}
1455
1456void SurfaceFlinger::screenReleased(int dpy)
1457{
1458 // this may be called by a signal handler, we can't do too much in here
1459 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1460 signalEvent();
1461}
1462
1463void SurfaceFlinger::screenAcquired(int dpy)
1464{
1465 // this may be called by a signal handler, we can't do too much in here
1466 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1467 signalEvent();
1468}
1469
1470status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1471{
1472 const size_t SIZE = 1024;
1473 char buffer[SIZE];
1474 String8 result;
Mathias Agopian375f5632009-06-15 18:24:59 -07001475 if (!mDump.checkCalling()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001476 snprintf(buffer, SIZE, "Permission Denial: "
1477 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1478 IPCThreadState::self()->getCallingPid(),
1479 IPCThreadState::self()->getCallingUid());
1480 result.append(buffer);
1481 } else {
Mathias Agopian9795c422009-08-26 16:36:26 -07001482
1483 // figure out if we're stuck somewhere
1484 const nsecs_t now = systemTime();
1485 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1486 const nsecs_t inTransaction(mDebugInTransaction);
1487 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1488 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1489
1490 // Try to get the main lock, but don't insist if we can't
1491 // (this would indicate SF is stuck, but we want to be able to
1492 // print something in dumpsys).
1493 int retry = 3;
1494 while (mStateLock.tryLock()<0 && --retry>=0) {
1495 usleep(1000000);
1496 }
1497 const bool locked(retry >= 0);
1498 if (!locked) {
1499 snprintf(buffer, SIZE,
1500 "SurfaceFlinger appears to be unresponsive, "
1501 "dumping anyways (no locks held)\n");
1502 result.append(buffer);
1503 }
1504
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001505 size_t s = mClientsMap.size();
1506 char name[64];
1507 for (size_t i=0 ; i<s ; i++) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001508 sp<Client> client = mClientsMap.valueAt(i);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509 sprintf(name, " Client (id=0x%08x)", client->cid);
1510 client->dump(name);
1511 }
1512 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1513 const size_t count = currentLayers.size();
1514 for (size_t i=0 ; i<count ; i++) {
1515 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001516 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001517 const Layer::State& s = layer->drawingState();
1518 snprintf(buffer, SIZE,
1519 "+ %s %p\n"
1520 " "
1521 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1522 "needsBlending=%1d, invalidate=%1d, "
1523 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001524 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001525 s.z, layer->tx(), layer->ty(), s.w, s.h,
1526 layer->needsBlending(), layer->contentDirty,
1527 s.alpha, s.flags,
1528 s.transform[0], s.transform[1],
1529 s.transform[2], s.transform[3]);
1530 result.append(buffer);
1531 buffer[0] = 0;
1532 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001533 sp<LayerBaseClient> lbc =
1534 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1535 if (lbc != 0) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001536 sp<Client> client(lbc->client.promote());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001537 snprintf(buffer, SIZE,
1538 " "
1539 "id=0x%08x, client=0x%08x, identity=%u\n",
Mathias Agopianf9d93272009-06-19 17:00:27 -07001540 lbc->clientIndex(), client.get() ? client->cid : 0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541 lbc->getIdentity());
1542 }
1543 result.append(buffer);
1544 buffer[0] = 0;
1545 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001546 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1547 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548 const LayerBitmap& buf0(l->getBuffer(0));
1549 const LayerBitmap& buf1(l->getBuffer(1));
1550 snprintf(buffer, SIZE,
1551 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001552 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553 " freezeLock=%p, swapState=0x%08x\n",
1554 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001555 buf0.getWidth(), buf0.getHeight(),
1556 buf0.getBuffer()->getStride(),
1557 buf1.getWidth(), buf1.getHeight(),
1558 buf1.getBuffer()->getStride(),
1559 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560 l->lcblk->swapState);
1561 }
1562 result.append(buffer);
1563 buffer[0] = 0;
1564 s.transparentRegion.dump(result, "transparentRegion");
1565 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1566 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1567 }
1568 mWormholeRegion.dump(result, "WormholeRegion");
1569 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1570 snprintf(buffer, SIZE,
1571 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1572 mFreezeDisplay?"yes":"no", mFreezeCount,
1573 mCurrentState.orientation, hw.canDraw());
1574 result.append(buffer);
Mathias Agopian9795c422009-08-26 16:36:26 -07001575 snprintf(buffer, SIZE,
1576 " last eglSwapBuffers() time: %f us\n"
1577 " last transaction time : %f us\n",
1578 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1579 result.append(buffer);
1580 if (inSwapBuffersDuration || !locked) {
1581 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
1582 inSwapBuffersDuration/1000.0);
1583 result.append(buffer);
1584 }
1585 if (inTransactionDuration || !locked) {
1586 snprintf(buffer, SIZE, " transaction time: %f us\n",
1587 inTransactionDuration/1000.0);
1588 result.append(buffer);
1589 }
Mathias Agopian759fdb22009-07-02 17:33:40 -07001590 snprintf(buffer, SIZE, " client count: %d\n", mClientsMap.size());
Mathias Agopian3d579642009-06-04 18:46:21 -07001591 result.append(buffer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001592 const BufferAllocator& alloc(BufferAllocator::get());
1593 alloc.dump(result);
Mathias Agopian9795c422009-08-26 16:36:26 -07001594
1595 if (locked) {
1596 mStateLock.unlock();
1597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001598 }
1599 write(fd, result.string(), result.size());
1600 return NO_ERROR;
1601}
1602
1603status_t SurfaceFlinger::onTransact(
1604 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1605{
1606 switch (code) {
1607 case CREATE_CONNECTION:
1608 case OPEN_GLOBAL_TRANSACTION:
1609 case CLOSE_GLOBAL_TRANSACTION:
1610 case SET_ORIENTATION:
1611 case FREEZE_DISPLAY:
1612 case UNFREEZE_DISPLAY:
1613 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001614 {
1615 // codes that require permission check
1616 IPCThreadState* ipc = IPCThreadState::self();
1617 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07001618 const int uid = ipc->getCallingUid();
Mathias Agopian375f5632009-06-15 18:24:59 -07001619 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1620 LOGE("Permission Denial: "
1621 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1622 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001623 }
1624 }
1625 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001626 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1627 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07001628 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Mathias Agopian375f5632009-06-15 18:24:59 -07001629 if (UNLIKELY(!mHardwareTest.checkCalling())) {
1630 IPCThreadState* ipc = IPCThreadState::self();
1631 const int pid = ipc->getCallingPid();
1632 const int uid = ipc->getCallingUid();
1633 LOGE("Permission Denial: "
1634 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001635 return PERMISSION_DENIED;
1636 }
1637 int n;
1638 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001639 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001640 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001641 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001642 return NO_ERROR;
1643 case 1002: // SHOW_UPDATES
1644 n = data.readInt32();
1645 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1646 return NO_ERROR;
1647 case 1003: // SHOW_BACKGROUND
1648 n = data.readInt32();
1649 mDebugBackground = n ? 1 : 0;
1650 return NO_ERROR;
1651 case 1004:{ // repaint everything
1652 Mutex::Autolock _l(mStateLock);
1653 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1654 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1655 signalEvent();
1656 }
1657 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001658 case 1007: // set mFreezeCount
1659 mFreezeCount = data.readInt32();
1660 return NO_ERROR;
1661 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001662 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001663 reply->writeInt32(0);
1664 reply->writeInt32(mDebugRegion);
1665 reply->writeInt32(mDebugBackground);
1666 return NO_ERROR;
1667 case 1013: {
1668 Mutex::Autolock _l(mStateLock);
1669 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1670 reply->writeInt32(hw.getPageFlipCount());
1671 }
1672 return NO_ERROR;
1673 }
1674 }
1675 return err;
1676}
1677
1678// ---------------------------------------------------------------------------
1679#if 0
1680#pragma mark -
1681#endif
1682
1683Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1684 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1685{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001686 const int pgsize = getpagesize();
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001687 const int cblksize = ((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1688
1689 mCblkHeap = new MemoryHeapBase(cblksize, 0,
1690 "SurfaceFlinger Client control-block");
1691
1692 ctrlblk = static_cast<per_client_cblk_t *>(mCblkHeap->getBase());
1693 if (ctrlblk) { // construct the shared structure in-place.
1694 new(ctrlblk) per_client_cblk_t;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001695 }
1696}
1697
1698Client::~Client() {
1699 if (ctrlblk) {
1700 const int pgsize = getpagesize();
1701 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1702 }
1703}
1704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001705int32_t Client::generateId(int pid)
1706{
1707 const uint32_t i = clz( ~mBitmap );
1708 if (i >= NUM_LAYERS_MAX) {
1709 return NO_MEMORY;
1710 }
1711 mPid = pid;
1712 mInUse.add(uint8_t(i));
1713 mBitmap |= 1<<(31-i);
1714 return i;
1715}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001716
1717status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001718{
1719 ssize_t idx = mInUse.indexOf(id);
1720 if (idx < 0)
1721 return NAME_NOT_FOUND;
1722 return mLayers.insertAt(layer, idx);
1723}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725void Client::free(int32_t id)
1726{
1727 ssize_t idx = mInUse.remove(uint8_t(id));
1728 if (idx >= 0) {
1729 mBitmap &= ~(1<<(31-id));
1730 mLayers.removeItemsAt(idx);
1731 }
1732}
1733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001734bool Client::isValid(int32_t i) const {
1735 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1736}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001737
1738sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1739 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001740 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001741 if (idx >= 0) {
1742 lbc = mLayers[idx].promote();
1743 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1744 }
1745 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001746}
1747
1748void Client::dump(const char* what)
1749{
1750}
1751
1752// ---------------------------------------------------------------------------
1753#if 0
1754#pragma mark -
1755#endif
1756
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001757BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemoryHeap>& cblk)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001758 : mId(cid), mFlinger(flinger), mCblk(cblk)
1759{
1760}
1761
1762BClient::~BClient() {
1763 // destroy all resources attached to this client
1764 mFlinger->destroyConnection(mId);
1765}
1766
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001767sp<IMemoryHeap> BClient::getControlBlock() const {
1768 return mCblk;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769}
1770
1771sp<ISurface> BClient::createSurface(
1772 ISurfaceFlingerClient::surface_data_t* params, int pid,
1773 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1774 uint32_t flags)
1775{
1776 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1777}
1778
1779status_t BClient::destroySurface(SurfaceID sid)
1780{
1781 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001782 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001783}
1784
1785status_t BClient::setState(int32_t count, const layer_state_t* states)
1786{
1787 return mFlinger->setClientState(mId, count, states);
1788}
1789
1790// ---------------------------------------------------------------------------
1791
1792GraphicPlane::GraphicPlane()
1793 : mHw(0)
1794{
1795}
1796
1797GraphicPlane::~GraphicPlane() {
1798 delete mHw;
1799}
1800
1801bool GraphicPlane::initialized() const {
1802 return mHw ? true : false;
1803}
1804
1805void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1806 mHw = hw;
1807}
1808
1809void GraphicPlane::setTransform(const Transform& tr) {
1810 mTransform = tr;
1811 mGlobalTransform = mOrientationTransform * mTransform;
1812}
1813
1814status_t GraphicPlane::orientationToTransfrom(
1815 int orientation, int w, int h, Transform* tr)
1816{
1817 float a, b, c, d, x, y;
1818 switch (orientation) {
1819 case ISurfaceComposer::eOrientationDefault:
1820 a=1; b=0; c=0; d=1; x=0; y=0;
1821 break;
1822 case ISurfaceComposer::eOrientation90:
1823 a=0; b=-1; c=1; d=0; x=w; y=0;
1824 break;
1825 case ISurfaceComposer::eOrientation180:
1826 a=-1; b=0; c=0; d=-1; x=w; y=h;
1827 break;
1828 case ISurfaceComposer::eOrientation270:
1829 a=0; b=1; c=-1; d=0; x=0; y=h;
1830 break;
1831 default:
1832 return BAD_VALUE;
1833 }
1834 tr->set(a, b, c, d);
1835 tr->set(x, y);
1836 return NO_ERROR;
1837}
1838
1839status_t GraphicPlane::setOrientation(int orientation)
1840{
1841 const DisplayHardware& hw(displayHardware());
1842 const float w = hw.getWidth();
1843 const float h = hw.getHeight();
1844
1845 if (orientation == ISurfaceComposer::eOrientationDefault) {
1846 // make sure the default orientation is optimal
1847 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001848 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001849 mGlobalTransform = mTransform;
1850 return NO_ERROR;
1851 }
1852
1853 // If the rotation can be handled in hardware, this is where
1854 // the magic should happen.
1855 if (UNLIKELY(orientation == 42)) {
1856 float a, b, c, d, x, y;
1857 const float r = (3.14159265f / 180.0f) * 42.0f;
1858 const float si = sinf(r);
1859 const float co = cosf(r);
1860 a=co; b=-si; c=si; d=co;
1861 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1862 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1863 mOrientationTransform.set(a, b, c, d);
1864 mOrientationTransform.set(x, y);
1865 } else {
1866 GraphicPlane::orientationToTransfrom(orientation, w, h,
1867 &mOrientationTransform);
1868 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001869 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001870 mGlobalTransform = mOrientationTransform * mTransform;
1871 return NO_ERROR;
1872}
1873
1874const DisplayHardware& GraphicPlane::displayHardware() const {
1875 return *mHw;
1876}
1877
1878const Transform& GraphicPlane::transform() const {
1879 return mGlobalTransform;
1880}
1881
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001882EGLDisplay GraphicPlane::getEGLDisplay() const {
1883 return mHw->getEGLDisplay();
1884}
1885
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886// ---------------------------------------------------------------------------
1887
1888}; // namespace android