blob: 96395a883c1366de564c7eda3fb3f556cbe4fe02 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "SurfaceFlinger"
18
19#include <stdlib.h>
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <cutils/properties.h>
24
25#include <utils/Errors.h>
26#include <utils/Log.h>
27#include <utils/StopWatch.h>
28
29#include <ui/PixelFormat.h>
30#include <ui/EGLDisplaySurface.h>
31
32#include "clz.h"
33#include "Layer.h"
34#include "LayerBitmap.h"
35#include "SurfaceFlinger.h"
36#include "VRamHeap.h"
37#include "DisplayHardware/DisplayHardware.h"
38
39
40#define DEBUG_RESIZE 0
41
42
43namespace android {
44
45// ---------------------------------------------------------------------------
46
47const uint32_t Layer::typeInfo = LayerBaseClient::typeInfo | 4;
48const char* const Layer::typeID = "Layer";
49
50// ---------------------------------------------------------------------------
51
52Layer::Layer(SurfaceFlinger* flinger, DisplayID display, Client* c, int32_t i)
53 : LayerBaseClient(flinger, display, c, i),
54 mSecure(false),
55 mFrontBufferIndex(1),
56 mNeedsBlending(true),
57 mResizeTransactionDone(false),
58 mTextureName(-1U), mTextureWidth(0), mTextureHeight(0)
59{
60 // no OpenGL operation is possible here, since we might not be
61 // in the OpenGL thread.
62}
63
64Layer::~Layer()
65{
66 client->free(clientIndex());
67 // this should always be called from the OpenGL thread
68 if (mTextureName != -1U) {
69 //glDeleteTextures(1, &mTextureName);
70 deletedTextures.add(mTextureName);
71 }
72}
73
74void Layer::initStates(uint32_t w, uint32_t h, uint32_t flags)
75{
76 LayerBase::initStates(w,h,flags);
77
78 if (flags & ISurfaceComposer::eDestroyBackbuffer)
79 lcblk->flags |= eNoCopyBack;
80}
81
82sp<LayerBaseClient::Surface> Layer::getSurface() const
83{
84 return mSurface;
85}
86
87status_t Layer::setBuffers( Client* client,
88 uint32_t w, uint32_t h,
89 PixelFormat format, uint32_t flags)
90{
91 PixelFormatInfo info;
92 status_t err = getPixelFormatInfo(format, &info);
93 if (err) return err;
94
95 // TODO: if eHardware is explicitly requested, we should fail
96 // on systems where we can't allocate memory that can be used with
97 // DMA engines for instance.
98
99 // FIXME: we always ask for hardware for now (this should come from copybit)
100 flags |= ISurfaceComposer::eHardware;
101
102 const uint32_t memory_flags = flags &
103 (ISurfaceComposer::eGPU |
104 ISurfaceComposer::eHardware |
105 ISurfaceComposer::eSecure);
106
107 // pixel-alignment. the final alignment may be bigger because
108 // we always force a 4-byte aligned bpr.
109 uint32_t alignment = 1;
110
Mathias Agopian0c6b5f62009-04-27 18:50:06 -0700111 if ((flags & ISurfaceComposer::eGPU) && (mFlinger->getGPU() != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 // FIXME: this value should come from the h/w
113 alignment = 8;
114 // FIXME: this is msm7201A specific, as its GPU only supports
115 // BGRA_8888.
116 if (format == PIXEL_FORMAT_RGBA_8888) {
117 format = PIXEL_FORMAT_BGRA_8888;
118 }
119 }
120
121 mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;
122 mNeedsBlending = (info.h_alpha - info.l_alpha) > 0;
123 sp<MemoryDealer> allocators[2];
124 for (int i=0 ; i<2 ; i++) {
125 allocators[i] = client->createAllocator(memory_flags);
126 if (allocators[i] == 0)
127 return NO_MEMORY;
128 mBuffers[i].init(allocators[i]);
129 int err = mBuffers[i].setBits(w, h, alignment, format, LayerBitmap::SECURE_BITS);
130 if (err != NO_ERROR)
131 return err;
132 mBuffers[i].clear(); // clear the bits for security
133 mBuffers[i].getInfo(lcblk->surface + i);
134 }
135
136 mSurface = new Surface(clientIndex(),
137 allocators[0]->getMemoryHeap(),
138 allocators[1]->getMemoryHeap(),
139 mIdentity);
140
141 return NO_ERROR;
142}
143
144void Layer::reloadTexture(const Region& dirty)
145{
146 if (UNLIKELY(mTextureName == -1U)) {
147 // create the texture name the first time
148 // can't do that in the ctor, because it runs in another thread.
149 mTextureName = createTexture();
150 }
151 const GGLSurface& t(frontBuffer().surface());
152 loadTexture(dirty, mTextureName, t, mTextureWidth, mTextureHeight);
153}
154
155
156void Layer::onDraw(const Region& clip) const
157{
158 if (UNLIKELY(mTextureName == -1LU)) {
159 //LOGW("Layer %p doesn't have a texture", this);
160 // the texture has not been created yet, this Layer has
161 // in fact never been drawn into. this happens frequently with
162 // SurfaceView.
163 clearWithOpenGL(clip);
164 return;
165 }
166
167 const DisplayHardware& hw(graphicPlane(0).displayHardware());
168 const LayerBitmap& front(frontBuffer());
169 const GGLSurface& t(front.surface());
170
171 status_t err = NO_ERROR;
172 const int can_use_copybit = canUseCopybit();
173 if (can_use_copybit) {
174 // StopWatch watch("copybit");
175 const State& s(drawingState());
176
177 copybit_image_t dst;
178 hw.getDisplaySurface(&dst);
179 const copybit_rect_t& drect
180 = reinterpret_cast<const copybit_rect_t&>(mTransformedBounds);
181
182 copybit_image_t src;
183 front.getBitmapSurface(&src);
184 copybit_rect_t srect = { 0, 0, t.width, t.height };
185
186 copybit_device_t* copybit = mFlinger->getBlitEngine();
187 copybit->set_parameter(copybit, COPYBIT_TRANSFORM, getOrientation());
188 copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, s.alpha);
189 copybit->set_parameter(copybit, COPYBIT_DITHER,
190 s.flags & ISurfaceComposer::eLayerDither ?
191 COPYBIT_ENABLE : COPYBIT_DISABLE);
192
193 region_iterator it(clip);
194 err = copybit->stretch(copybit, &dst, &src, &drect, &srect, &it);
195 }
196
197 if (!can_use_copybit || err) {
198 drawWithOpenGL(clip, mTextureName, t);
199 }
200}
201
202status_t Layer::reallocateBuffer(int32_t index, uint32_t w, uint32_t h)
203{
204 LOGD_IF(DEBUG_RESIZE,
205 "reallocateBuffer (layer=%p), "
206 "requested (%dx%d), "
207 "index=%d, (%dx%d), (%dx%d)",
208 this,
209 int(w), int(h),
210 int(index),
211 int(mBuffers[0].width()), int(mBuffers[0].height()),
212 int(mBuffers[1].width()), int(mBuffers[1].height()));
213
214 status_t err = mBuffers[index].resize(w, h);
215 if (err == NO_ERROR) {
216 mBuffers[index].getInfo(lcblk->surface + index);
217 } else {
218 LOGE("resizing buffer %d to (%u,%u) failed [%08x] %s",
219 index, w, h, err, strerror(err));
220 // XXX: what to do, what to do? We could try to free some
221 // hidden surfaces, instead of killing this one?
222 }
223 return err;
224}
225
226uint32_t Layer::doTransaction(uint32_t flags)
227{
228 const Layer::State& front(drawingState());
229 const Layer::State& temp(currentState());
230
231 // the test front.{w|h} != temp.{w|h} is not enough because it is possible
232 // that the size changed back to its previous value before the buffer
233 // was resized (in the eLocked case below), in which case, we still
234 // need to execute the code below so the clients have a chance to be
235 // release. resze() deals with the fact that the size can be the same.
236
237 /*
238 * Various states we could be in...
239
240 resize = state & eResizeRequested;
241 if (backbufferChanged) {
242 if (resize == 0) {
243 // ERROR, the resized buffer doesn't have its resize flag set
244 } else if (resize == mask) {
245 // ERROR one of the buffer has already been resized
246 } else if (resize == mask ^ eResizeRequested) {
247 // ERROR, the resized buffer doesn't have its resize flag set
248 } else if (resize == eResizeRequested) {
249 // OK, Normal case, proceed with resize
250 }
251 } else {
252 if (resize == 0) {
253 // OK, nothing special, do nothing
254 } else if (resize == mask) {
255 // restarted transaction, do nothing
256 } else if (resize == mask ^ eResizeRequested) {
257 // restarted transaction, do nothing
258 } else if (resize == eResizeRequested) {
259 // OK, size reset to previous value, proceed with resize
260 }
261 }
262 */
263
264 // Index of the back buffer
265 const bool backbufferChanged = (front.w != temp.w) || (front.h != temp.h);
266 const uint32_t state = lcblk->swapState;
267 const int32_t clientBackBufferIndex = layer_cblk_t::backBuffer(state);
268 const uint32_t mask = clientBackBufferIndex ? eResizeBuffer1 : eResizeBuffer0;
269 uint32_t resizeFlags = state & eResizeRequested;
270
271 if (UNLIKELY(backbufferChanged && (resizeFlags != eResizeRequested))) {
272 LOGE( "backbuffer size changed, but both resize flags are not set! "
273 "(layer=%p), state=%08x, requested (%dx%d), drawing (%d,%d), "
274 "index=%d, (%dx%d), (%dx%d)",
275 this, state,
276 int(temp.w), int(temp.h),
277 int(drawingState().w), int(drawingState().h),
278 int(clientBackBufferIndex),
279 int(mBuffers[0].width()), int(mBuffers[0].height()),
280 int(mBuffers[1].width()), int(mBuffers[1].height()));
281 // if we get there we're pretty screwed. the only reasonable
282 // thing to do is to pretend we should do the resize since
283 // backbufferChanged is set (this also will give a chance to
284 // client to get unblocked)
285 resizeFlags = eResizeRequested;
286 }
287
288 if (resizeFlags == eResizeRequested) {
289 // NOTE: asserting that clientBackBufferIndex!=mFrontBufferIndex
290 // here, would be wrong and misleading because by this point
291 // mFrontBufferIndex has not been updated yet.
292
293 LOGD_IF(DEBUG_RESIZE,
294 "resize (layer=%p), state=%08x, "
295 "requested (%dx%d), "
296 "drawing (%d,%d), "
297 "index=%d, (%dx%d), (%dx%d)",
298 this, state,
299 int(temp.w), int(temp.h),
300 int(drawingState().w), int(drawingState().h),
301 int(clientBackBufferIndex),
302 int(mBuffers[0].width()), int(mBuffers[0].height()),
303 int(mBuffers[1].width()), int(mBuffers[1].height()));
304
305 if (state & eLocked) {
306 // if the buffer is locked, we can't resize anything because
307 // - the backbuffer is currently in use by the user
308 // - the front buffer is being shown
309 // We just act as if the transaction didn't happen and we
310 // reschedule it later...
311 flags |= eRestartTransaction;
312 } else {
313 // This buffer needs to be resized
314 status_t err =
315 resize(clientBackBufferIndex, temp.w, temp.h, "transaction");
316 if (err == NO_ERROR) {
317 const uint32_t mask = clientBackBufferIndex ? eResizeBuffer1 : eResizeBuffer0;
318 android_atomic_and(~mask, &(lcblk->swapState));
319 // since a buffer became available, we can let the client go...
320 mFlinger->scheduleBroadcast(client);
321 mResizeTransactionDone = true;
322
323 // we're being resized and there is a freeze display request,
324 // acquire a freeze lock, so that the screen stays put
325 // until we've redrawn at the new size; this is to avoid
326 // glitches upon orientation changes.
327 if (mFlinger->hasFreezeRequest()) {
328 // if the surface is hidden, don't try to acquire the
329 // freeze lock, since hidden surfaces may never redraw
330 if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
331 mFreezeLock = mFlinger->getFreezeLock();
332 }
333 }
334 }
335 }
336 }
337
338 if (temp.sequence != front.sequence) {
339 if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
340 // this surface is now hidden, so it shouldn't hold a freeze lock
341 // (it may never redraw, which is fine if it is hidden)
342 mFreezeLock.clear();
343 }
344 }
345
346 return LayerBase::doTransaction(flags);
347}
348
349status_t Layer::resize(
350 int32_t clientBackBufferIndex,
351 uint32_t width, uint32_t height,
352 const char* what)
353{
354 /*
355 * handle resize (backbuffer and frontbuffer reallocation)
356 */
357
358 const LayerBitmap& clientBackBuffer(mBuffers[clientBackBufferIndex]);
359
360 // if the new (transaction) size is != from the the backbuffer
361 // then we need to reallocate the backbuffer
362 bool backbufferChanged = (clientBackBuffer.width() != width) ||
363 (clientBackBuffer.height() != height);
364
365 LOGD_IF(!backbufferChanged,
366 "(%s) eResizeRequested (layer=%p), but size not changed: "
367 "requested (%dx%d), drawing (%d,%d), current (%d,%d),"
368 "state=%08lx, index=%d, (%dx%d), (%dx%d)",
369 what, this,
370 int(width), int(height),
371 int(drawingState().w), int(drawingState().h),
372 int(currentState().w), int(currentState().h),
373 long(lcblk->swapState),
374 int(clientBackBufferIndex),
375 int(mBuffers[0].width()), int(mBuffers[0].height()),
376 int(mBuffers[1].width()), int(mBuffers[1].height()));
377
378 // this can happen when changing the size back and forth quickly
379 status_t err = NO_ERROR;
380 if (backbufferChanged) {
381 err = reallocateBuffer(clientBackBufferIndex, width, height);
382 }
383 if (UNLIKELY(err != NO_ERROR)) {
384 // couldn't reallocate the surface
385 android_atomic_write(eInvalidSurface, &lcblk->swapState);
386 memset(lcblk->surface+clientBackBufferIndex, 0, sizeof(surface_info_t));
387 }
388 return err;
389}
390
391void Layer::setSizeChanged(uint32_t w, uint32_t h)
392{
393 LOGD_IF(DEBUG_RESIZE,
394 "setSizeChanged w=%d, h=%d (old: w=%d, h=%d)",
395 w, h, mCurrentState.w, mCurrentState.h);
396 android_atomic_or(eResizeRequested, &(lcblk->swapState));
397}
398
399// ----------------------------------------------------------------------------
400// pageflip handling...
401// ----------------------------------------------------------------------------
402
403void Layer::lockPageFlip(bool& recomputeVisibleRegions)
404{
405 uint32_t state = android_atomic_or(eBusy, &(lcblk->swapState));
406 // preemptively block the client, because he might set
407 // eFlipRequested at any time and want to use this buffer
408 // for the next frame. This will be unset below if it
409 // turns out we didn't need it.
410
411 uint32_t mask = eInvalidSurface | eFlipRequested | eResizeRequested;
412 if (!(state & mask))
413 return;
414
415 if (UNLIKELY(state & eInvalidSurface)) {
416 // if eInvalidSurface is set, this means the surface
417 // became invalid during a transaction (NO_MEMORY for instance)
418 mFlinger->scheduleBroadcast(client);
419 return;
420 }
421
422 if (UNLIKELY(state & eFlipRequested)) {
423 uint32_t oldState;
424 mPostedDirtyRegion = post(&oldState, recomputeVisibleRegions);
425 if (oldState & eNextFlipPending) {
426 // Process another round (we know at least a buffer
427 // is ready for that client).
428 mFlinger->signalEvent();
429 }
430 }
431}
432
433Region Layer::post(uint32_t* previousSate, bool& recomputeVisibleRegions)
434{
435 // atomically swap buffers and (re)set eFlipRequested
436 int32_t oldValue, newValue;
437 layer_cblk_t * const lcblk = this->lcblk;
438 do {
439 oldValue = lcblk->swapState;
440 // get the current value
441
442 LOG_ASSERT(oldValue&eFlipRequested,
443 "eFlipRequested not set, yet we're flipping! (state=0x%08lx)",
444 long(oldValue));
445
446 newValue = (oldValue ^ eIndex);
447 // swap buffers
448
449 newValue &= ~(eFlipRequested | eNextFlipPending);
450 // clear eFlipRequested and eNextFlipPending
451
452 if (oldValue & eNextFlipPending)
453 newValue |= eFlipRequested;
454 // if eNextFlipPending is set (second buffer already has something
455 // in it) we need to reset eFlipRequested because the client
456 // might never do it
457
458 } while(android_atomic_cmpxchg(oldValue, newValue, &(lcblk->swapState)));
459 *previousSate = oldValue;
460
461 const int32_t index = (newValue & eIndex) ^ 1;
462 mFrontBufferIndex = index;
463
464 // ... post the new front-buffer
465 Region dirty(lcblk->region + index);
466 dirty.andSelf(frontBuffer().bounds());
467
468 //LOGI("Did post oldValue=%08lx, newValue=%08lx, mFrontBufferIndex=%u\n",
469 // oldValue, newValue, mFrontBufferIndex);
470 //dirty.dump("dirty");
471
472 if (UNLIKELY(oldValue & eResizeRequested)) {
473
474 LOGD_IF(DEBUG_RESIZE,
475 "post (layer=%p), state=%08x, "
476 "index=%d, (%dx%d), (%dx%d)",
477 this, newValue,
478 int(1-index),
479 int(mBuffers[0].width()), int(mBuffers[0].height()),
480 int(mBuffers[1].width()), int(mBuffers[1].height()));
481
482 // here, we just posted the surface and we have resolved
483 // the front/back buffer indices. The client is blocked, so
484 // it cannot start using the new backbuffer.
485
486 // If the backbuffer was resized in THIS round, we actually cannot
487 // resize the frontbuffer because it has *just* been drawn (and we
488 // would have nothing to draw). In this case we just skip the resize
489 // it'll happen after the next page flip or during the next
490 // transaction.
491
492 const uint32_t mask = (1-index) ? eResizeBuffer1 : eResizeBuffer0;
493 if (mResizeTransactionDone && (newValue & mask)) {
494 // Resize the layer's second buffer only if the transaction
495 // happened. It may not have happened yet if eResizeRequested
496 // was set immediately after the "transactionRequested" test,
497 // in which case the drawing state's size would be wrong.
498 mFreezeLock.clear();
499 const Layer::State& s(drawingState());
500 if (resize(1-index, s.w, s.h, "post") == NO_ERROR) {
501 do {
502 oldValue = lcblk->swapState;
503 if ((oldValue & eResizeRequested) == eResizeRequested) {
504 // ugh, another resize was requested since we processed
505 // the first buffer, don't free the client, and let
506 // the next transaction handle everything.
507 break;
508 }
509 newValue = oldValue & ~mask;
510 } while(android_atomic_cmpxchg(oldValue, newValue, &(lcblk->swapState)));
511 }
512 mResizeTransactionDone = false;
513 recomputeVisibleRegions = true;
514 this->contentDirty = true;
515 }
516 }
517
518 reloadTexture(dirty);
519
520 return dirty;
521}
522
523Point Layer::getPhysicalSize() const
524{
525 const LayerBitmap& front(frontBuffer());
526 return Point(front.width(), front.height());
527}
528
529void Layer::unlockPageFlip(
530 const Transform& planeTransform, Region& outDirtyRegion)
531{
532 Region dirtyRegion(mPostedDirtyRegion);
533 if (!dirtyRegion.isEmpty()) {
534 mPostedDirtyRegion.clear();
535 // The dirty region is given in the layer's coordinate space
536 // transform the dirty region by the surface's transformation
537 // and the global transformation.
538 const Layer::State& s(drawingState());
539 const Transform tr(planeTransform * s.transform);
540 dirtyRegion = tr.transform(dirtyRegion);
541
542 // At this point, the dirty region is in screen space.
543 // Make sure it's constrained by the visible region (which
544 // is in screen space as well).
545 dirtyRegion.andSelf(visibleRegionScreen);
546 outDirtyRegion.orSelf(dirtyRegion);
547
548 // client could be blocked, so signal them so they get a
549 // chance to reevaluate their condition.
550 mFlinger->scheduleBroadcast(client);
551 }
552}
553
554void Layer::finishPageFlip()
555{
556 if (LIKELY(!(lcblk->swapState & eInvalidSurface))) {
557 LOGE_IF(!(lcblk->swapState & eBusy),
558 "layer %p wasn't locked!", this);
559 android_atomic_and(~eBusy, &(lcblk->swapState));
560 }
561 mFlinger->scheduleBroadcast(client);
562}
563
564
565// ---------------------------------------------------------------------------
566
567
568}; // namespace android