blob: c78921a11575b508d5f63f97ad0b60d1e8a1a8bd [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++) {
Mathias Agopian0852e672009-09-04 19:50:23 -0700576 if (ditchedLayers[i] != 0) {
577 //LOGD("ditching layer %p", ditchedLayers[i].get());
578 ditchedLayers[i]->ditch();
579 }
Mathias Agopian3d579642009-06-04 18:46:21 -0700580 }
581}
582
583void SurfaceFlinger::handleTransactionLocked(
584 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
585{
586 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587 const size_t count = currentLayers.size();
588
589 /*
590 * Traversal of the children
591 * (perform the transaction for each of them if needed)
592 */
593
594 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
595 if (layersNeedTransaction) {
596 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700597 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800598 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
599 if (!trFlags) continue;
600
601 const uint32_t flags = layer->doTransaction(0);
602 if (flags & Layer::eVisibleRegion)
603 mVisibleRegionsDirty = true;
604
605 if (flags & Layer::eRestartTransaction) {
606 // restart the transaction, but back-off a little
607 layer->setTransactionFlags(eTransactionNeeded);
608 setTransactionFlags(eTraversalNeeded, ms2ns(8));
609 }
610 }
611 }
612
613 /*
614 * Perform our own transaction if needed
615 */
616
617 if (transactionFlags & eTransactionNeeded) {
618 if (mCurrentState.orientation != mDrawingState.orientation) {
619 // the orientation has changed, recompute all visible regions
620 // and invalidate everything.
621
622 const int dpy = 0;
623 const int orientation = mCurrentState.orientation;
Mathias Agopianc08731e2009-03-27 18:11:38 -0700624 const uint32_t type = mCurrentState.orientationType;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625 GraphicPlane& plane(graphicPlane(dpy));
626 plane.setOrientation(orientation);
627
628 // update the shared control block
629 const DisplayHardware& hw(plane.displayHardware());
630 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
631 dcblk->orientation = orientation;
632 if (orientation & eOrientationSwapMask) {
633 // 90 or 270 degrees orientation
634 dcblk->w = hw.getHeight();
635 dcblk->h = hw.getWidth();
636 } else {
637 dcblk->w = hw.getWidth();
638 dcblk->h = hw.getHeight();
639 }
640
641 mVisibleRegionsDirty = true;
642 mDirtyRegion.set(hw.bounds());
Mathias Agopianc08731e2009-03-27 18:11:38 -0700643 mFreezeDisplayTime = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644 }
645
646 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
647 // freezing or unfreezing the display -> trigger animation if needed
648 mFreezeDisplay = mCurrentState.freezeDisplay;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649 }
650
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700651 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
652 // layers have been added
653 mVisibleRegionsDirty = true;
654 }
655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800656 // some layers might have been removed, so
657 // we need to update the regions they're exposing.
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700658 if (mLayersRemoved) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800659 mVisibleRegionsDirty = true;
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700660 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
Mathias Agopian3d579642009-06-04 18:46:21 -0700661 const size_t count = previousLayers.size();
662 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700663 const sp<LayerBase>& layer(previousLayers[i]);
664 if (currentLayers.indexOf( layer ) < 0) {
665 // this layer is not visible anymore
Mathias Agopian3d579642009-06-04 18:46:21 -0700666 ditchedLayers.add(layer);
Mathias Agopian5d7126b2009-07-28 14:20:21 -0700667 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
Mathias Agopian0aa758d2009-04-22 15:23:34 -0700668 }
669 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800670 }
671
672 // get rid of all resources we don't need anymore
673 // (layers and clients)
674 free_resources_l();
675 }
676
677 commitTransaction();
678}
679
680sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
681{
682 return new FreezeLock(const_cast<SurfaceFlinger *>(this));
683}
684
685void SurfaceFlinger::computeVisibleRegions(
686 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
687{
688 const GraphicPlane& plane(graphicPlane(0));
689 const Transform& planeTransform(plane.transform());
690
691 Region aboveOpaqueLayers;
692 Region aboveCoveredLayers;
693 Region dirty;
694
695 bool secureFrameBuffer = false;
696
697 size_t i = currentLayers.size();
698 while (i--) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700699 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700 layer->validateVisibility(planeTransform);
701
702 // start with the whole surface at its current location
Mathias Agopian97011222009-07-28 10:57:27 -0700703 const Layer::State& s(layer->drawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800704
705 // handle hidden surfaces by setting the visible region to empty
706 Region opaqueRegion;
707 Region visibleRegion;
708 Region coveredRegion;
Mathias Agopian97011222009-07-28 10:57:27 -0700709 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800710 const bool translucent = layer->needsBlending();
Mathias Agopian97011222009-07-28 10:57:27 -0700711 const Rect bounds(layer->visibleBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712 visibleRegion.set(bounds);
713 coveredRegion = visibleRegion;
714
715 // Remove the transparent area from the visible region
716 if (translucent) {
717 visibleRegion.subtractSelf(layer->transparentRegionScreen);
718 }
719
720 // compute the opaque region
721 if (s.alpha==255 && !translucent && layer->getOrientation()>=0) {
722 // the opaque region is the visible region
723 opaqueRegion = visibleRegion;
724 }
725 }
726
727 // subtract the opaque region covered by the layers above us
728 visibleRegion.subtractSelf(aboveOpaqueLayers);
729 coveredRegion.andSelf(aboveCoveredLayers);
730
731 // compute this layer's dirty region
732 if (layer->contentDirty) {
733 // we need to invalidate the whole region
734 dirty = visibleRegion;
735 // as well, as the old visible region
736 dirty.orSelf(layer->visibleRegionScreen);
737 layer->contentDirty = false;
738 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -0700739 /* compute the exposed region:
740 * exposed = what's VISIBLE and NOT COVERED now
741 * but was COVERED before
742 */
743 dirty = (visibleRegion - coveredRegion) & layer->coveredRegionScreen;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744 }
745 dirty.subtractSelf(aboveOpaqueLayers);
746
747 // accumulate to the screen dirty region
748 dirtyRegion.orSelf(dirty);
749
Mathias Agopian62b74442009-04-14 23:02:51 -0700750 // Update aboveOpaqueLayers/aboveCoveredLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751 aboveOpaqueLayers.orSelf(opaqueRegion);
Mathias Agopiana8d44f72009-06-28 02:54:16 -0700752 aboveCoveredLayers.orSelf(visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800753
754 // Store the visible region is screen space
755 layer->setVisibleRegion(visibleRegion);
756 layer->setCoveredRegion(coveredRegion);
757
Mathias Agopian97011222009-07-28 10:57:27 -0700758 // If a secure layer is partially visible, lock-down the screen!
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759 if (layer->isSecure() && !visibleRegion.isEmpty()) {
760 secureFrameBuffer = true;
761 }
762 }
763
Mathias Agopian97011222009-07-28 10:57:27 -0700764 // invalidate the areas where a layer was removed
765 dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
766 mDirtyRegionRemovedLayer.clear();
767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800768 mSecureFrameBuffer = secureFrameBuffer;
769 opaqueRegion = aboveOpaqueLayers;
770}
771
772
773void SurfaceFlinger::commitTransaction()
774{
775 mDrawingState = mCurrentState;
776 mTransactionCV.signal();
777}
778
779void SurfaceFlinger::handlePageFlip()
780{
781 bool visibleRegions = mVisibleRegionsDirty;
782 LayerVector& currentLayers = const_cast<LayerVector&>(mDrawingState.layersSortedByZ);
783 visibleRegions |= lockPageFlip(currentLayers);
784
785 const DisplayHardware& hw = graphicPlane(0).displayHardware();
786 const Region screenRegion(hw.bounds());
787 if (visibleRegions) {
788 Region opaqueRegion;
789 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
790 mWormholeRegion = screenRegion.subtract(opaqueRegion);
791 mVisibleRegionsDirty = false;
792 }
793
794 unlockPageFlip(currentLayers);
795 mDirtyRegion.andSelf(screenRegion);
796}
797
798bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
799{
800 bool recomputeVisibleRegions = false;
801 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700802 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800803 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700804 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805 layer->lockPageFlip(recomputeVisibleRegions);
806 }
807 return recomputeVisibleRegions;
808}
809
810void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
811{
812 const GraphicPlane& plane(graphicPlane(0));
813 const Transform& planeTransform(plane.transform());
814 size_t count = currentLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700815 sp<LayerBase> const* layers = currentLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800816 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700817 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800818 layer->unlockPageFlip(planeTransform, mDirtyRegion);
819 }
820}
821
Mathias Agopianb8a55602009-06-26 19:06:36 -0700822
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800823void SurfaceFlinger::handleRepaint()
824{
Mathias Agopianb8a55602009-06-26 19:06:36 -0700825 // compute the invalid region
826 mInvalidRegion.orSelf(mDirtyRegion);
827 if (mInvalidRegion.isEmpty()) {
828 // nothing to do
829 return;
830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831
832 if (UNLIKELY(mDebugRegion)) {
833 debugFlashRegions();
834 }
835
Mathias Agopianb8a55602009-06-26 19:06:36 -0700836 // set the frame buffer
837 const DisplayHardware& hw(graphicPlane(0).displayHardware());
838 glMatrixMode(GL_MODELVIEW);
839 glLoadIdentity();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840
841 uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700842 if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
843 (flags & DisplayHardware::BUFFER_PRESERVED))
844 {
Mathias Agopian29d06ac2009-06-29 18:49:56 -0700845 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
846 // takes a rectangle, we must make sure to update that whole
847 // rectangle in that case
848 if (flags & DisplayHardware::SWAP_RECTANGLE) {
849 // FIXME: we really should be able to pass a region to
850 // SWAP_RECTANGLE so that we don't have to redraw all this.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800851 mDirtyRegion.set(mInvalidRegion.bounds());
852 } else {
Mathias Agopian29d06ac2009-06-29 18:49:56 -0700853 // in the BUFFER_PRESERVED case, obviously, we can update only
854 // what's needed and nothing more.
855 // NOTE: this is NOT a common case, as preserving the backbuffer
856 // is costly and usually involves copying the whole update back.
857 }
858 } else {
859 if (flags & DisplayHardware::UPDATE_ON_DEMAND) {
860 // We need to redraw the rectangle that will be updated
861 // (pushed to the framebuffer).
862 // This is needed because UPDATE_ON_DEMAND only takes one
863 // rectangle instead of a region (see DisplayHardware::flip())
864 mDirtyRegion.set(mInvalidRegion.bounds());
865 } else {
866 // we need to redraw everything (the whole screen)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800867 mDirtyRegion.set(hw.bounds());
868 mInvalidRegion = mDirtyRegion;
869 }
870 }
871
872 // compose all surfaces
873 composeSurfaces(mDirtyRegion);
874
875 // clear the dirty regions
876 mDirtyRegion.clear();
877}
878
879void SurfaceFlinger::composeSurfaces(const Region& dirty)
880{
881 if (UNLIKELY(!mWormholeRegion.isEmpty())) {
882 // should never happen unless the window manager has a bug
883 // draw something...
884 drawWormhole();
885 }
886 const SurfaceFlinger& flinger(*this);
887 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
888 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700889 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800890 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700891 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892 const Region& visibleRegion(layer->visibleRegionScreen);
893 if (!visibleRegion.isEmpty()) {
894 const Region clip(dirty.intersect(visibleRegion));
895 if (!clip.isEmpty()) {
896 layer->draw(clip);
897 }
898 }
899 }
900}
901
902void SurfaceFlinger::unlockClients()
903{
904 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
905 const size_t count = drawingLayers.size();
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700906 sp<LayerBase> const* const layers = drawingLayers.array();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700908 const sp<LayerBase>& layer = layers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800909 layer->finishPageFlip();
910 }
911}
912
Mathias Agopianf9d93272009-06-19 17:00:27 -0700913void SurfaceFlinger::scheduleBroadcast(const sp<Client>& client)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800914{
915 if (mLastScheduledBroadcast != client) {
916 mLastScheduledBroadcast = client;
917 mScheduledBroadcasts.add(client);
918 }
919}
920
921void SurfaceFlinger::executeScheduledBroadcasts()
922{
Mathias Agopianf9d93272009-06-19 17:00:27 -0700923 SortedVector< wp<Client> >& list(mScheduledBroadcasts);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800924 size_t count = list.size();
925 while (count--) {
Mathias Agopianf9d93272009-06-19 17:00:27 -0700926 sp<Client> client = list[count].promote();
927 if (client != 0) {
928 per_client_cblk_t* const cblk = client->ctrlblk;
929 if (cblk->lock.tryLock() == NO_ERROR) {
930 cblk->cv.broadcast();
931 list.removeAt(count);
932 cblk->lock.unlock();
933 } else {
934 // schedule another round
935 LOGW("executeScheduledBroadcasts() skipped, "
936 "contention on the client. We'll try again later...");
937 signalDelayedEvent(ms2ns(4));
938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800939 }
940 }
941 mLastScheduledBroadcast = 0;
942}
943
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800944void SurfaceFlinger::debugFlashRegions()
945{
Mathias Agopian0926f502009-05-04 14:17:04 -0700946 const DisplayHardware& hw(graphicPlane(0).displayHardware());
947 const uint32_t flags = hw.getFlags();
Mathias Agopiandf3ca302009-05-04 19:29:25 -0700948
949 if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
950 (flags & DisplayHardware::BUFFER_PRESERVED))) {
Mathias Agopian0926f502009-05-04 14:17:04 -0700951 const Region repaint((flags & DisplayHardware::UPDATE_ON_DEMAND) ?
952 mDirtyRegion.bounds() : hw.bounds());
953 composeSurfaces(repaint);
954 }
955
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800956 glDisable(GL_TEXTURE_2D);
957 glDisable(GL_BLEND);
958 glDisable(GL_DITHER);
959 glDisable(GL_SCISSOR_TEST);
960
Mathias Agopian0926f502009-05-04 14:17:04 -0700961 static int toggle = 0;
962 toggle = 1 - toggle;
963 if (toggle) {
964 glColor4x(0x10000, 0, 0x10000, 0x10000);
965 } else {
966 glColor4x(0x10000, 0x10000, 0, 0x10000);
967 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800968
Mathias Agopian20f68782009-05-11 00:03:41 -0700969 Region::const_iterator it = mDirtyRegion.begin();
970 Region::const_iterator const end = mDirtyRegion.end();
971 while (it != end) {
972 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800973 GLfloat vertices[][2] = {
974 { r.left, r.top },
975 { r.left, r.bottom },
976 { r.right, r.bottom },
977 { r.right, r.top }
978 };
979 glVertexPointer(2, GL_FLOAT, 0, vertices);
980 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
981 }
Mathias Agopian0926f502009-05-04 14:17:04 -0700982
Mathias Agopianb8a55602009-06-26 19:06:36 -0700983 if (mInvalidRegion.isEmpty()) {
984 mDirtyRegion.dump("mDirtyRegion");
985 mInvalidRegion.dump("mInvalidRegion");
986 }
987 hw.flip(mInvalidRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800988
989 if (mDebugRegion > 1)
990 usleep(mDebugRegion * 1000);
991
992 glEnable(GL_SCISSOR_TEST);
993 //mDirtyRegion.dump("mDirtyRegion");
994}
995
996void SurfaceFlinger::drawWormhole() const
997{
998 const Region region(mWormholeRegion.intersect(mDirtyRegion));
999 if (region.isEmpty())
1000 return;
1001
1002 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1003 const int32_t width = hw.getWidth();
1004 const int32_t height = hw.getHeight();
1005
1006 glDisable(GL_BLEND);
1007 glDisable(GL_DITHER);
1008
1009 if (LIKELY(!mDebugBackground)) {
1010 glClearColorx(0,0,0,0);
Mathias Agopian20f68782009-05-11 00:03:41 -07001011 Region::const_iterator it = region.begin();
1012 Region::const_iterator const end = region.end();
1013 while (it != end) {
1014 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015 const GLint sy = height - (r.top + r.height());
1016 glScissor(r.left, sy, r.width(), r.height());
1017 glClear(GL_COLOR_BUFFER_BIT);
1018 }
1019 } else {
1020 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
1021 { width, height }, { 0, height } };
1022 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };
1023 glVertexPointer(2, GL_SHORT, 0, vertices);
1024 glTexCoordPointer(2, GL_SHORT, 0, tcoords);
1025 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1026 glEnable(GL_TEXTURE_2D);
1027 glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1028 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1029 glMatrixMode(GL_TEXTURE);
1030 glLoadIdentity();
1031 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
Mathias Agopian20f68782009-05-11 00:03:41 -07001032 Region::const_iterator it = region.begin();
1033 Region::const_iterator const end = region.end();
1034 while (it != end) {
1035 const Rect& r = *it++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036 const GLint sy = height - (r.top + r.height());
1037 glScissor(r.left, sy, r.width(), r.height());
1038 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1039 }
1040 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1041 }
1042}
1043
1044void SurfaceFlinger::debugShowFPS() const
1045{
1046 static int mFrameCount;
1047 static int mLastFrameCount = 0;
1048 static nsecs_t mLastFpsTime = 0;
1049 static float mFps = 0;
1050 mFrameCount++;
1051 nsecs_t now = systemTime();
1052 nsecs_t diff = now - mLastFpsTime;
1053 if (diff > ms2ns(250)) {
1054 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1055 mLastFpsTime = now;
1056 mLastFrameCount = mFrameCount;
1057 }
1058 // XXX: mFPS has the value we want
1059 }
1060
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001061status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062{
1063 Mutex::Autolock _l(mStateLock);
1064 addLayer_l(layer);
1065 setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1066 return NO_ERROR;
1067}
1068
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001069status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070{
1071 Mutex::Autolock _l(mStateLock);
Mathias Agopian3d579642009-06-04 18:46:21 -07001072 status_t err = purgatorizeLayer_l(layer);
1073 if (err == NO_ERROR)
1074 setTransactionFlags(eTransactionNeeded);
1075 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076}
1077
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001078status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079{
1080 layer->forceVisibilityTransaction();
1081 setTransactionFlags(eTraversalNeeded);
1082 return NO_ERROR;
1083}
1084
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001085status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001086{
Mathias Agopian0852e672009-09-04 19:50:23 -07001087 if (layer == 0)
1088 return BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089 ssize_t i = mCurrentState.layersSortedByZ.add(
1090 layer, &LayerBase::compareCurrentStateZ);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001091 sp<LayerBaseClient> lbc = LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1092 if (lbc != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001093 mLayerMap.add(lbc->serverIndex(), lbc);
1094 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001095 return NO_ERROR;
1096}
1097
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001098status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001099{
1100 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1101 if (index >= 0) {
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001102 mLayersRemoved = true;
Mathias Agopian9a112062009-04-17 19:36:26 -07001103 sp<LayerBaseClient> layer =
1104 LayerBase::dynamicCast< LayerBaseClient* >(layerBase.get());
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001105 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001106 mLayerMap.removeItem(layer->serverIndex());
1107 }
1108 return NO_ERROR;
1109 }
Mathias Agopian3d579642009-06-04 18:46:21 -07001110 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001111}
1112
Mathias Agopian9a112062009-04-17 19:36:26 -07001113status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1114{
Mathias Agopian759fdb22009-07-02 17:33:40 -07001115 // remove the layer from the main list (through a transaction).
Mathias Agopian9a112062009-04-17 19:36:26 -07001116 ssize_t err = removeLayer_l(layerBase);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001117
Mathias Agopian3d579642009-06-04 18:46:21 -07001118 // it's possible that we don't find a layer, because it might
1119 // have been destroyed already -- this is not technically an error
1120 // from the user because there is a race between BClient::destroySurface(),
1121 // ~BClient() and ~ISurface().
Mathias Agopian9a112062009-04-17 19:36:26 -07001122 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1123}
1124
1125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001126void SurfaceFlinger::free_resources_l()
1127{
1128 // Destroy layers that were removed
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001129 mLayersRemoved = false;
1130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001131 // free resources associated with disconnected clients
Mathias Agopianf9d93272009-06-19 17:00:27 -07001132 SortedVector< wp<Client> >& scheduledBroadcasts(mScheduledBroadcasts);
1133 Vector< sp<Client> >& disconnectedClients(mDisconnectedClients);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001134 const size_t count = disconnectedClients.size();
1135 for (size_t i=0 ; i<count ; i++) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001136 sp<Client> client = disconnectedClients[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001137 // if this client is the scheduled broadcast list,
1138 // remove it from there (and we don't need to signal it
1139 // since it is dead).
1140 int32_t index = scheduledBroadcasts.indexOf(client);
1141 if (index >= 0) {
1142 scheduledBroadcasts.removeItemsAt(index);
1143 }
1144 mTokens.release(client->cid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001145 }
1146 disconnectedClients.clear();
1147}
1148
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001149uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1150{
1151 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1152}
1153
1154uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags, nsecs_t delay)
1155{
1156 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1157 if ((old & flags)==0) { // wake the server up
1158 if (delay > 0) {
1159 signalDelayedEvent(delay);
1160 } else {
1161 signalEvent();
1162 }
1163 }
1164 return old;
1165}
1166
1167void SurfaceFlinger::openGlobalTransaction()
1168{
1169 android_atomic_inc(&mTransactionCount);
1170}
1171
1172void SurfaceFlinger::closeGlobalTransaction()
1173{
1174 if (android_atomic_dec(&mTransactionCount) == 1) {
1175 signalEvent();
1176 }
1177}
1178
1179status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1180{
1181 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1182 return BAD_VALUE;
1183
1184 Mutex::Autolock _l(mStateLock);
1185 mCurrentState.freezeDisplay = 1;
1186 setTransactionFlags(eTransactionNeeded);
1187
1188 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001189 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001190 return NO_ERROR;
1191}
1192
1193status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1194{
1195 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1196 return BAD_VALUE;
1197
1198 Mutex::Autolock _l(mStateLock);
1199 mCurrentState.freezeDisplay = 0;
1200 setTransactionFlags(eTransactionNeeded);
1201
1202 // flags is intended to communicate some sort of animation behavior
Mathias Agopian62b74442009-04-14 23:02:51 -07001203 // (for instance fading)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204 return NO_ERROR;
1205}
1206
Mathias Agopianc08731e2009-03-27 18:11:38 -07001207int SurfaceFlinger::setOrientation(DisplayID dpy,
1208 int orientation, uint32_t flags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001209{
1210 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1211 return BAD_VALUE;
1212
1213 Mutex::Autolock _l(mStateLock);
1214 if (mCurrentState.orientation != orientation) {
1215 if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
Mathias Agopianc08731e2009-03-27 18:11:38 -07001216 mCurrentState.orientationType = flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217 mCurrentState.orientation = orientation;
1218 setTransactionFlags(eTransactionNeeded);
1219 mTransactionCV.wait(mStateLock);
1220 } else {
1221 orientation = BAD_VALUE;
1222 }
1223 }
1224 return orientation;
1225}
1226
1227sp<ISurface> SurfaceFlinger::createSurface(ClientID clientId, int pid,
1228 ISurfaceFlingerClient::surface_data_t* params,
1229 DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1230 uint32_t flags)
1231{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001232 sp<LayerBaseClient> layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001233 sp<LayerBaseClient::Surface> surfaceHandle;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07001234
1235 if (int32_t(w|h) < 0) {
1236 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1237 int(w), int(h));
1238 return surfaceHandle;
1239 }
1240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241 Mutex::Autolock _l(mStateLock);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001242 sp<Client> client = mClientsMap.valueFor(clientId);
1243 if (UNLIKELY(client == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244 LOGE("createSurface() failed, client not found (id=%d)", clientId);
1245 return surfaceHandle;
1246 }
1247
1248 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001249 int32_t id = client->generateId(pid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001250 if (uint32_t(id) >= NUM_LAYERS_MAX) {
1251 LOGE("createSurface() failed, generateId = %d", id);
1252 return surfaceHandle;
1253 }
1254
1255 switch (flags & eFXSurfaceMask) {
1256 case eFXSurfaceNormal:
1257 if (UNLIKELY(flags & ePushBuffers)) {
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001258 layer = createPushBuffersSurfaceLocked(client, d, id,
1259 w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001260 } else {
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001261 layer = createNormalSurfaceLocked(client, d, id,
1262 w, h, flags, format);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263 }
1264 break;
1265 case eFXSurfaceBlur:
Mathias Agopianf9d93272009-06-19 17:00:27 -07001266 layer = createBlurSurfaceLocked(client, d, id, w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001267 break;
1268 case eFXSurfaceDim:
Mathias Agopianf9d93272009-06-19 17:00:27 -07001269 layer = createDimSurfaceLocked(client, d, id, w, h, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270 break;
1271 }
1272
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001273 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001274 setTransactionFlags(eTransactionNeeded);
1275 surfaceHandle = layer->getSurface();
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001276 if (surfaceHandle != 0) {
1277 params->token = surfaceHandle->getToken();
1278 params->identity = surfaceHandle->getIdentity();
1279 params->width = w;
1280 params->height = h;
1281 params->format = format;
1282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001283 }
1284
1285 return surfaceHandle;
1286}
1287
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001288sp<LayerBaseClient> SurfaceFlinger::createNormalSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001289 const sp<Client>& client, DisplayID display,
Mathias Agopian1c97d2e2009-08-19 17:46:26 -07001290 int32_t id, uint32_t w, uint32_t h, uint32_t flags,
1291 PixelFormat& format)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292{
1293 // initialize the surfaces
1294 switch (format) { // TODO: take h/w into account
1295 case PIXEL_FORMAT_TRANSPARENT:
1296 case PIXEL_FORMAT_TRANSLUCENT:
1297 format = PIXEL_FORMAT_RGBA_8888;
1298 break;
1299 case PIXEL_FORMAT_OPAQUE:
1300 format = PIXEL_FORMAT_RGB_565;
1301 break;
1302 }
1303
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001304 sp<Layer> layer = new Layer(this, display, client, id);
Mathias Agopianf9d93272009-06-19 17:00:27 -07001305 status_t err = layer->setBuffers(w, h, format, flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001306 if (LIKELY(err == NO_ERROR)) {
1307 layer->initStates(w, h, flags);
1308 addLayer_l(layer);
1309 } else {
1310 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001311 layer.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001312 }
1313 return layer;
1314}
1315
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001316sp<LayerBaseClient> SurfaceFlinger::createBlurSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001317 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001318 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1319{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001320 sp<LayerBlur> layer = new LayerBlur(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001321 layer->initStates(w, h, flags);
1322 addLayer_l(layer);
1323 return layer;
1324}
1325
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001326sp<LayerBaseClient> SurfaceFlinger::createDimSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001327 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1329{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001330 sp<LayerDim> layer = new LayerDim(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001331 layer->initStates(w, h, flags);
1332 addLayer_l(layer);
1333 return layer;
1334}
1335
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001336sp<LayerBaseClient> SurfaceFlinger::createPushBuffersSurfaceLocked(
Mathias Agopianf9d93272009-06-19 17:00:27 -07001337 const sp<Client>& client, DisplayID display,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001338 int32_t id, uint32_t w, uint32_t h, uint32_t flags)
1339{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001340 sp<LayerBuffer> layer = new LayerBuffer(this, display, client, id);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341 layer->initStates(w, h, flags);
1342 addLayer_l(layer);
1343 return layer;
1344}
1345
Mathias Agopian9a112062009-04-17 19:36:26 -07001346status_t SurfaceFlinger::removeSurface(SurfaceID index)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001347{
Mathias Agopian9a112062009-04-17 19:36:26 -07001348 /*
1349 * called by the window manager, when a surface should be marked for
1350 * destruction.
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001351 *
1352 * The surface is removed from the current and drawing lists, but placed
1353 * in the purgatory queue, so it's not destroyed right-away (we need
1354 * to wait for all client's references to go away first).
Mathias Agopian9a112062009-04-17 19:36:26 -07001355 */
Mathias Agopian9a112062009-04-17 19:36:26 -07001356
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001357 Mutex::Autolock _l(mStateLock);
1358 sp<LayerBaseClient> layer = getLayerUser_l(index);
1359 status_t err = purgatorizeLayer_l(layer);
1360 if (err == NO_ERROR) {
1361 setTransactionFlags(eTransactionNeeded);
Mathias Agopian9a112062009-04-17 19:36:26 -07001362 }
1363 return err;
1364}
1365
1366status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1367{
Mathias Agopian759fdb22009-07-02 17:33:40 -07001368 // called by ~ISurface() when all references are gone
Mathias Agopian9a112062009-04-17 19:36:26 -07001369
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001370 class MessageDestroySurface : public MessageBase {
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001371 SurfaceFlinger* flinger;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001372 sp<LayerBaseClient> layer;
1373 public:
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001374 MessageDestroySurface(
1375 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1376 : flinger(flinger), layer(layer) { }
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001377 virtual bool handler() {
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001378 sp<LayerBaseClient> l(layer);
1379 layer.clear(); // clear it outside of the lock;
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001380 Mutex::Autolock _l(flinger->mStateLock);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001381 /*
1382 * remove the layer from the current list -- chances are that it's
1383 * not in the list anyway, because it should have been removed
1384 * already upon request of the client (eg: window manager).
1385 * However, a buggy client could have not done that.
1386 * Since we know we don't have any more clients, we don't need
1387 * to use the purgatory.
1388 */
Mathias Agopiancd8c5e22009-06-19 16:24:02 -07001389 status_t err = flinger->removeLayer_l(l);
Mathias Agopian759fdb22009-07-02 17:33:40 -07001390 LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1391 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001392 return true;
1393 }
1394 };
Mathias Agopian3d579642009-06-04 18:46:21 -07001395
Mathias Agopianf1d8e872009-04-20 19:39:12 -07001396 mEventQueue.postMessage( new MessageDestroySurface(this, layer) );
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397 return NO_ERROR;
1398}
1399
1400status_t SurfaceFlinger::setClientState(
1401 ClientID cid,
1402 int32_t count,
1403 const layer_state_t* states)
1404{
1405 Mutex::Autolock _l(mStateLock);
1406 uint32_t flags = 0;
1407 cid <<= 16;
1408 for (int i=0 ; i<count ; i++) {
1409 const layer_state_t& s = states[i];
Mathias Agopian3d579642009-06-04 18:46:21 -07001410 sp<LayerBaseClient> layer(getLayerUser_l(s.surface | cid));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001411 if (layer != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001412 const uint32_t what = s.what;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001413 if (what & ePositionChanged) {
1414 if (layer->setPosition(s.x, s.y))
1415 flags |= eTraversalNeeded;
1416 }
1417 if (what & eLayerChanged) {
1418 if (layer->setLayer(s.z)) {
1419 mCurrentState.layersSortedByZ.reorder(
1420 layer, &Layer::compareCurrentStateZ);
1421 // we need traversal (state changed)
1422 // AND transaction (list changed)
1423 flags |= eTransactionNeeded|eTraversalNeeded;
1424 }
1425 }
1426 if (what & eSizeChanged) {
1427 if (layer->setSize(s.w, s.h))
1428 flags |= eTraversalNeeded;
1429 }
1430 if (what & eAlphaChanged) {
1431 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1432 flags |= eTraversalNeeded;
1433 }
1434 if (what & eMatrixChanged) {
1435 if (layer->setMatrix(s.matrix))
1436 flags |= eTraversalNeeded;
1437 }
1438 if (what & eTransparentRegionChanged) {
1439 if (layer->setTransparentRegionHint(s.transparentRegion))
1440 flags |= eTraversalNeeded;
1441 }
1442 if (what & eVisibilityChanged) {
1443 if (layer->setFlags(s.flags, s.mask))
1444 flags |= eTraversalNeeded;
1445 }
1446 }
1447 }
1448 if (flags) {
1449 setTransactionFlags(flags);
1450 }
1451 return NO_ERROR;
1452}
1453
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001454sp<LayerBaseClient> SurfaceFlinger::getLayerUser_l(SurfaceID s) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001455{
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001456 sp<LayerBaseClient> layer = mLayerMap.valueFor(s);
1457 return layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458}
1459
1460void SurfaceFlinger::screenReleased(int dpy)
1461{
1462 // this may be called by a signal handler, we can't do too much in here
1463 android_atomic_or(eConsoleReleased, &mConsoleSignals);
1464 signalEvent();
1465}
1466
1467void SurfaceFlinger::screenAcquired(int dpy)
1468{
1469 // this may be called by a signal handler, we can't do too much in here
1470 android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1471 signalEvent();
1472}
1473
1474status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1475{
1476 const size_t SIZE = 1024;
1477 char buffer[SIZE];
1478 String8 result;
Mathias Agopian375f5632009-06-15 18:24:59 -07001479 if (!mDump.checkCalling()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480 snprintf(buffer, SIZE, "Permission Denial: "
1481 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1482 IPCThreadState::self()->getCallingPid(),
1483 IPCThreadState::self()->getCallingUid());
1484 result.append(buffer);
1485 } else {
Mathias Agopian9795c422009-08-26 16:36:26 -07001486
1487 // figure out if we're stuck somewhere
1488 const nsecs_t now = systemTime();
1489 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1490 const nsecs_t inTransaction(mDebugInTransaction);
1491 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1492 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1493
1494 // Try to get the main lock, but don't insist if we can't
1495 // (this would indicate SF is stuck, but we want to be able to
1496 // print something in dumpsys).
1497 int retry = 3;
1498 while (mStateLock.tryLock()<0 && --retry>=0) {
1499 usleep(1000000);
1500 }
1501 const bool locked(retry >= 0);
1502 if (!locked) {
1503 snprintf(buffer, SIZE,
1504 "SurfaceFlinger appears to be unresponsive, "
1505 "dumping anyways (no locks held)\n");
1506 result.append(buffer);
1507 }
1508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001509 size_t s = mClientsMap.size();
1510 char name[64];
1511 for (size_t i=0 ; i<s ; i++) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001512 sp<Client> client = mClientsMap.valueAt(i);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001513 sprintf(name, " Client (id=0x%08x)", client->cid);
1514 client->dump(name);
1515 }
1516 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1517 const size_t count = currentLayers.size();
1518 for (size_t i=0 ; i<count ; i++) {
1519 /*** LayerBase ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001520 const sp<LayerBase>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521 const Layer::State& s = layer->drawingState();
1522 snprintf(buffer, SIZE,
1523 "+ %s %p\n"
1524 " "
1525 "z=%9d, pos=(%4d,%4d), size=(%4d,%4d), "
1526 "needsBlending=%1d, invalidate=%1d, "
1527 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n",
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001528 layer->getTypeID(), layer.get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001529 s.z, layer->tx(), layer->ty(), s.w, s.h,
1530 layer->needsBlending(), layer->contentDirty,
1531 s.alpha, s.flags,
1532 s.transform[0], s.transform[1],
1533 s.transform[2], s.transform[3]);
1534 result.append(buffer);
1535 buffer[0] = 0;
1536 /*** LayerBaseClient ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001537 sp<LayerBaseClient> lbc =
1538 LayerBase::dynamicCast< LayerBaseClient* >(layer.get());
1539 if (lbc != 0) {
Mathias Agopianf9d93272009-06-19 17:00:27 -07001540 sp<Client> client(lbc->client.promote());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541 snprintf(buffer, SIZE,
1542 " "
1543 "id=0x%08x, client=0x%08x, identity=%u\n",
Mathias Agopianf9d93272009-06-19 17:00:27 -07001544 lbc->clientIndex(), client.get() ? client->cid : 0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001545 lbc->getIdentity());
1546 }
1547 result.append(buffer);
1548 buffer[0] = 0;
1549 /*** Layer ***/
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001550 sp<Layer> l = LayerBase::dynamicCast< Layer* >(layer.get());
1551 if (l != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001552 const LayerBitmap& buf0(l->getBuffer(0));
1553 const LayerBitmap& buf1(l->getBuffer(1));
1554 snprintf(buffer, SIZE,
1555 " "
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001556 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u],"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557 " freezeLock=%p, swapState=0x%08x\n",
1558 l->pixelFormat(),
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001559 buf0.getWidth(), buf0.getHeight(),
1560 buf0.getBuffer()->getStride(),
1561 buf1.getWidth(), buf1.getHeight(),
1562 buf1.getBuffer()->getStride(),
1563 l->getFreezeLock().get(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001564 l->lcblk->swapState);
1565 }
1566 result.append(buffer);
1567 buffer[0] = 0;
1568 s.transparentRegion.dump(result, "transparentRegion");
1569 layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1570 layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1571 }
1572 mWormholeRegion.dump(result, "WormholeRegion");
1573 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1574 snprintf(buffer, SIZE,
1575 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1576 mFreezeDisplay?"yes":"no", mFreezeCount,
1577 mCurrentState.orientation, hw.canDraw());
1578 result.append(buffer);
Mathias Agopian9795c422009-08-26 16:36:26 -07001579 snprintf(buffer, SIZE,
1580 " last eglSwapBuffers() time: %f us\n"
1581 " last transaction time : %f us\n",
1582 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1583 result.append(buffer);
1584 if (inSwapBuffersDuration || !locked) {
1585 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
1586 inSwapBuffersDuration/1000.0);
1587 result.append(buffer);
1588 }
1589 if (inTransactionDuration || !locked) {
1590 snprintf(buffer, SIZE, " transaction time: %f us\n",
1591 inTransactionDuration/1000.0);
1592 result.append(buffer);
1593 }
Mathias Agopian759fdb22009-07-02 17:33:40 -07001594 snprintf(buffer, SIZE, " client count: %d\n", mClientsMap.size());
Mathias Agopian3d579642009-06-04 18:46:21 -07001595 result.append(buffer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001596 const BufferAllocator& alloc(BufferAllocator::get());
1597 alloc.dump(result);
Mathias Agopian9795c422009-08-26 16:36:26 -07001598
1599 if (locked) {
1600 mStateLock.unlock();
1601 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001602 }
1603 write(fd, result.string(), result.size());
1604 return NO_ERROR;
1605}
1606
1607status_t SurfaceFlinger::onTransact(
1608 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1609{
1610 switch (code) {
1611 case CREATE_CONNECTION:
1612 case OPEN_GLOBAL_TRANSACTION:
1613 case CLOSE_GLOBAL_TRANSACTION:
1614 case SET_ORIENTATION:
1615 case FREEZE_DISPLAY:
1616 case UNFREEZE_DISPLAY:
1617 case BOOT_FINISHED:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001618 {
1619 // codes that require permission check
1620 IPCThreadState* ipc = IPCThreadState::self();
1621 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07001622 const int uid = ipc->getCallingUid();
Mathias Agopian375f5632009-06-15 18:24:59 -07001623 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1624 LOGE("Permission Denial: "
1625 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1626 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001627 }
1628 }
1629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001630 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1631 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07001632 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Mathias Agopian375f5632009-06-15 18:24:59 -07001633 if (UNLIKELY(!mHardwareTest.checkCalling())) {
1634 IPCThreadState* ipc = IPCThreadState::self();
1635 const int pid = ipc->getCallingPid();
1636 const int uid = ipc->getCallingUid();
1637 LOGE("Permission Denial: "
1638 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001639 return PERMISSION_DENIED;
1640 }
1641 int n;
1642 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07001643 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001644 return NO_ERROR;
Mathias Agopiancbc93ca2009-04-21 18:28:33 -07001645 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001646 return NO_ERROR;
1647 case 1002: // SHOW_UPDATES
1648 n = data.readInt32();
1649 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1650 return NO_ERROR;
1651 case 1003: // SHOW_BACKGROUND
1652 n = data.readInt32();
1653 mDebugBackground = n ? 1 : 0;
1654 return NO_ERROR;
1655 case 1004:{ // repaint everything
1656 Mutex::Autolock _l(mStateLock);
1657 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1658 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1659 signalEvent();
1660 }
1661 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001662 case 1007: // set mFreezeCount
1663 mFreezeCount = data.readInt32();
1664 return NO_ERROR;
1665 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07001666 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001667 reply->writeInt32(0);
1668 reply->writeInt32(mDebugRegion);
1669 reply->writeInt32(mDebugBackground);
1670 return NO_ERROR;
1671 case 1013: {
1672 Mutex::Autolock _l(mStateLock);
1673 const DisplayHardware& hw(graphicPlane(0).displayHardware());
1674 reply->writeInt32(hw.getPageFlipCount());
1675 }
1676 return NO_ERROR;
1677 }
1678 }
1679 return err;
1680}
1681
1682// ---------------------------------------------------------------------------
1683#if 0
1684#pragma mark -
1685#endif
1686
1687Client::Client(ClientID clientID, const sp<SurfaceFlinger>& flinger)
1688 : ctrlblk(0), cid(clientID), mPid(0), mBitmap(0), mFlinger(flinger)
1689{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001690 const int pgsize = getpagesize();
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001691 const int cblksize = ((sizeof(per_client_cblk_t)+(pgsize-1))&~(pgsize-1));
1692
1693 mCblkHeap = new MemoryHeapBase(cblksize, 0,
1694 "SurfaceFlinger Client control-block");
1695
1696 ctrlblk = static_cast<per_client_cblk_t *>(mCblkHeap->getBase());
1697 if (ctrlblk) { // construct the shared structure in-place.
1698 new(ctrlblk) per_client_cblk_t;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001699 }
1700}
1701
1702Client::~Client() {
1703 if (ctrlblk) {
1704 const int pgsize = getpagesize();
1705 ctrlblk->~per_client_cblk_t(); // destroy our shared-structure.
1706 }
1707}
1708
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709int32_t Client::generateId(int pid)
1710{
1711 const uint32_t i = clz( ~mBitmap );
1712 if (i >= NUM_LAYERS_MAX) {
1713 return NO_MEMORY;
1714 }
1715 mPid = pid;
1716 mInUse.add(uint8_t(i));
1717 mBitmap |= 1<<(31-i);
1718 return i;
1719}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001720
1721status_t Client::bindLayer(const sp<LayerBaseClient>& layer, int32_t id)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001722{
1723 ssize_t idx = mInUse.indexOf(id);
1724 if (idx < 0)
1725 return NAME_NOT_FOUND;
1726 return mLayers.insertAt(layer, idx);
1727}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001728
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001729void Client::free(int32_t id)
1730{
1731 ssize_t idx = mInUse.remove(uint8_t(id));
1732 if (idx >= 0) {
1733 mBitmap &= ~(1<<(31-id));
1734 mLayers.removeItemsAt(idx);
1735 }
1736}
1737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001738bool Client::isValid(int32_t i) const {
1739 return (uint32_t(i)<NUM_LAYERS_MAX) && (mBitmap & (1<<(31-i)));
1740}
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001741
1742sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1743 sp<LayerBaseClient> lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001744 ssize_t idx = mInUse.indexOf(uint8_t(i));
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001745 if (idx >= 0) {
1746 lbc = mLayers[idx].promote();
1747 LOGE_IF(lbc==0, "getLayerUser(i=%d), idx=%d is dead", int(i), int(idx));
1748 }
1749 return lbc;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001750}
1751
1752void Client::dump(const char* what)
1753{
1754}
1755
1756// ---------------------------------------------------------------------------
1757#if 0
1758#pragma mark -
1759#endif
1760
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001761BClient::BClient(SurfaceFlinger *flinger, ClientID cid, const sp<IMemoryHeap>& cblk)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001762 : mId(cid), mFlinger(flinger), mCblk(cblk)
1763{
1764}
1765
1766BClient::~BClient() {
1767 // destroy all resources attached to this client
1768 mFlinger->destroyConnection(mId);
1769}
1770
Mathias Agopian7303c6b2009-07-02 18:11:53 -07001771sp<IMemoryHeap> BClient::getControlBlock() const {
1772 return mCblk;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773}
1774
1775sp<ISurface> BClient::createSurface(
1776 ISurfaceFlingerClient::surface_data_t* params, int pid,
1777 DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1778 uint32_t flags)
1779{
1780 return mFlinger->createSurface(mId, pid, params, display, w, h, format, flags);
1781}
1782
1783status_t BClient::destroySurface(SurfaceID sid)
1784{
1785 sid |= (mId << 16); // add the client-part to id
Mathias Agopian9a112062009-04-17 19:36:26 -07001786 return mFlinger->removeSurface(sid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001787}
1788
1789status_t BClient::setState(int32_t count, const layer_state_t* states)
1790{
1791 return mFlinger->setClientState(mId, count, states);
1792}
1793
1794// ---------------------------------------------------------------------------
1795
1796GraphicPlane::GraphicPlane()
1797 : mHw(0)
1798{
1799}
1800
1801GraphicPlane::~GraphicPlane() {
1802 delete mHw;
1803}
1804
1805bool GraphicPlane::initialized() const {
1806 return mHw ? true : false;
1807}
1808
1809void GraphicPlane::setDisplayHardware(DisplayHardware *hw) {
1810 mHw = hw;
1811}
1812
1813void GraphicPlane::setTransform(const Transform& tr) {
1814 mTransform = tr;
1815 mGlobalTransform = mOrientationTransform * mTransform;
1816}
1817
1818status_t GraphicPlane::orientationToTransfrom(
1819 int orientation, int w, int h, Transform* tr)
1820{
1821 float a, b, c, d, x, y;
1822 switch (orientation) {
1823 case ISurfaceComposer::eOrientationDefault:
1824 a=1; b=0; c=0; d=1; x=0; y=0;
1825 break;
1826 case ISurfaceComposer::eOrientation90:
1827 a=0; b=-1; c=1; d=0; x=w; y=0;
1828 break;
1829 case ISurfaceComposer::eOrientation180:
1830 a=-1; b=0; c=0; d=-1; x=w; y=h;
1831 break;
1832 case ISurfaceComposer::eOrientation270:
1833 a=0; b=1; c=-1; d=0; x=0; y=h;
1834 break;
1835 default:
1836 return BAD_VALUE;
1837 }
1838 tr->set(a, b, c, d);
1839 tr->set(x, y);
1840 return NO_ERROR;
1841}
1842
1843status_t GraphicPlane::setOrientation(int orientation)
1844{
1845 const DisplayHardware& hw(displayHardware());
1846 const float w = hw.getWidth();
1847 const float h = hw.getHeight();
1848
1849 if (orientation == ISurfaceComposer::eOrientationDefault) {
1850 // make sure the default orientation is optimal
1851 mOrientationTransform.reset();
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001852 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853 mGlobalTransform = mTransform;
1854 return NO_ERROR;
1855 }
1856
1857 // If the rotation can be handled in hardware, this is where
1858 // the magic should happen.
1859 if (UNLIKELY(orientation == 42)) {
1860 float a, b, c, d, x, y;
1861 const float r = (3.14159265f / 180.0f) * 42.0f;
1862 const float si = sinf(r);
1863 const float co = cosf(r);
1864 a=co; b=-si; c=si; d=co;
1865 x = si*(h*0.5f) + (1-co)*(w*0.5f);
1866 y =-si*(w*0.5f) + (1-co)*(h*0.5f);
1867 mOrientationTransform.set(a, b, c, d);
1868 mOrientationTransform.set(x, y);
1869 } else {
1870 GraphicPlane::orientationToTransfrom(orientation, w, h,
1871 &mOrientationTransform);
1872 }
Mathias Agopian0d1318b2009-03-27 17:58:20 -07001873 mOrientation = orientation;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001874 mGlobalTransform = mOrientationTransform * mTransform;
1875 return NO_ERROR;
1876}
1877
1878const DisplayHardware& GraphicPlane::displayHardware() const {
1879 return *mHw;
1880}
1881
1882const Transform& GraphicPlane::transform() const {
1883 return mGlobalTransform;
1884}
1885
Mathias Agopian076b1cc2009-04-10 14:24:30 -07001886EGLDisplay GraphicPlane::getEGLDisplay() const {
1887 return mHw->getEGLDisplay();
1888}
1889
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001890// ---------------------------------------------------------------------------
1891
1892}; // namespace android