Home | History | Annotate | Download | only in gui
      1 /*
      2  * Copyright (C) 2010 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 "Surface"
     18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
     19 //#define LOG_NDEBUG 0
     20 
     21 #include <android/native_window.h>
     22 
     23 #include <binder/Parcel.h>
     24 
     25 #include <utils/Log.h>
     26 #include <utils/Trace.h>
     27 #include <utils/NativeHandle.h>
     28 
     29 #include <ui/Fence.h>
     30 
     31 #include <gui/IProducerListener.h>
     32 #include <gui/ISurfaceComposer.h>
     33 #include <gui/SurfaceComposerClient.h>
     34 #include <gui/GLConsumer.h>
     35 #include <gui/Surface.h>
     36 
     37 #include <private/gui/ComposerService.h>
     38 
     39 namespace android {
     40 
     41 Surface::Surface(
     42         const sp<IGraphicBufferProducer>& bufferProducer,
     43         bool controlledByApp)
     44     : mGraphicBufferProducer(bufferProducer)
     45 {
     46     // Initialize the ANativeWindow function pointers.
     47     ANativeWindow::setSwapInterval  = hook_setSwapInterval;
     48     ANativeWindow::dequeueBuffer    = hook_dequeueBuffer;
     49     ANativeWindow::cancelBuffer     = hook_cancelBuffer;
     50     ANativeWindow::queueBuffer      = hook_queueBuffer;
     51     ANativeWindow::query            = hook_query;
     52     ANativeWindow::perform          = hook_perform;
     53 
     54     ANativeWindow::dequeueBuffer_DEPRECATED = hook_dequeueBuffer_DEPRECATED;
     55     ANativeWindow::cancelBuffer_DEPRECATED  = hook_cancelBuffer_DEPRECATED;
     56     ANativeWindow::lockBuffer_DEPRECATED    = hook_lockBuffer_DEPRECATED;
     57     ANativeWindow::queueBuffer_DEPRECATED   = hook_queueBuffer_DEPRECATED;
     58 
     59     const_cast<int&>(ANativeWindow::minSwapInterval) = 0;
     60     const_cast<int&>(ANativeWindow::maxSwapInterval) = 1;
     61 
     62     mReqWidth = 0;
     63     mReqHeight = 0;
     64     mReqFormat = 0;
     65     mReqUsage = 0;
     66     mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
     67     mCrop.clear();
     68     mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
     69     mTransform = 0;
     70     mStickyTransform = 0;
     71     mDefaultWidth = 0;
     72     mDefaultHeight = 0;
     73     mUserWidth = 0;
     74     mUserHeight = 0;
     75     mTransformHint = 0;
     76     mConsumerRunningBehind = false;
     77     mConnectedToCpu = false;
     78     mProducerControlledByApp = controlledByApp;
     79     mSwapIntervalZero = false;
     80 }
     81 
     82 Surface::~Surface() {
     83     if (mConnectedToCpu) {
     84         Surface::disconnect(NATIVE_WINDOW_API_CPU);
     85     }
     86 }
     87 
     88 sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
     89     return mGraphicBufferProducer;
     90 }
     91 
     92 void Surface::setSidebandStream(const sp<NativeHandle>& stream) {
     93     mGraphicBufferProducer->setSidebandStream(stream);
     94 }
     95 
     96 void Surface::allocateBuffers() {
     97     uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
     98     uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
     99     mGraphicBufferProducer->allocateBuffers(mSwapIntervalZero, mReqWidth,
    100             mReqHeight, mReqFormat, mReqUsage);
    101 }
    102 
    103 int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
    104     Surface* c = getSelf(window);
    105     return c->setSwapInterval(interval);
    106 }
    107 
    108 int Surface::hook_dequeueBuffer(ANativeWindow* window,
    109         ANativeWindowBuffer** buffer, int* fenceFd) {
    110     Surface* c = getSelf(window);
    111     return c->dequeueBuffer(buffer, fenceFd);
    112 }
    113 
    114 int Surface::hook_cancelBuffer(ANativeWindow* window,
    115         ANativeWindowBuffer* buffer, int fenceFd) {
    116     Surface* c = getSelf(window);
    117     return c->cancelBuffer(buffer, fenceFd);
    118 }
    119 
    120 int Surface::hook_queueBuffer(ANativeWindow* window,
    121         ANativeWindowBuffer* buffer, int fenceFd) {
    122     Surface* c = getSelf(window);
    123     return c->queueBuffer(buffer, fenceFd);
    124 }
    125 
    126 int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
    127         ANativeWindowBuffer** buffer) {
    128     Surface* c = getSelf(window);
    129     ANativeWindowBuffer* buf;
    130     int fenceFd = -1;
    131     int result = c->dequeueBuffer(&buf, &fenceFd);
    132     sp<Fence> fence(new Fence(fenceFd));
    133     int waitResult = fence->waitForever("dequeueBuffer_DEPRECATED");
    134     if (waitResult != OK) {
    135         ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
    136                 waitResult);
    137         c->cancelBuffer(buf, -1);
    138         return waitResult;
    139     }
    140     *buffer = buf;
    141     return result;
    142 }
    143 
    144 int Surface::hook_cancelBuffer_DEPRECATED(ANativeWindow* window,
    145         ANativeWindowBuffer* buffer) {
    146     Surface* c = getSelf(window);
    147     return c->cancelBuffer(buffer, -1);
    148 }
    149 
    150 int Surface::hook_lockBuffer_DEPRECATED(ANativeWindow* window,
    151         ANativeWindowBuffer* buffer) {
    152     Surface* c = getSelf(window);
    153     return c->lockBuffer_DEPRECATED(buffer);
    154 }
    155 
    156 int Surface::hook_queueBuffer_DEPRECATED(ANativeWindow* window,
    157         ANativeWindowBuffer* buffer) {
    158     Surface* c = getSelf(window);
    159     return c->queueBuffer(buffer, -1);
    160 }
    161 
    162 int Surface::hook_query(const ANativeWindow* window,
    163                                 int what, int* value) {
    164     const Surface* c = getSelf(window);
    165     return c->query(what, value);
    166 }
    167 
    168 int Surface::hook_perform(ANativeWindow* window, int operation, ...) {
    169     va_list args;
    170     va_start(args, operation);
    171     Surface* c = getSelf(window);
    172     return c->perform(operation, args);
    173 }
    174 
    175 int Surface::setSwapInterval(int interval) {
    176     ATRACE_CALL();
    177     // EGL specification states:
    178     //  interval is silently clamped to minimum and maximum implementation
    179     //  dependent values before being stored.
    180 
    181     if (interval < minSwapInterval)
    182         interval = minSwapInterval;
    183 
    184     if (interval > maxSwapInterval)
    185         interval = maxSwapInterval;
    186 
    187     mSwapIntervalZero = (interval == 0);
    188 
    189     return NO_ERROR;
    190 }
    191 
    192 int Surface::dequeueBuffer(android_native_buffer_t** buffer, int* fenceFd) {
    193     ATRACE_CALL();
    194     ALOGV("Surface::dequeueBuffer");
    195 
    196     int reqW;
    197     int reqH;
    198     bool swapIntervalZero;
    199     uint32_t reqFormat;
    200     uint32_t reqUsage;
    201 
    202     {
    203         Mutex::Autolock lock(mMutex);
    204 
    205         reqW = mReqWidth ? mReqWidth : mUserWidth;
    206         reqH = mReqHeight ? mReqHeight : mUserHeight;
    207 
    208         swapIntervalZero = mSwapIntervalZero;
    209         reqFormat = mReqFormat;
    210         reqUsage = mReqUsage;
    211     } // Drop the lock so that we can still touch the Surface while blocking in IGBP::dequeueBuffer
    212 
    213     int buf = -1;
    214     sp<Fence> fence;
    215     status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, swapIntervalZero,
    216             reqW, reqH, reqFormat, reqUsage);
    217 
    218     if (result < 0) {
    219         ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer(%d, %d, %d, %d, %d)"
    220              "failed: %d", swapIntervalZero, reqW, reqH, reqFormat, reqUsage,
    221              result);
    222         return result;
    223     }
    224 
    225     Mutex::Autolock lock(mMutex);
    226 
    227     sp<GraphicBuffer>& gbuf(mSlots[buf].buffer);
    228 
    229     // this should never happen
    230     ALOGE_IF(fence == NULL, "Surface::dequeueBuffer: received null Fence! buf=%d", buf);
    231 
    232     if (result & IGraphicBufferProducer::RELEASE_ALL_BUFFERS) {
    233         freeAllBuffers();
    234     }
    235 
    236     if ((result & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) || gbuf == 0) {
    237         result = mGraphicBufferProducer->requestBuffer(buf, &gbuf);
    238         if (result != NO_ERROR) {
    239             ALOGE("dequeueBuffer: IGraphicBufferProducer::requestBuffer failed: %d", result);
    240             mGraphicBufferProducer->cancelBuffer(buf, fence);
    241             return result;
    242         }
    243     }
    244 
    245     if (fence->isValid()) {
    246         *fenceFd = fence->dup();
    247         if (*fenceFd == -1) {
    248             ALOGE("dequeueBuffer: error duping fence: %d", errno);
    249             // dup() should never fail; something is badly wrong. Soldier on
    250             // and hope for the best; the worst that should happen is some
    251             // visible corruption that lasts until the next frame.
    252         }
    253     } else {
    254         *fenceFd = -1;
    255     }
    256 
    257     *buffer = gbuf.get();
    258     return OK;
    259 }
    260 
    261 int Surface::cancelBuffer(android_native_buffer_t* buffer,
    262         int fenceFd) {
    263     ATRACE_CALL();
    264     ALOGV("Surface::cancelBuffer");
    265     Mutex::Autolock lock(mMutex);
    266     int i = getSlotFromBufferLocked(buffer);
    267     if (i < 0) {
    268         return i;
    269     }
    270     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
    271     mGraphicBufferProducer->cancelBuffer(i, fence);
    272     return OK;
    273 }
    274 
    275 int Surface::getSlotFromBufferLocked(
    276         android_native_buffer_t* buffer) const {
    277     bool dumpedState = false;
    278     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
    279         if (mSlots[i].buffer != NULL &&
    280                 mSlots[i].buffer->handle == buffer->handle) {
    281             return i;
    282         }
    283     }
    284     ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
    285     return BAD_VALUE;
    286 }
    287 
    288 int Surface::lockBuffer_DEPRECATED(android_native_buffer_t* buffer __attribute__((unused))) {
    289     ALOGV("Surface::lockBuffer");
    290     Mutex::Autolock lock(mMutex);
    291     return OK;
    292 }
    293 
    294 int Surface::queueBuffer(android_native_buffer_t* buffer, int fenceFd) {
    295     ATRACE_CALL();
    296     ALOGV("Surface::queueBuffer");
    297     Mutex::Autolock lock(mMutex);
    298     int64_t timestamp;
    299     bool isAutoTimestamp = false;
    300     if (mTimestamp == NATIVE_WINDOW_TIMESTAMP_AUTO) {
    301         timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
    302         isAutoTimestamp = true;
    303         ALOGV("Surface::queueBuffer making up timestamp: %.2f ms",
    304             timestamp / 1000000.f);
    305     } else {
    306         timestamp = mTimestamp;
    307     }
    308     int i = getSlotFromBufferLocked(buffer);
    309     if (i < 0) {
    310         return i;
    311     }
    312 
    313 
    314     // Make sure the crop rectangle is entirely inside the buffer.
    315     Rect crop;
    316     mCrop.intersect(Rect(buffer->width, buffer->height), &crop);
    317 
    318     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
    319     IGraphicBufferProducer::QueueBufferOutput output;
    320     IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
    321             crop, mScalingMode, mTransform ^ mStickyTransform, mSwapIntervalZero,
    322             fence, mStickyTransform);
    323     status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
    324     if (err != OK)  {
    325         ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
    326     }
    327     uint32_t numPendingBuffers = 0;
    328     uint32_t hint = 0;
    329     output.deflate(&mDefaultWidth, &mDefaultHeight, &hint,
    330             &numPendingBuffers);
    331 
    332     // Disable transform hint if sticky transform is set.
    333     if (mStickyTransform == 0) {
    334         mTransformHint = hint;
    335     }
    336 
    337     mConsumerRunningBehind = (numPendingBuffers >= 2);
    338 
    339     return err;
    340 }
    341 
    342 int Surface::query(int what, int* value) const {
    343     ATRACE_CALL();
    344     ALOGV("Surface::query");
    345     { // scope for the lock
    346         Mutex::Autolock lock(mMutex);
    347         switch (what) {
    348             case NATIVE_WINDOW_FORMAT:
    349                 if (mReqFormat) {
    350                     *value = mReqFormat;
    351                     return NO_ERROR;
    352                 }
    353                 break;
    354             case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER: {
    355                 sp<ISurfaceComposer> composer(
    356                         ComposerService::getComposerService());
    357                 if (composer->authenticateSurfaceTexture(mGraphicBufferProducer)) {
    358                     *value = 1;
    359                 } else {
    360                     *value = 0;
    361                 }
    362                 return NO_ERROR;
    363             }
    364             case NATIVE_WINDOW_CONCRETE_TYPE:
    365                 *value = NATIVE_WINDOW_SURFACE;
    366                 return NO_ERROR;
    367             case NATIVE_WINDOW_DEFAULT_WIDTH:
    368                 *value = mUserWidth ? mUserWidth : mDefaultWidth;
    369                 return NO_ERROR;
    370             case NATIVE_WINDOW_DEFAULT_HEIGHT:
    371                 *value = mUserHeight ? mUserHeight : mDefaultHeight;
    372                 return NO_ERROR;
    373             case NATIVE_WINDOW_TRANSFORM_HINT:
    374                 *value = mTransformHint;
    375                 return NO_ERROR;
    376             case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
    377                 status_t err = NO_ERROR;
    378                 if (!mConsumerRunningBehind) {
    379                     *value = 0;
    380                 } else {
    381                     err = mGraphicBufferProducer->query(what, value);
    382                     if (err == NO_ERROR) {
    383                         mConsumerRunningBehind = *value;
    384                     }
    385                 }
    386                 return err;
    387             }
    388         }
    389     }
    390     return mGraphicBufferProducer->query(what, value);
    391 }
    392 
    393 int Surface::perform(int operation, va_list args)
    394 {
    395     int res = NO_ERROR;
    396     switch (operation) {
    397     case NATIVE_WINDOW_CONNECT:
    398         // deprecated. must return NO_ERROR.
    399         break;
    400     case NATIVE_WINDOW_DISCONNECT:
    401         // deprecated. must return NO_ERROR.
    402         break;
    403     case NATIVE_WINDOW_SET_USAGE:
    404         res = dispatchSetUsage(args);
    405         break;
    406     case NATIVE_WINDOW_SET_CROP:
    407         res = dispatchSetCrop(args);
    408         break;
    409     case NATIVE_WINDOW_SET_BUFFER_COUNT:
    410         res = dispatchSetBufferCount(args);
    411         break;
    412     case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
    413         res = dispatchSetBuffersGeometry(args);
    414         break;
    415     case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
    416         res = dispatchSetBuffersTransform(args);
    417         break;
    418     case NATIVE_WINDOW_SET_BUFFERS_STICKY_TRANSFORM:
    419         res = dispatchSetBuffersStickyTransform(args);
    420         break;
    421     case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
    422         res = dispatchSetBuffersTimestamp(args);
    423         break;
    424     case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS:
    425         res = dispatchSetBuffersDimensions(args);
    426         break;
    427     case NATIVE_WINDOW_SET_BUFFERS_USER_DIMENSIONS:
    428         res = dispatchSetBuffersUserDimensions(args);
    429         break;
    430     case NATIVE_WINDOW_SET_BUFFERS_FORMAT:
    431         res = dispatchSetBuffersFormat(args);
    432         break;
    433     case NATIVE_WINDOW_LOCK:
    434         res = dispatchLock(args);
    435         break;
    436     case NATIVE_WINDOW_UNLOCK_AND_POST:
    437         res = dispatchUnlockAndPost(args);
    438         break;
    439     case NATIVE_WINDOW_SET_SCALING_MODE:
    440         res = dispatchSetScalingMode(args);
    441         break;
    442     case NATIVE_WINDOW_API_CONNECT:
    443         res = dispatchConnect(args);
    444         break;
    445     case NATIVE_WINDOW_API_DISCONNECT:
    446         res = dispatchDisconnect(args);
    447         break;
    448     case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
    449         res = dispatchSetSidebandStream(args);
    450         break;
    451     default:
    452         res = NAME_NOT_FOUND;
    453         break;
    454     }
    455     return res;
    456 }
    457 
    458 int Surface::dispatchConnect(va_list args) {
    459     int api = va_arg(args, int);
    460     return connect(api);
    461 }
    462 
    463 int Surface::dispatchDisconnect(va_list args) {
    464     int api = va_arg(args, int);
    465     return disconnect(api);
    466 }
    467 
    468 int Surface::dispatchSetUsage(va_list args) {
    469     int usage = va_arg(args, int);
    470     return setUsage(usage);
    471 }
    472 
    473 int Surface::dispatchSetCrop(va_list args) {
    474     android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
    475     return setCrop(reinterpret_cast<Rect const*>(rect));
    476 }
    477 
    478 int Surface::dispatchSetBufferCount(va_list args) {
    479     size_t bufferCount = va_arg(args, size_t);
    480     return setBufferCount(bufferCount);
    481 }
    482 
    483 int Surface::dispatchSetBuffersGeometry(va_list args) {
    484     int w = va_arg(args, int);
    485     int h = va_arg(args, int);
    486     int f = va_arg(args, int);
    487     int err = setBuffersDimensions(w, h);
    488     if (err != 0) {
    489         return err;
    490     }
    491     return setBuffersFormat(f);
    492 }
    493 
    494 int Surface::dispatchSetBuffersDimensions(va_list args) {
    495     int w = va_arg(args, int);
    496     int h = va_arg(args, int);
    497     return setBuffersDimensions(w, h);
    498 }
    499 
    500 int Surface::dispatchSetBuffersUserDimensions(va_list args) {
    501     int w = va_arg(args, int);
    502     int h = va_arg(args, int);
    503     return setBuffersUserDimensions(w, h);
    504 }
    505 
    506 int Surface::dispatchSetBuffersFormat(va_list args) {
    507     int f = va_arg(args, int);
    508     return setBuffersFormat(f);
    509 }
    510 
    511 int Surface::dispatchSetScalingMode(va_list args) {
    512     int m = va_arg(args, int);
    513     return setScalingMode(m);
    514 }
    515 
    516 int Surface::dispatchSetBuffersTransform(va_list args) {
    517     int transform = va_arg(args, int);
    518     return setBuffersTransform(transform);
    519 }
    520 
    521 int Surface::dispatchSetBuffersStickyTransform(va_list args) {
    522     int transform = va_arg(args, int);
    523     return setBuffersStickyTransform(transform);
    524 }
    525 
    526 int Surface::dispatchSetBuffersTimestamp(va_list args) {
    527     int64_t timestamp = va_arg(args, int64_t);
    528     return setBuffersTimestamp(timestamp);
    529 }
    530 
    531 int Surface::dispatchLock(va_list args) {
    532     ANativeWindow_Buffer* outBuffer = va_arg(args, ANativeWindow_Buffer*);
    533     ARect* inOutDirtyBounds = va_arg(args, ARect*);
    534     return lock(outBuffer, inOutDirtyBounds);
    535 }
    536 
    537 int Surface::dispatchUnlockAndPost(va_list args __attribute__((unused))) {
    538     return unlockAndPost();
    539 }
    540 
    541 int Surface::dispatchSetSidebandStream(va_list args) {
    542     native_handle_t* sH = va_arg(args, native_handle_t*);
    543     sp<NativeHandle> sidebandHandle = NativeHandle::create(sH, false);
    544     setSidebandStream(sidebandHandle);
    545     return OK;
    546 }
    547 
    548 int Surface::connect(int api) {
    549     ATRACE_CALL();
    550     ALOGV("Surface::connect");
    551     static sp<IProducerListener> listener = new DummyProducerListener();
    552     Mutex::Autolock lock(mMutex);
    553     IGraphicBufferProducer::QueueBufferOutput output;
    554     int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
    555     if (err == NO_ERROR) {
    556         uint32_t numPendingBuffers = 0;
    557         uint32_t hint = 0;
    558         output.deflate(&mDefaultWidth, &mDefaultHeight, &hint,
    559                 &numPendingBuffers);
    560 
    561         // Disable transform hint if sticky transform is set.
    562         if (mStickyTransform == 0) {
    563             mTransformHint = hint;
    564         }
    565 
    566         mConsumerRunningBehind = (numPendingBuffers >= 2);
    567     }
    568     if (!err && api == NATIVE_WINDOW_API_CPU) {
    569         mConnectedToCpu = true;
    570     }
    571     return err;
    572 }
    573 
    574 
    575 int Surface::disconnect(int api) {
    576     ATRACE_CALL();
    577     ALOGV("Surface::disconnect");
    578     Mutex::Autolock lock(mMutex);
    579     freeAllBuffers();
    580     int err = mGraphicBufferProducer->disconnect(api);
    581     if (!err) {
    582         mReqFormat = 0;
    583         mReqWidth = 0;
    584         mReqHeight = 0;
    585         mReqUsage = 0;
    586         mCrop.clear();
    587         mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
    588         mTransform = 0;
    589         mStickyTransform = 0;
    590 
    591         if (api == NATIVE_WINDOW_API_CPU) {
    592             mConnectedToCpu = false;
    593         }
    594     }
    595     return err;
    596 }
    597 
    598 int Surface::setUsage(uint32_t reqUsage)
    599 {
    600     ALOGV("Surface::setUsage");
    601     Mutex::Autolock lock(mMutex);
    602     mReqUsage = reqUsage;
    603     return OK;
    604 }
    605 
    606 int Surface::setCrop(Rect const* rect)
    607 {
    608     ATRACE_CALL();
    609 
    610     Rect realRect;
    611     if (rect == NULL || rect->isEmpty()) {
    612         realRect.clear();
    613     } else {
    614         realRect = *rect;
    615     }
    616 
    617     ALOGV("Surface::setCrop rect=[%d %d %d %d]",
    618             realRect.left, realRect.top, realRect.right, realRect.bottom);
    619 
    620     Mutex::Autolock lock(mMutex);
    621     mCrop = realRect;
    622     return NO_ERROR;
    623 }
    624 
    625 int Surface::setBufferCount(int bufferCount)
    626 {
    627     ATRACE_CALL();
    628     ALOGV("Surface::setBufferCount");
    629     Mutex::Autolock lock(mMutex);
    630 
    631     status_t err = mGraphicBufferProducer->setBufferCount(bufferCount);
    632     ALOGE_IF(err, "IGraphicBufferProducer::setBufferCount(%d) returned %s",
    633             bufferCount, strerror(-err));
    634 
    635     if (err == NO_ERROR) {
    636         freeAllBuffers();
    637     }
    638 
    639     return err;
    640 }
    641 
    642 int Surface::setBuffersDimensions(int w, int h)
    643 {
    644     ATRACE_CALL();
    645     ALOGV("Surface::setBuffersDimensions");
    646 
    647     if (w<0 || h<0)
    648         return BAD_VALUE;
    649 
    650     if ((w && !h) || (!w && h))
    651         return BAD_VALUE;
    652 
    653     Mutex::Autolock lock(mMutex);
    654     mReqWidth = w;
    655     mReqHeight = h;
    656     return NO_ERROR;
    657 }
    658 
    659 int Surface::setBuffersUserDimensions(int w, int h)
    660 {
    661     ATRACE_CALL();
    662     ALOGV("Surface::setBuffersUserDimensions");
    663 
    664     if (w<0 || h<0)
    665         return BAD_VALUE;
    666 
    667     if ((w && !h) || (!w && h))
    668         return BAD_VALUE;
    669 
    670     Mutex::Autolock lock(mMutex);
    671     mUserWidth = w;
    672     mUserHeight = h;
    673     return NO_ERROR;
    674 }
    675 
    676 int Surface::setBuffersFormat(int format)
    677 {
    678     ALOGV("Surface::setBuffersFormat");
    679 
    680     if (format<0)
    681         return BAD_VALUE;
    682 
    683     Mutex::Autolock lock(mMutex);
    684     mReqFormat = format;
    685     return NO_ERROR;
    686 }
    687 
    688 int Surface::setScalingMode(int mode)
    689 {
    690     ATRACE_CALL();
    691     ALOGV("Surface::setScalingMode(%d)", mode);
    692 
    693     switch (mode) {
    694         case NATIVE_WINDOW_SCALING_MODE_FREEZE:
    695         case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
    696         case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
    697             break;
    698         default:
    699             ALOGE("unknown scaling mode: %d", mode);
    700             return BAD_VALUE;
    701     }
    702 
    703     Mutex::Autolock lock(mMutex);
    704     mScalingMode = mode;
    705     return NO_ERROR;
    706 }
    707 
    708 int Surface::setBuffersTransform(int transform)
    709 {
    710     ATRACE_CALL();
    711     ALOGV("Surface::setBuffersTransform");
    712     Mutex::Autolock lock(mMutex);
    713     mTransform = transform;
    714     return NO_ERROR;
    715 }
    716 
    717 int Surface::setBuffersStickyTransform(int transform)
    718 {
    719     ATRACE_CALL();
    720     ALOGV("Surface::setBuffersStickyTransform");
    721     Mutex::Autolock lock(mMutex);
    722     mStickyTransform = transform;
    723     return NO_ERROR;
    724 }
    725 
    726 int Surface::setBuffersTimestamp(int64_t timestamp)
    727 {
    728     ALOGV("Surface::setBuffersTimestamp");
    729     Mutex::Autolock lock(mMutex);
    730     mTimestamp = timestamp;
    731     return NO_ERROR;
    732 }
    733 
    734 void Surface::freeAllBuffers() {
    735     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
    736         mSlots[i].buffer = 0;
    737     }
    738 }
    739 
    740 // ----------------------------------------------------------------------
    741 // the lock/unlock APIs must be used from the same thread
    742 
    743 static status_t copyBlt(
    744         const sp<GraphicBuffer>& dst,
    745         const sp<GraphicBuffer>& src,
    746         const Region& reg)
    747 {
    748     // src and dst with, height and format must be identical. no verification
    749     // is done here.
    750     status_t err;
    751     uint8_t const * src_bits = NULL;
    752     err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(), (void**)&src_bits);
    753     ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
    754 
    755     uint8_t* dst_bits = NULL;
    756     err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(), (void**)&dst_bits);
    757     ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
    758 
    759     Region::const_iterator head(reg.begin());
    760     Region::const_iterator tail(reg.end());
    761     if (head != tail && src_bits && dst_bits) {
    762         const size_t bpp = bytesPerPixel(src->format);
    763         const size_t dbpr = dst->stride * bpp;
    764         const size_t sbpr = src->stride * bpp;
    765 
    766         while (head != tail) {
    767             const Rect& r(*head++);
    768             ssize_t h = r.height();
    769             if (h <= 0) continue;
    770             size_t size = r.width() * bpp;
    771             uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
    772             uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
    773             if (dbpr==sbpr && size==sbpr) {
    774                 size *= h;
    775                 h = 1;
    776             }
    777             do {
    778                 memcpy(d, s, size);
    779                 d += dbpr;
    780                 s += sbpr;
    781             } while (--h > 0);
    782         }
    783     }
    784 
    785     if (src_bits)
    786         src->unlock();
    787 
    788     if (dst_bits)
    789         dst->unlock();
    790 
    791     return err;
    792 }
    793 
    794 // ----------------------------------------------------------------------------
    795 
    796 status_t Surface::lock(
    797         ANativeWindow_Buffer* outBuffer, ARect* inOutDirtyBounds)
    798 {
    799     if (mLockedBuffer != 0) {
    800         ALOGE("Surface::lock failed, already locked");
    801         return INVALID_OPERATION;
    802     }
    803 
    804     if (!mConnectedToCpu) {
    805         int err = Surface::connect(NATIVE_WINDOW_API_CPU);
    806         if (err) {
    807             return err;
    808         }
    809         // we're intending to do software rendering from this point
    810         setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
    811     }
    812 
    813     ANativeWindowBuffer* out;
    814     int fenceFd = -1;
    815     status_t err = dequeueBuffer(&out, &fenceFd);
    816     ALOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
    817     if (err == NO_ERROR) {
    818         sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
    819         const Rect bounds(backBuffer->width, backBuffer->height);
    820 
    821         Region newDirtyRegion;
    822         if (inOutDirtyBounds) {
    823             newDirtyRegion.set(static_cast<Rect const&>(*inOutDirtyBounds));
    824             newDirtyRegion.andSelf(bounds);
    825         } else {
    826             newDirtyRegion.set(bounds);
    827         }
    828 
    829         // figure out if we can copy the frontbuffer back
    830         const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
    831         const bool canCopyBack = (frontBuffer != 0 &&
    832                 backBuffer->width  == frontBuffer->width &&
    833                 backBuffer->height == frontBuffer->height &&
    834                 backBuffer->format == frontBuffer->format);
    835 
    836         if (canCopyBack) {
    837             // copy the area that is invalid and not repainted this round
    838             const Region copyback(mDirtyRegion.subtract(newDirtyRegion));
    839             if (!copyback.isEmpty())
    840                 copyBlt(backBuffer, frontBuffer, copyback);
    841         } else {
    842             // if we can't copy-back anything, modify the user's dirty
    843             // region to make sure they redraw the whole buffer
    844             newDirtyRegion.set(bounds);
    845             mDirtyRegion.clear();
    846             Mutex::Autolock lock(mMutex);
    847             for (size_t i=0 ; i<NUM_BUFFER_SLOTS ; i++) {
    848                 mSlots[i].dirtyRegion.clear();
    849             }
    850         }
    851 
    852 
    853         { // scope for the lock
    854             Mutex::Autolock lock(mMutex);
    855             int backBufferSlot(getSlotFromBufferLocked(backBuffer.get()));
    856             if (backBufferSlot >= 0) {
    857                 Region& dirtyRegion(mSlots[backBufferSlot].dirtyRegion);
    858                 mDirtyRegion.subtract(dirtyRegion);
    859                 dirtyRegion = newDirtyRegion;
    860             }
    861         }
    862 
    863         mDirtyRegion.orSelf(newDirtyRegion);
    864         if (inOutDirtyBounds) {
    865             *inOutDirtyBounds = newDirtyRegion.getBounds();
    866         }
    867 
    868         void* vaddr;
    869         status_t res = backBuffer->lockAsync(
    870                 GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
    871                 newDirtyRegion.bounds(), &vaddr, fenceFd);
    872 
    873         ALOGW_IF(res, "failed locking buffer (handle = %p)",
    874                 backBuffer->handle);
    875 
    876         if (res != 0) {
    877             err = INVALID_OPERATION;
    878         } else {
    879             mLockedBuffer = backBuffer;
    880             outBuffer->width  = backBuffer->width;
    881             outBuffer->height = backBuffer->height;
    882             outBuffer->stride = backBuffer->stride;
    883             outBuffer->format = backBuffer->format;
    884             outBuffer->bits   = vaddr;
    885         }
    886     }
    887     return err;
    888 }
    889 
    890 status_t Surface::unlockAndPost()
    891 {
    892     if (mLockedBuffer == 0) {
    893         ALOGE("Surface::unlockAndPost failed, no locked buffer");
    894         return INVALID_OPERATION;
    895     }
    896 
    897     int fd = -1;
    898     status_t err = mLockedBuffer->unlockAsync(&fd);
    899     ALOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
    900 
    901     err = queueBuffer(mLockedBuffer.get(), fd);
    902     ALOGE_IF(err, "queueBuffer (handle=%p) failed (%s)",
    903             mLockedBuffer->handle, strerror(-err));
    904 
    905     mPostedBuffer = mLockedBuffer;
    906     mLockedBuffer = 0;
    907     return err;
    908 }
    909 
    910 }; // namespace android
    911